问:
Dynamic table display using kivy and sqlite 3
I am working on a GUI to manage inventory (Python 3.4, Sqlite3 and Kivy 1.9.1) and the idea is to be able to recognize products based on their different features, which are listed in a database.

Is there a way to display a sqlite table using kivy ? I think a ListView could be the solution but I am really struggling to understand how to make a CustomListItem with the right args_converter to get several columns with different labels in them.

答:
Slightly modifying the original solution from @el3ien for better look and feel :-</p>

```<code>import sqlite3 as lite

con = lite.connect('test.db')
cur = con.cursor()

try:
    with con:
        cur.execute("CREATE TABLE Cars(Id INT, Name TEXT, Price INT)")
        cur.execute("INSERT INTO Cars VALUES(1,'Audi',52642)")
        cur.execute("INSERT INTO Cars VALUES(2,'Mercedes',57127)")
        cur.execute("INSERT INTO Cars VALUES(3,'Skoda',9000)")
        cur.execute("INSERT INTO Cars VALUES(4,'Volvo',29000)")
        cur.execute("INSERT INTO Cars VALUES(5,'Bentley',350000)")
        cur.execute("INSERT INTO Cars VALUES(6,'Citroen',21000)")
        cur.execute("INSERT INTO Cars VALUES(7,'Hummer',41400)")
        cur.execute("INSERT INTO Cars VALUES(8,'Volkswagen',21600)")
except:
    pass

from kivy.uix.boxlayout import BoxLayout
from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.properties import ListProperty

Builder.load_string("""

<MyLayout>:
    orientation: "vertical"
    BoxLayout:
        size_hint_y: 0.1
        Label:
            text: 'ID'
        Label:
            text: 'Brand'
        Label:
            text: 'Km'
    BoxLayout:
        RecycleView:
            data: [{'text':"{}".format(id)} for id,name,km in root.rows]
            viewclass: "Label"
            RecycleBoxLayout:
                default_size: None, dp(56)
                default_size_hint: 1, None
                size_hint_y: None
                height: self.minimum_height
                orientation: "vertical"
        RecycleView:
            data: [{'text':"{}".format(name)} for id,name,km in root.rows]
            viewclass: "Label"
            RecycleBoxLayout:
                default_size: None, dp(56)
                orientation: "vertical"
                default_size_hint: 1, None
                size_hint_y: None
                height: self.minimum_height
        RecycleView:
            data: [{'text':"{}".format(km)} for id,name,km in root.rows]
            viewclass: "Label"
            RecycleBoxLayout:
                default_size: None, dp(56)
                orientation: "vertical"
                default_size_hint: 1, None
                size_hint_y: None
                height: self.minimum_height
    Button:
        size_hint_y: 0.1
        text: "Get data"
        on_press: root.get_data()

""")

class MyLayout(BoxLayout):
    rows = ListProperty([("Id","Brand","Km Run")])
    def get_data(self):
        cur.execute("SELECT * FROM Cars")
        self.rows = cur.fetchall()
        print(self.rows)

runTouchApp(MyLayout())
</code>```

Body:
Slightly modifying the original solution from @el3ien for better look and feel :-

import sqlite3 as lite

con = lite.connect('test.db')
cur = con.cursor()

try:
    with con:
        cur.execute("CREATE TABLE Cars(Id INT, Name TEXT, Price INT)")
        cur.execute("INSERT INTO Cars VALUES(1,'Audi',52642)")
        cur.execute("INSERT INTO Cars VALUES(2,'Mercedes',57127)")
        cur.execute("INSERT INTO Cars VALUES(3,'Skoda',9000)")
        cur.execute("INSERT INTO Cars VALUES(4,'Volvo',29000)")
        cur.execute("INSERT INTO Cars VALUES(5,'Bentley',350000)")
        cur.execute("INSERT INTO Cars VALUES(6,'Citroen',21000)")
        cur.execute("INSERT INTO Cars VALUES(7,'Hummer',41400)")
        cur.execute("INSERT INTO Cars VALUES(8,'Volkswagen',21600)")
except:
    pass

from kivy.uix.boxlayout import BoxLayout
from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.properties import ListProperty

Builder.load_string("""

<MyLayout>:
    orientation: "vertical"
    BoxLayout:
        size_hint_y: 0.1
        Label:
            text: 'ID'
        Label:
            text: 'Brand'
        Label:
            text: 'Km'
    BoxLayout:
        RecycleView:
            data: [{'text':"{}".format(id)} for id,name,km in root.rows]
            viewclass: "Label"
            RecycleBoxLayout:
                default_size: None, dp(56)
                default_size_hint: 1, None
                size_hint_y: None
                height: self.minimum_height
                orientation: "vertical"
        RecycleView:
            data: [{'text':"{}".format(name)} for id,name,km in root.rows]
            viewclass: "Label"
            RecycleBoxLayout:
                default_size: None, dp(56)
                orientation: "vertical"
                default_size_hint: 1, None
                size_hint_y: None
                height: self.minimum_height
        RecycleView:
            data: [{'text':"{}".format(km)} for id,name,km in root.rows]
            viewclass: "Label"
            RecycleBoxLayout:
                default_size: None, dp(56)
                orientation: "vertical"
                default_size_hint: 1, None
                size_hint_y: None
                height: self.minimum_height
    Button:
        size_hint_y: 0.1
        text: "Get data"
        on_press: root.get_data()

""")

class MyLayout(BoxLayout):
    rows = ListProperty([("Id","Brand","Km Run")])
    def get_data(self):
        cur.execute("SELECT * FROM Cars")
        self.rows = cur.fetchall()
        print(self.rows)

runTouchApp(MyLayout())


来源: stackexchange

问:
Node Express Router /users/:id vs /users/login
I am building a restful api with a path /users/:id (for viewing a user's information) and /users/login (for logging in with credentials).
How do I prevent /users/:id only called when :id is a number? Is this even a good approach for building a restful api?

One way I could do it is I create a /users/:id route and inside I check if id is a number, otherwise switch between cases of login, signup, etc. Is this the right approach?

答:
You can use the (\\d+) expression:

```<code>const route = Router();

router.get('user/:id(\\d+)');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use the (\\d+) expression:

const route = Router();

router.get('user/:id(\\d+)');


问:
Finding the number of X11 screens from Haskell
I'd like to know how many X screens the current machine has, to make my .xmonad a little more general; I have a netbook as well as a desktop with two monitors, and I use several single monitored machines too.

To this end, I'd like to be able to find out how many X screens the current machine has. (I think screens is the correct words, I mean physical monitors).

The reason being is that I want multiple instances of xmobar, one per monitor. I've hard coded it to be on two at the moment.

答:
For the curious, I ended up using  </p>

```<code> screenCount :: X Int
 screenCount = withDisplay (io.fmap length.getScreenInfo)
</code>```

<p>I also found out that the XMonad module has a function  </p>

```<code> screenCount :: Display -> Foreign.C.Types.CInt
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For the curious, I ended up using

 screenCount :: X Int
 screenCount = withDisplay (io.fmap length.getScreenInfo)

I also found out that the XMonad module has a function

 screenCount :: Display -> Foreign.C.Types.CInt


问:
Question about Self Joins. Seeing if two users interacted
I was given a SQL assignment that is the following table simulating a dating app: Table name = dating

```<code>user_id | viewing_profile_id | date | liked
   1              2             x       yes
   1              3             x       yes
   2              1             x       yes
   2              3             x       no
   3              1             x       no
   3              2             x       no
</code>```

essentially I want to see the % of profiles that match each other. a match is when both profiles like each other.

I think I know what I have to do. Perform a Self join onto the table itself and use a case when for when the profiles like each other.

```<code>select t.date, sum(t.match) / count(t.match) as p_match
from (
select s1.user_id, s1.viewing_profile_id,
date_trunc('day',s1.date) as date, case when s1.liked = 'yes'
and s2.liked = 'yes' then 1 else 0 end as match
from dating s1
left join dating s2 on s2.ser_id = s1.viewing_profile_id
group by 1,2) t
group by 1
</code>```

Since this is just a made up table, and I do not have any data execute this on, I was wondering if I can get some insight into whether or not this would work.

I am expecting the subquery to produce something like the following:

```<code>user_id | viewing_profile_id | date | match
   1              2             x       1
   1              3             x       0
   2              1             x       1
   2              3             x       0
   3              1             x       0
   3              2             x       0
</code>```

答:
```<code>/* for matched users*/
SELECT *
FROM user viewed, user viewing
WHERE viewed.user_id = viewing.viewing_profile_id
and viewed.liked='yes'
and viewing.liked='yes'

/* for Match_Percentage */
SELECT
(SELECT count(*)
FROM user viewed, user viewing
WHERE viewed.user_id = viewing.viewing_profile_id
and viewed.liked='yes'
and viewing.liked='yes')
/
(SELECT count(*) FROM user)
*100 as Match_Percentage
FROM dual;
</code>```

Body:
I was given a SQL assignment that is the following table simulating a dating app: Table name = dating

user_id | viewing_profile_id | date | liked
   1              2             x       yes
   1              3             x       yes
   2              1             x       yes
   2              3             x       no
   3              1             x       no
   3              2             x       no

essentially I want to see the % of profiles that match each other. a match is when both profiles like each other.

I think I know what I have to do. Perform a Self join onto the table itself and use a case when for when the profiles like each other.

select t.date, sum(t.match) / count(t.match) as p_match
from (
select s1.user_id, s1.viewing_profile_id,
date_trunc('day',s1.date) as date, case when s1.liked = 'yes'
and s2.liked = 'yes' then 1 else 0 end as match
from dating s1
left join dating s2 on s2.ser_id = s1.viewing_profile_id
group by 1,2) t
group by 1

Since this is just a made up table, and I do not have any data execute this on, I was wondering if I can get some insight into whether or not this would work.

I am expecting the subquery to produce something like the following:

user_id | viewing_profile_id | date | match
   1              2             x       1
   1              3             x       0
   2              1             x       1
   2              3             x       0
   3              1             x       0
   3              2             x       0


问:
Java streams, wait for Google distance matrix to return result
I have a list of vehicles that I need to calculate the total fuel used per vehicle. I am using Java streams to loop through the list, get a vehicle, calculate its distance using the Google distance matrix api, use the distance to calculate fuel usage and return a response. I have noticed that the program just hangs most likely it could be that the stream does not wait for the Matrix api to return a response before it moves to the next item, I say this because I have put system.out.println calls in the Matrix method and some messages do not get printed.

The code that is suppose to calculate total fuel usage

```<code>vehicles.stream().map(vehicles ->
                calculateTotalFuelBeingUsedByAllVehicles(vehicle, getDistanceBetweenOriginsAndDestination(
                        new LatLng(vehicle.getOrigin().getLatitude(), vehicle.getOrigin().getLatitude()), new LatLng(vehicle.getDestination().getLatitude(), vehicles.getDestination().getLatitude()))))
                .collect(Collectors.toList());
</code>```

```<code>    public static double getDistanceBetweenOriginsAndDestination(LatLng origin, LatLng destination){
        //Gets printed
        System.out.println("Calculating distance");
        GeoApiContext context = new GeoApiContext.Builder()
                .apiKey(GOOGLE_MAPS_API_KEY)
                .build();
        DistanceMatrixApiRequest distanceMatrixApiRequest = DistanceMatrixApi.newRequest(context)
                .mode(TravelMode.DRIVING)
                .trafficModel(TrafficModel.BEST_GUESS)
                .departureTime(Instant.now().atZone(ZoneOffset.UTC).toInstant())
                .destinations(destination)
                .origins(origin);
        try {

            long distance =  Arrays.stream(distanceMatrixApiRequest.await().rows)
                    .flatMap(distanceMatrixRow -> Arrays.stream(distanceMatrixRow.elements))
                    .mapToLong(distanceMatrixElement -> distanceMatrixElement.distance.inMeters)
                    .sum();

            //Never gets printed
            System.out.println("Calculated distance: "+distance);
            return distance;

        } catch (ApiException | InterruptedException | IOException e) {
            //Never gets printed
            System.out.println("Error encountered when calculating distance");
            e.printStackTrace();
        }
        return 0;
    }
</code>```

In the getDistanceBetweenOriginsAndDestination the System.out.println("Calculating distance") gets printed and the rest are not.

答: You have a typo at the creation of LatLng, you send latitude instead of longitude. It may be Google doesn't respond you or takes a lot of time to respond, because it is impossible to calculate a route between these points.</p>

Body:
I have a list of vehicles that I need to calculate the total fuel used per vehicle. I am using Java streams to loop through the list, get a vehicle, calculate its distance using the Google distance matrix api, use the distance to calculate fuel usage and return a response. I have noticed that the program just hangs most likely it could be that the stream does not wait for the Matrix api to return a response before it moves to the next item, I say this because I have put system.out.println calls in the Matrix method and some messages do not get printed.

The code that is suppose to calculate total fuel usage

vehicles.stream().map(vehicles ->
                calculateTotalFuelBeingUsedByAllVehicles(vehicle, getDistanceBetweenOriginsAndDestination(
                        new LatLng(vehicle.getOrigin().getLatitude(), vehicle.getOrigin().getLatitude()), new LatLng(vehicle.getDestination().getLatitude(), vehicles.getDestination().getLatitude()))))
                .collect(Collectors.toList());

    public static double getDistanceBetweenOriginsAndDestination(LatLng origin, LatLng destination){
        //Gets printed
        System.out.println("Calculating distance");
        GeoApiContext context = new GeoApiContext.Builder()
                .apiKey(GOOGLE_MAPS_API_KEY)
                .build();
        DistanceMatrixApiRequest distanceMatrixApiRequest = DistanceMatrixApi.newRequest(context)
                .mode(TravelMode.DRIVING)
                .trafficModel(TrafficModel.BEST_GUESS)
                .departureTime(Instant.now().atZone(ZoneOffset.UTC).toInstant())
                .destinations(destination)
                .origins(origin);
        try {

            long distance =  Arrays.stream(distanceMatrixApiRequest.await().rows)
                    .flatMap(distanceMatrixRow -> Arrays.stream(distanceMatrixRow.elements))
                    .mapToLong(distanceMatrixElement -> distanceMatrixElement.distance.inMeters)
                    .sum();

            //Never gets printed
            System.out.println("Calculated distance: "+distance);
            return distance;

        } catch (ApiException | InterruptedException | IOException e) {
            //Never gets printed
            System.out.println("Error encountered when calculating distance");
            e.printStackTrace();
        }
        return 0;
    }

In the getDistanceBetweenOriginsAndDestination the System.out.println("Calculating distance") gets printed and the rest are not.


问:
In place reinitialization of objects
I'm working on an embedded system, where memory is scarce, and more importantly, since there's a soft realtime constraint (i.e. it's a bug if we don't make the deadline, but no one dies), I cannot use dynamic memory allocation.

However, there's the occasional need to re-initialize a subsystem, and there's been a number of bugs related to not-quite-everything getting either cleaned up or reset correctly. This is of course exactly the problem that constructors and destructors are supposed to solve, but since we don't allocate dynamically, we can't use the idiom where we'd destruct the object and then allocate a new one from scratch (mostly the objects of relevance here are globals).

So in the end there's usually setup code in a constructor, and a reinitialize -type function, which resemble each other but are not identical, since the reinitialize function also does a lot of what a destructor would do.

One way out that I'm thinking of is to write a "renew" -template (this is just a draft, may contain erors and possibly not complet):

```<code>template<typename T, typename .. Args>
void renew(T & obj, Args&&... args) {
  obj.~T();
  new(&obj) T(std::forward<Args>(args)...);
}
</code>```

which could be used to reinitialize non-dynamically alloctated variables. So for example

```<code>A a{17};
... //Do something with a
renew(a, 14);
...//work with the new a, no need to reallocate memory
</code>```

This would allow getting some of the advantages of constructors and destructors (primarily single way to initialize and deinitialize an object) without dynamic memory allocation. Note that the usage above is simplified, in practice this would mostly be used in very specific points in the main loop and on global objects representing the actual physical subsystems.

Question: is this a sensible way of going about it? Or is there a better alternative?

There's a very similar question here Calling a constructor to re-initialize object. I'm asking much the same thing but specifically in context of embedded programming, where I can't do things the usual way with dynamic allocation.

答:
The only reason I see were you would like to your the construction you propose is where the new class would be of a different derived type. But in this case you would have to be really be careful to use the exact same amount of memory, not to override following variables. I know of one example where this is used in mbed. It used to retype their function callbacks, search for "new" and you will various examples.

I am wondering if you have considered using a "clear" function in your class? In my honest opinion as far as I can see now this would be the easiest solution.

An alternative solution would be to write a memory manager which has a fixed buffer size. From this buffer you can then "dynamically" allocate memory. I do not think this is the solution you are looking for as this is more useful for when you often need to allocate and deallocate multiple objects.

Title: In place reinitialization of objects

Body:
I'm working on an embedded system, where memory is scarce, and more importantly, since there's a soft realtime constraint (i.e. it's a bug if we don't make the deadline, but no one dies), I cannot use dynamic memory allocation.

However, there's the occasional need to re-initialize a subsystem, and there's been a number of bugs related to not-quite-everything getting either cleaned up or reset correctly. This is of course exactly the problem that constructors and destructors are supposed to solve, but since we don't allocate dynamically, we can't use the idiom where we'd destruct the object and then allocate a new one from scratch (mostly the objects of relevance here are globals).

So in the end there's usually setup code in a constructor, and a reinitialize -type function, which resemble each other but are not identical, since the reinitialize function also does a lot of what a destructor would do.

One way out that I'm thinking of is to write a "renew" -template (this is just a draft, may contain erors and possibly not complet):

template<typename T, typename .. Args>
void renew(T & obj, Args&&... args) {
  obj.~T();
  new(&obj) T(std::forward<Args>(args)...);
}

which could be used to reinitialize non-dynamically alloctated variables. So for example

A a{17};
... //Do something with a
renew(a, 14);
...//work with the new a, no need to reallocate memory

This would allow getting some of the advantages of constructors and destructors (primarily single way to initialize and deinitialize an object) without dynamic memory allocation. Note that the usage above is simplified, in practice this would mostly be used in very specific points in the main loop and on global objects representing the actual physical subsystems.

Question: is this a sensible way of going about it? Or is there a better alternative?

There's a very similar question here Calling a constructor to re-initialize object. I'm asking much the same thing but specifically in context of embedded programming, where I can't do things the usual way with dynamic allocation.


问:
How to extract address in excel?
I have addresses in one cell and I want to extract them in different cells on the same row. Some cells have four lines of address and some have three. I am able to easily split using text to column and various delimiters for the ones with three but not the ones with four.

enter image description here

In the first example I have four lines and second has three

```<code>Anchorage Oncology Centre
3801 University Lake Drive
Suite 300-B2
Anchorage, AK 99508 US
</code>```

I would like the above as split into 5 cells. One cell each for address, City, State, Zip code and country

```<code>Anchorage Oncology Centre
3801 University Lake Drive
Suite 300-B2

Anchorage

AK

99508

US
</code>```

in second example below

```<code>Providence Alaska Medical Center
3200 Providence Drive
Anchorage, AK 99508 US
</code>```

I would like

```<code>Providence Alaska Medical Center
3200 Providence Drive

Anchorage

AK

99508

US
</code>```

Could this be done using a formula?

What I have done so far is that the full address is in cell A1 and I want them in B1, C1, D1, E1, and F1. What i have done is for the country I use =RIGHT(A2,2), zip code, i use =MID(A2, LEN(A2)-7, 5), state =MID(A2, LEN(A2)-10, 2). Now I am trying to extract the city. The city is before the comma and after the line break (Char(10)) and Address is first 2 or 3 lines. I don't know how to do that.

There is a line break between each line.

Thank you

答:
A possible solution would be

```<code>=IF(ROW(A1)<SUMPRODUCT((A$1:A$7<>"")*1),A1,TRIM(MID(SUBSTITUTE(SUBSTITUTE(INDEX(A$1:A$7,SUMPRODUCT((A$1:A$7<>"")*1)),",",)," ",REPT(" ",999)),(ROW(X1)-SUMPRODUCT((A$1:A$7<>"")*1)+1)*999-998,999)))
</code>```

The split part is from here:

```<code>=TRIM(MID(SUBSTITUTE(A$2," ",REPT(" ",999)),ROW(X1)*999-998,999))
</code>```

I have added some calculations to find the last row and eliminate commas:

```<code>SUBSTITUTE(INDEX(A$1:A$7,SUMPRODUCT((A$1:A$7<>"")*1)),",",)
</code>```

If all the adresses are located in the first row, then u can insert the formula below the adress in column one and copy it down and to the right. Currently the address can have 7 lines, so u have to copy it at least to line 8.

Title: How to extract address in excel?

Body:
I have addresses in one cell and I want to extract them in different cells on the same row. Some cells have four lines of address and some have three. I am able to easily split using text to column and various delimiters for the ones with three but not the ones with four.

enter image description here

In the first example I have four lines and second has three

Anchorage Oncology Centre
3801 University Lake Drive
Suite 300-B2
Anchorage, AK 99508 US

I would like the above as split into 5 cells. One cell each for address, City, State, Zip code and country

Anchorage Oncology Centre
3801 University Lake Drive
Suite 300-B2

Anchorage

AK

99508

US

in second example below

Providence Alaska Medical Center
3200 Providence Drive
Anchorage, AK 99508 US

I would like

Providence Alaska Medical Center
3200 Providence Drive

Anchorage

AK

99508

US

Could this be done using a formula?

What I have done so far is that the full address is in cell A1 and I want them in B1, C1, D1, E1, and F1. What i have done is for the country I use =RIGHT(A2,2), zip code, i use =MID(A2, LEN(A2)-7, 5), state =MID(A2, LEN(A2)-10, 2). Now I am trying to extract the city. The city is before the comma and after the line break (Char(10)) and Address is first 2 or 3 lines. I don't know how to do that.

There is a line break between each line.

Thank you

Body:
A possible solution would be

=IF(ROW(A1)<SUMPRODUCT((A$1:A$7<>"")*1),A1,TRIM(MID(SUBSTITUTE(SUBSTITUTE(INDEX(A$1:A$7,SUMPRODUCT((A$1:A$7<>"")*1)),",",)," ",REPT(" ",999)),(ROW(X1)-SUMPRODUCT((A$1:A$7<>"")*1)+1)*999-998,999)))

The split part is from here:

=TRIM(MID(SUBSTITUTE(A$2," ",REPT(" ",999)),ROW(X1)*999-998,999))

I have added some calculations to find the last row and eliminate commas:

SUBSTITUTE(INDEX(A$1:A$7,SUMPRODUCT((A$1:A$7<>"")*1)),",",)

If all the adresses are located in the first row, then u can insert the formula below the adress in column one and copy it down and to the right. Currently the address can have 7 lines, so u have to copy it at least to line 8.


问:
How can I create my own functions in October CMS?
The "global" means functions that I can call everywhere on pages and layouts without repeating them on every place where I should use them</p>

答:
You can create your own custom plugin and use registerMarkupTags inside Plugin.php</p>

```<code>public function registerMarkupTags()
{
    return [
        'functions' => [
            'currentUrl' => function () {
                return request()->getRequestUri();
            },
            'currentUrlFull' => function () {
                return URL::to(request()->getRequestUri());
            },
            'ip' => function () {
                return Request::ip();
            }
        ]
    ];
}
</code>```

Body:
You can create your own custom plugin and use registerMarkupTags inside Plugin.php

public function registerMarkupTags()
{
    return [
        'functions' => [
            'currentUrl' => function () {
                return request()->getRequestUri();
            },
            'currentUrlFull' => function () {
                return URL::to(request()->getRequestUri());
            },
            'ip' => function () {
                return Request::ip();
            }
        ]
    ];
}


问:
Invalid data. Expected a dictionary, but got bytes
when I request to save API, I got this error:
{
    "non_field_errors": [
        "Invalid data. Expected a dictionary, but got bytes."
    ]
}

models.py

```<code>from django.db import models

# Create your models here.
class employee(models.Model):
    name=models.CharField(max_length=10)
    surname=models.CharField(max_length=10)
    emo_id=models.IntegerField()

    class Meta:
        db_table = "employee"

    def __str__(self):
        return self.name
</code>```

```<code>serializer.py
from rest_framework import serializers
from .models import employee

class convertSerializers(serializers.ModelSerializer):
    class Meta:
        model = employee
        fields = '__all__' # for all field
</code>```

views.py

```<code>def saveEmployee(request):
    serializer = convertSerializers(data=request.body)
    print(serializer)
    if request.method == 'POST':
        if serializer.is_valid():
            serializer.save()
            return JsonResponse('saved successfull', safe=False)
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

答:
Since you're using DRF, you can use request.data instead of request.body

```<code><b>from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['POST'])</b>
def saveEmployee(request):
    serializer = convertSerializers(<b>data=request.data</b>)
    <b>serializer.is_valid(True)
    serializer.save()
    return Response('saved successful')</b></code>```

Body:
when I request to save API, I got this error:
{
    "non_field_errors": [
        "Invalid data. Expected a dictionary, but got bytes."
    ]
}

models.py

from django.db import models

# Create your models here.
class employee(models.Model):
    name=models.CharField(max_length=10)
    surname=models.CharField(max_length=10)
    emo_id=models.IntegerField()

    class Meta:
        db_table = "employee"

    def __str__(self):
        return self.name

serializer.py
from rest_framework import serializers
from .models import employee

class convertSerializers(serializers.ModelSerializer):
    class Meta:
        model = employee
        fields = '__all__' # for all field

views.py

def saveEmployee(request):
    serializer = convertSerializers(data=request.body)
    print(serializer)
    if request.method == 'POST':
        if serializer.is_valid():
            serializer.save()
            return JsonResponse('saved successfull', safe=False)
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Body:
Since you're using DRF, you can use request.data instead of request.body

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['POST'])
def saveEmployee(request):
    serializer = convertSerializers(data=request.data)
    serializer.is_valid(True)
    serializer.save()
    return Response('saved successful')


问:
FastAPI websocket can not connect
I am trying to let my Vue.js app communicate with my FastAPI(based on starlette) local server using websockets. I tried using the exact same code as in their example: https://fastapi.tiangolo.com/tutorial/websockets/. However something weird happens, because my server can not start with the reason: AttributeError: 'FastAPI' object has no attribute 'websocket'. That is strange because this exact code is the official docs of FastAPI.

After that I used the Starlette example code: https://www.starlette.io/websockets/. However when I try to connect to it, the FastApi prints to the terminal: WARNING: Invalid HTTP request received.

I tried using another client, the Simple WebSocket Client: https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo, but the same error appears on the terminal.

What am I doing wrong here? In the first place I find it weird that the FastAPI code does not seem to work on my computer, does anyone know why?

Thanks in advance!

答: Apparently the WebSocket functionality was added in FastAPI 0.24, which was just released. I was using an older version.</p>

Title: FastAPI websocket can not connect


问:
The requested package ... could not be found in any version
When I want to require my project, the following errors shows up:

The requested package mvc-php/framework could not be found in any version, there may be a typo in the package name.

The "mvc-php/framework" is a git folder.

```<code>{
    "name": "mvc-php/app",
    "repositories": [
        {
            "type": "path",
            "url": "/Users/youri/Documents/Github/framework"
        }
    ],
    "require": {
        "php": ">=7.0",
        "mvc-php/framework": "master"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    }
}
</code>```

Project i want to require:

```<code>{
    "name": "mvc-php/framework",
    "description": "PHP MVC framework",
    "autoload": {
        "psr-4": {
            "Mvc\\" : "src/"
        }
    },
    "require": {
        "php": ">=7.0"
    }
}
</code>```

答:
It is important to note that if you do not add your own mirror source to the global variable, an error will occur where the sub-scene is not found.
You can add this in composer.json:</p>

```<code>"repositories":[
 {
  "type":"composer",
  "url":"https://packag"
 }
],
</code>```

Body:
When I want to require my project, the following errors shows up:

The requested package mvc-php/framework could not be found in any version, there may be a typo in the package name.

The "mvc-php/framework" is a git folder.

{
    "name": "mvc-php/app",
    "repositories": [
        {
            "type": "path",
            "url": "/Users/youri/Documents/Github/framework"
        }
    ],
    "require": {
        "php": ">=7.0",
        "mvc-php/framework": "master"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    }
}

Project i want to require:

{
    "name": "mvc-php/framework",
    "description": "PHP MVC framework",
    "autoload": {
        "psr-4": {
            "Mvc\\" : "src/"
        }
    },
    "require": {
        "php": ">=7.0"
    }
}

Body:
It is important to note that if you do not add your own mirror source to the global variable, an error will occur where the sub-scene is not found.
You can add this in composer.json:

"repositories":[
 {
  "type":"composer",
  "url":"https://packag"
 }
],


问:
Find parent with defined attribute wuth LINQ
I have variable XElement content =

```<code>        "...
         <item text="Name-1" id="1" segment="1" secret-id="Find-Me">
            <item text="Name-1-1" id="1.1">
               <item text="Name-1-1-1" id="1.1.1" />
               <item text="Name-1-1-2" id="1.1.2" />
            </item>
         </item>
         ..."
</code>```

I have also an item with id = 1.1.2

I need to find the first parent of this item which has attribute segment="1" and get its secret-id

How to do this with LINQ?

答:
You mean the "closest ancestor"?

```<code>string secretId = element.Ancestors()
                         .Where(x => (string) x.Attribute("segment") == "1")
                         .Select(x => (string) x.Attribute("secret-id"))
                         .FirstOrDefault();
</code>```

The result will be null if either:

There are no ancestors with an attribute segment="1"

The element with that attribute has no secret-id attribute.

Body:
I have variable XElement content =

        "...
         <item text="Name-1" id="1" segment="1" secret-id="Find-Me">
            <item text="Name-1-1" id="1.1">
               <item text="Name-1-1-1" id="1.1.1" />
               <item text="Name-1-1-2" id="1.1.2" />
            </item>
         </item>
         ..."

I have also an item with id = 1.1.2

I need to find the first parent of this item which has attribute segment="1" and get its secret-id

How to do this with LINQ?

Body:
You mean the "closest ancestor"?

string secretId = element.Ancestors()
                         .Where(x => (string) x.Attribute("segment") == "1")
                         .Select(x => (string) x.Attribute("secret-id"))
                         .FirstOrDefault();

The result will be null if either:

There are no ancestors with an attribute segment="1"

The element with that attribute has no secret-id attribute.


问:
Module not found: Error: Can't resolve '../fonts/fontawesome-webfont.eot'
I am using Webpack 4 and installed "font-awesome": "^4.7.0" in package.json. Then I tried to import it into my index.scss as following:

```<code>@import '~font-awesome/scss/font-awesome.scss';
@import '~bootstrap/scss/bootstrap.scss';
</code>```

And I've got the following error message:

```<code>ERROR in ./src/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss)
    Module not found: Error: Can't resolve '../fonts/fontawesome-webfont.eot' in '/Volumes/Develop/react-reason/cockpit/src'
     @ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss 7:414-457

    ERROR in ./src/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss)
    Module not found: Error: Can't resolve '../fonts/fontawesome-webfont.eot?v=4.7.0' in '/Volumes/Develop/react-reason/cockpit/src'
     @ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss 7:332-383

    ERROR in ./src/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss)
    Module not found: Error: Can't resolve '../fonts/fontawesome-webfont.svg?v=4.7.0' in '/Volumes/Develop/react-reason/cockpit/src'
     @ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss 7:806-857

    ERROR in ./src/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss)
    Module not found: Error: Can't resolve '../fonts/fontawesome-webfont.ttf?v=4.7.0' in '/Volumes/Develop/react-reason/cockpit/src'
     @ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss 7:711-762

    ERROR in ./src/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss)
    Module not found: Error: Can't resolve '../fonts/fontawesome-webfont.woff2?v=4.7.0' in '/Volumes/Develop/react-reason/cockpit/src'
     @ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss 7:525-578

    ERROR in ./src/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss)
    Module not found: Error: Can't resolve '../fonts/fontawesome-webfont.woff?v=4.7.0' in '/Volumes/Develop/react-reason/cockpit/src'
     @ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss 7:619-671
</code>```

As you can see, bootstrap works fine, but font-awesome not.

The folder of downloaded font-awesome looks as following:

Do I miss some configuration?

Update
Import the css file like:

```<code>@import '~font-awesome/css/font-awesome.css';
</code>```

but import scss file like:

```<code>@import '~font-awesome/scss/font-awesome.scss';
</code>```

does not work why?

答:
I made it work with these steps:

create src/_variables.scss with content:

```<code>$fa-font-path: '../node_modules/font-awesome-sass/assets/fonts/font-awesome/';
</code>```

So I set the complete path beginning ../node_modules

and for completeness my src/styles.scss:

```<code>@import 'variables';
@import "../node_modules/font-awesome-sass/assets/stylesheets/font-awesome";
</code>```

(I'm using package font-awesome-sass so your path(s) may differ)

Body:
I am using Webpack 4 and installed "font-awesome": "^4.7.0" in package.json. Then I tried to import it into my index.scss as following:

@import '~font-awesome/scss/font-awesome.scss';
@import '~bootstrap/scss/bootstrap.scss';

And I've got the following error message:

ERROR in ./src/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss)
    Module not found: Error: Can't resolve '../fonts/fontawesome-webfont.eot' in '/Volumes/Develop/react-reason/cockpit/src'
     @ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss 7:414-457

    ERROR in ./src/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss)
    Module not found: Error: Can't resolve '../fonts/fontawesome-webfont.eot?v=4.7.0' in '/Volumes/Develop/react-reason/cockpit/src'
     @ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss 7:332-383

    ERROR in ./src/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss)
    Module not found: Error: Can't resolve '../fonts/fontawesome-webfont.svg?v=4.7.0' in '/Volumes/Develop/react-reason/cockpit/src'
     @ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss 7:806-857

    ERROR in ./src/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss)
    Module not found: Error: Can't resolve '../fonts/fontawesome-webfont.ttf?v=4.7.0' in '/Volumes/Develop/react-reason/cockpit/src'
     @ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss 7:711-762

    ERROR in ./src/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss)
    Module not found: Error: Can't resolve '../fonts/fontawesome-webfont.woff2?v=4.7.0' in '/Volumes/Develop/react-reason/cockpit/src'
     @ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss 7:525-578

    ERROR in ./src/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss)
    Module not found: Error: Can't resolve '../fonts/fontawesome-webfont.woff?v=4.7.0' in '/Volumes/Develop/react-reason/cockpit/src'
     @ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/index.scss 7:619-671

As you can see, bootstrap works fine, but font-awesome not.

The folder of downloaded font-awesome looks as following:

Do I miss some configuration?

Update
Import the css file like:

@import '~font-awesome/css/font-awesome.css';

but import scss file like:

@import '~font-awesome/scss/font-awesome.scss';

does not work why?

Body:
I made it work with these steps:

create src/_variables.scss with content:

$fa-font-path: '../node_modules/font-awesome-sass/assets/fonts/font-awesome/';

So I set the complete path beginning ../node_modules

and for completeness my src/styles.scss:

@import 'variables';
@import "../node_modules/font-awesome-sass/assets/stylesheets/font-awesome";

(I'm using package font-awesome-sass so your path(s) may differ)


问:
Is there a more efficient way to run three statsby regressions with different reference groups?
I want to run these three regressions. Note that each has a different reference group, which is why I run them separately.

statsby _b, by(grp_iden) saving(reg_aaa.dta, replace): reg prezzo ib43.city_str i.marca_str, baselevels

statsby _b, by(grp_iden) saving(reg_bbb.dta, replace): reg prezzo ib6.city_str i.marca_str, baselevels

statsby _b, by(grp_iden) saving(reg_ccc.dta, replace): reg prezzo ib11.city_str i.marca_str, baselevels

However, before running each, I resort to the following:

Before running regression (1), I use: keep if rcode=="aaa"

Before running regression (2), I use: keep if rcode=="bbb"

Before running regression (3), I use: keep if rcode=="ccc"

Is there a way to run the three statsby regressions more efficiently, and perhaps without the need to drop observations from the sample before each respective regression?

Something like the following could work, but I would need to find a way to select different reference groups (i.e., different XX in ibXX.city_str) in each rcode set:

```<code>statsby _b, by(rcode grp_iden) saving(reg_ccc.dta, replace): reg prezzo ib11.city_str i.marca_str, baselevels
</code>```

答:
You might use a loop over 43 6 11 and also over aaa bbb ccc:

```<code>tokenize "aaa bbb ccc"
local x = 1
foreach g in 43 6 11 {
    statsby _b, by(grp_iden) saving(reg_``x''.dta, replace): reg prezzo ib`g'.city_str i.marca_str if rcode == "``x''", baselevels
    local ++x
}
</code>```

I have very mixed feelings about such coding. Sure, you exploit common structure to make the code shorter.  If the real problem included say 10 cases, that would clean up the code a lot. If the real problem were very similar, you might lose much clarity, for yourself later, for people in your team, and for other people trying to understand your code. A sharp test is that if you didn't see how to do this yourself, it may be trickier than you should want to use. But it's also true that we only grow by seeing how to use language features, which then become part of our basic toolkit.

Efficiency always sounds better than its lack, but making code more clever but less clear is often not a good idea. The time gain from a loop is dubious: Stata in fact has to interpret the looping machinery, although the cost of that should be trivial. Always include time spent reading the code in your consideration.

Body:
I want to run these three regressions. Note that each has a different reference group, which is why I run them separately.

statsby _b, by(grp_iden) saving(reg_aaa.dta, replace): reg prezzo ib43.city_str i.marca_str, baselevels

statsby _b, by(grp_iden) saving(reg_bbb.dta, replace): reg prezzo ib6.city_str i.marca_str, baselevels

statsby _b, by(grp_iden) saving(reg_ccc.dta, replace): reg prezzo ib11.city_str i.marca_str, baselevels

However, before running each, I resort to the following:

Before running regression (1), I use: keep if rcode=="aaa"

Before running regression (2), I use: keep if rcode=="bbb"

Before running regression (3), I use: keep if rcode=="ccc"

Is there a way to run the three statsby regressions more efficiently, and perhaps without the need to drop observations from the sample before each respective regression?

Something like the following could work, but I would need to find a way to select different reference groups (i.e., different XX in ibXX.city_str) in each rcode set:

statsby _b, by(rcode grp_iden) saving(reg_ccc.dta, replace): reg prezzo ib11.city_str i.marca_str, baselevels

Body:
You might use a loop over 43 6 11 and also over aaa bbb ccc:

tokenize "aaa bbb ccc"
local x = 1
foreach g in 43 6 11 {
    statsby _b, by(grp_iden) saving(reg_``x''.dta, replace): reg prezzo ib`g'.city_str i.marca_str if rcode == "``x''", baselevels
    local ++x
}

I have very mixed feelings about such coding. Sure, you exploit common structure to make the code shorter.  If the real problem included say 10 cases, that would clean up the code a lot. If the real problem were very similar, you might lose much clarity, for yourself later, for people in your team, and for other people trying to understand your code. A sharp test is that if you didn't see how to do this yourself, it may be trickier than you should want to use. But it's also true that we only grow by seeing how to use language features, which then become part of our basic toolkit.

Efficiency always sounds better than its lack, but making code more clever but less clear is often not a good idea. The time gain from a loop is dubious: Stata in fact has to interpret the looping machinery, although the cost of that should be trivial. Always include time spent reading the code in your consideration.


问:
Open Babel running .Net C# Process, doesn't work on deployed website
Due to some circumstances, I was ask to develop a page that uses Process in .Net C# to call the function through command prompt.
The code works perfectly Fine on visual studio, but when deployed on an IIS server. the Process doesn't seems to work, I've debugged and find out the process itself works. but the open Babel command doesn't work, i did double check and the identity i supply with should be alright, i did even supply it with admin privilege but still doesn't work. it doesn't even pop or error, it just simply ignored it and go through the commands.
I put the command into a .bat file, with some extra command to test if the .bat works. everything is fine until the command with open babel, then process just doesn't seem react with the command.

obabel %1 -O %2 --gen2d

this is the command i supply it with, %1 is the input file while %2 is the output file name. A very simple conversion. Note: everything is fine, just only the open babel command got ignored in the entire file. and I've tried to supply it with admin privilege, still doesn't work. the open babel can be used if directly used with command prompt on the server, or through visual studio. but it doesn't work if i deployed it through IIS server.

答:
Found the solution, after all kinds of modification.
it seems like i have to provide a physical path to Open Babel.exe in the .bat file, and same as the parameter file i supply it with.
It's risky solution, but at least it solves the problem.</p>


问:
Azure Devops NPM Please change your working directory to a valid directory
I am trying to build a project with npm run-script build

my package.json is like this

```<code>{
  "name": "isomorphic",
  "version": "2.6.0",
  "private": true,
  "dependencies": {
    "adal-angular": "^1.0.17",
    "antd": "^3.0.3",
    "antd-local-icon": "^0.1.3",
    "axios": "^0.18.0",
    "classnames": "^2.2.5",
    "clone": "^2.1.1",
    "history": "^4.6.3",
    "nprogress": "^0.2.0",
    "postcss-inline-rtl": "^0.9.8",
    "q": "^1.5.1",
    "react": "^16.2.0",
    "react-adal": "^0.4.17",
    "react-dom": "^16.2.0",
    "react-highlight-words": "^0.16.0",
    "react-intl": "^2.3.0",
    "react-placeholder": "^2.0.0",
    "react-redux": "^5.0.4",
    "react-router": "^4.1.1",
    "react-router-dom": "^4.1.0",
    "react-router-redux": "^5.0.0-alpha.5",
    "react-scripts": "1.0.17",
    "react-sidebar": "^2.3.2",
    "react-smooth-scrollbar": "^8.0.6",
    "react-throttle": "^0.3.0",
    "react-window-size-listener": "^1.0.10",
    "redux": "^3.6.0",
    "redux-devtools": "^3.3.2",
    "redux-devtools-dock-monitor": "^1.1.1",
    "redux-devtools-log-monitor": "^1.2.0",
    "redux-saga": "^0.16.0",
    "redux-thunk": "^2.2.0",
    "smooth-scrollbar": "^8.2.5",
    "styled-components": "^2.2.1",
    "styled-theme": "^0.3.3",
    "webpack-cli": "^3.2.3"
  },
  "devDependencies": {
    "react-app-rewired": "^1.4.0",
    "webpack": "^4.29.5"
  },
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test --env=jsdom",
    "eject": "react-scripts eject"
  }
}
</code>```

and my build definition is like this

However I still get this error:
Azure Devops NPM Please change your working directory to a valid directory

答: Just leave empty "Working folder with package.json" field

Body:
I am trying to build a project with npm run-script build

my package.json is like this

{
  "name": "isomorphic",
  "version": "2.6.0",
  "private": true,
  "dependencies": {
    "adal-angular": "^1.0.17",
    "antd": "^3.0.3",
    "antd-local-icon": "^0.1.3",
    "axios": "^0.18.0",
    "classnames": "^2.2.5",
    "clone": "^2.1.1",
    "history": "^4.6.3",
    "nprogress": "^0.2.0",
    "postcss-inline-rtl": "^0.9.8",
    "q": "^1.5.1",
    "react": "^16.2.0",
    "react-adal": "^0.4.17",
    "react-dom": "^16.2.0",
    "react-highlight-words": "^0.16.0",
    "react-intl": "^2.3.0",
    "react-placeholder": "^2.0.0",
    "react-redux": "^5.0.4",
    "react-router": "^4.1.1",
    "react-router-dom": "^4.1.0",
    "react-router-redux": "^5.0.0-alpha.5",
    "react-scripts": "1.0.17",
    "react-sidebar": "^2.3.2",
    "react-smooth-scrollbar": "^8.0.6",
    "react-throttle": "^0.3.0",
    "react-window-size-listener": "^1.0.10",
    "redux": "^3.6.0",
    "redux-devtools": "^3.3.2",
    "redux-devtools-dock-monitor": "^1.1.1",
    "redux-devtools-log-monitor": "^1.2.0",
    "redux-saga": "^0.16.0",
    "redux-thunk": "^2.2.0",
    "smooth-scrollbar": "^8.2.5",
    "styled-components": "^2.2.1",
    "styled-theme": "^0.3.3",
    "webpack-cli": "^3.2.3"
  },
  "devDependencies": {
    "react-app-rewired": "^1.4.0",
    "webpack": "^4.29.5"
  },
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

and my build definition is like this

However I still get this error:
Azure Devops NPM Please change your working directory to a valid directory


问:
problem while installing app on iphone
H everyone

i have up graded my xcode to xcode 4 & i am trying to install a app through this xcode on to a iphone but i am getting following error & i am unable to launch the app

```<code>warning: Unable to read symbols for /var/mobile/Applications/7A08B9EA-DD46-47B4-8E0C-BF081BDB1F4B/QIA All.app/QIA All (file not found).

dyld: Library not loaded: /System/Library/Frameworks/QuickLook.framework/QuickLook
  Referenced from: /var/mobile/Applications/7A08B9EA-DD46-47B4-8E0C-BF081BDB1F4B/QIA All.app/QIA All

Reason: image not found
</code>```

i have following warning in my app
ld: warning: directory not found for option '-F/Developer/new xcode/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.1.2.sdk/System/Library/PrivateFrameworks'

is from this warning

how can i fix this?,,,thanx in advance

答: you have to check that all images and framework are included friend. may b any image is missing that is deleted from project folder .check if you get any image in red then add that image</p>

Title: problem while installing app on iphone

Body:
H everyone

i have up graded my xcode to xcode 4 & i am trying to install a app through this xcode on to a iphone but i am getting following error & i am unable to launch the app

warning: Unable to read symbols for /var/mobile/Applications/7A08B9EA-DD46-47B4-8E0C-BF081BDB1F4B/QIA All.app/QIA All (file not found).

dyld: Library not loaded: /System/Library/Frameworks/QuickLook.framework/QuickLook
  Referenced from: /var/mobile/Applications/7A08B9EA-DD46-47B4-8E0C-BF081BDB1F4B/QIA All.app/QIA All

Reason: image not found

i have following warning in my app
ld: warning: directory not found for option '-F/Developer/new xcode/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.1.2.sdk/System/Library/PrivateFrameworks'

is from this warning

how can i fix this?,,,thanx in advance


问:
Extract text and integer after specific letter
I have string:

```<code>s = 'travel to africa x 2\ asia x 2\ europe x 2\ Airport pick up included. Furnitures 3 seater couch x 1 4 seater+ couch x 1 < 60 inches TV x 1 60 inches+ TV x 1 Washer - front loader x 1 Box / bag / misc x 1 The maximum clearance is 1.5m.'
</code>```

I would like split it by x and extract number after it.

So expected output is:

```<code>out = [('travel to africa', '2'),
       ('\ asia', '2'),
       ( '\ europe', '2'),
       ('\ Airport pick up included. Furnitures 3 seater couch', '1'),
       ('4 seater+ couch', '1'),
       ('< 60 inches TV', '1'),
       ('60 inches+ TV', '1'),
       ('Washer - front loader', '1'),
       ('Box / bag / misc', '1')]
</code>```

I try this regex, but failed, because special chars like -+< was omited (also there should be another special chars):

```<code>r'([A-Za-z 0-9]+)\s+x\s+(\d+)'
</code>```

What is correct regex for extract this values? Or also is possible solution without regex?

答:
My take on problem:

```<code>import re
import pprint

s = 'travel to africa x 2\ asia x 2\ europe x 2\ Airport pick up included. Furnitures 3 seater couch x 1 4 seater+ couch x 1 < 60 inches TV x 1 60 inches+ TV x 1 Washer - front loader x 1 Box / bag / misc x 1 The maximum clearance is 1.5m.'

out = []

for g in re.findall(r'(((^|\\?).*?)\s*x\s*(\d+)(.*?))', s):
    out += [[g[1], g[3]]]

pprint.pprint(out)
</code>```

Prints:

```<code>[['travel to africa', '2'],
 ['\\ asia', '2'],
 ['\\ europe', '2'],
 ['\\ Airport pick up included. Furnitures 3 seater couch', '1'],
 [' 4 seater+ couch', '1'],
 [' < 60 inches TV', '1'],
 [' 60 inches+ TV', '1'],
 [' Washer - front loader', '1'],
 [' Box / bag / misc', '1']]
</code>```

Body:
I have string:

s = 'travel to africa x 2\ asia x 2\ europe x 2\ Airport pick up included. Furnitures 3 seater couch x 1 4 seater+ couch x 1 < 60 inches TV x 1 60 inches+ TV x 1 Washer - front loader x 1 Box / bag / misc x 1 The maximum clearance is 1.5m.'

I would like split it by x and extract number after it.

So expected output is:

out = [('travel to africa', '2'),
       ('\ asia', '2'),
       ( '\ europe', '2'),
       ('\ Airport pick up included. Furnitures 3 seater couch', '1'),
       ('4 seater+ couch', '1'),
       ('< 60 inches TV', '1'),
       ('60 inches+ TV', '1'),
       ('Washer - front loader', '1'),
       ('Box / bag / misc', '1')]

I try this regex, but failed, because special chars like -+< was omited (also there should be another special chars):

r'([A-Za-z 0-9]+)\s+x\s+(\d+)'

What is correct regex for extract this values? Or also is possible solution without regex?

Body:
My take on problem:

import re
import pprint

s = 'travel to africa x 2\ asia x 2\ europe x 2\ Airport pick up included. Furnitures 3 seater couch x 1 4 seater+ couch x 1 < 60 inches TV x 1 60 inches+ TV x 1 Washer - front loader x 1 Box / bag / misc x 1 The maximum clearance is 1.5m.'

out = []

for g in re.findall(r'(((^|\\?).*?)\s*x\s*(\d+)(.*?))', s):
    out += [[g[1], g[3]]]

pprint.pprint(out)

Prints:

[['travel to africa', '2'],
 ['\\ asia', '2'],
 ['\\ europe', '2'],
 ['\\ Airport pick up included. Furnitures 3 seater couch', '1'],
 [' 4 seater+ couch', '1'],
 [' < 60 inches TV', '1'],
 [' 60 inches+ TV', '1'],
 [' Washer - front loader', '1'],
 [' Box / bag / misc', '1']]


问:
Asp.NET Identity 2 giving "Invalid Token" error
I'm using Asp.Net-Identity-2 and I'm trying to verify email verification code using the below method. But I am getting an "Invalid Token" error message.

My Application's User Manager is like this:

```<code>public class AppUserManager : UserManager<AppUser>
{
    public AppUserManager(IUserStore<AppUser> store) : base(store) { }

    public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
    {
        AppIdentityDbContext db = context.Get<AppIdentityDbContext>();
        AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db));

        manager.PasswordValidator = new PasswordValidator {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = false,
            RequireLowercase = true,
            RequireUppercase = true
        };

        manager.UserValidator = new UserValidator<AppUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = true,
            RequireUniqueEmail = true
        };

        var dataProtectionProvider = options.DataProtectionProvider;

        //token life span is 3 hours
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider =
               new DataProtectorTokenProvider<AppUser>
                  (dataProtectionProvider.Create("ConfirmationToken"))
               {
                   TokenLifespan = TimeSpan.FromHours(3)
               };
        }

        manager.EmailService = new EmailService();

        return manager;
    } //Create
  } //class
} //namespace
</code>```

My Action to generate the token is (and even if I check the token here, I get "Invalid token" message):

```<code>[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ForgotPassword(string email)
{
    if (ModelState.IsValid)
    {
        AppUser user = UserManager.FindByEmail(email);
        if (user == null || !(UserManager.IsEmailConfirmed(user.Id)))
        {
            // Returning without warning anything wrong...
            return View("../Home/Index");

        } //if

        string code = UserManager.GeneratePasswordResetToken(user.Id);
        string callbackUrl = Url.Action("ResetPassword", "Admin", new { Id = user.Id, code = HttpUtility.UrlEncode(code) }, protocol: Request.Url.Scheme);

        UserManager.SendEmail(user.Id, "Reset password Link", "Use the following  link to reset your password: <a href=\"" + callbackUrl + "\">link</a>");

        //This 2 lines I use tho debugger propose. The result is: "Invalid token" (???)
        IdentityResult result;
        result = UserManager.ConfirmEmail(user.Id, code);
    }

    // If we got this far, something failed, redisplay form
    return View();

} //ForgotPassword
</code>```

My Action to check the token is (here, I always get "Invalid Token" when I check the result):

```<code>[AllowAnonymous]
public async Task<ActionResult> ResetPassword(string id, string code)
{

    if (id == null || code == null)
    {
        return View("Error", new string[] { "Invalid params to reset password." });
    }

    IdentityResult result;

    try
    {
        result = await UserManager.ConfirmEmailAsync(id, code);
    }
    catch (InvalidOperationException ioe)
    {
        // ConfirmEmailAsync throws when the id is not found.
        return View("Error", new string[] { "Error to reset password:<br/><br/><li>" + ioe.Message + "</li>" });
    }

    if (result.Succeeded)
    {
        AppUser objUser = await UserManager.FindByIdAsync(id);
        ResetPasswordModel model = new ResetPasswordModel();

        model.Id = objUser.Id;
        model.Name = objUser.UserName;
        model.Email = objUser.Email;

        return View(model);
    }

    // If we got this far, something failed.
    string strErrorMsg = "";
    foreach(string strError in result.Errors)
    {
        strErrorMsg += "<li>" + strError + "</li>";
    } //foreach

    return View("Error", new string[] { strErrorMsg });

} //ForgotPasswordConfirmation
</code>```

I don't know what could be missing or what's wrong...

答:
tl;dr: Register custom token provider in aspnet core 2.2 to use AES encryption instead of MachineKey protection, gist: https://gist.github.com/cyptus/dd9b2f90c190aaed4e807177c45c3c8b

i ran into the same issue with aspnet core 2.2, as cheny pointed out the instances of the token provider needs to be the same.
this does not work for me because

i got different API-projects which does generate the token and
receive the token to reset password

the APIs may run on different instances of virtual machines, so the machine key would not be the
same

the API may restart and the token would be invalid because it is
not the same instance any more

i could use
services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo("path"))
to save the token to the file system and avoid restart and multiple instance sharing issues, but could not get around the issue with multiple projects, as each project generates a own file.

the solution for me is to replace the MachineKey data protection logic with an own logic which does use AES then HMAC to symmetric encrypt the token with a key from my own settings which i can share across machines, instances and projects. I took the encryption logic from
Encrypt and decrypt a string in C#?
(Gist: https://gist.github.com/jbtule/4336842#file-aesthenhmac-cs)
and implemented a custom TokenProvider:

    public class AesDataProtectorTokenProvider<TUser> : DataProtectorTokenProvider<TUser> where TUser : class
    {
        public AesDataProtectorTokenProvider(IOptions<DataProtectionTokenProviderOptions> options, ISettingSupplier settingSupplier)
            : base(new AesProtectionProvider(settingSupplier.Supply()), options)
        {
            var settingsLifetime = settingSupplier.Supply().Encryption.PasswordResetLifetime;

            if (settingsLifetime.TotalSeconds > 1)
            {
                Options.TokenLifespan = settingsLifetime;
            }
        }
    }
```

<pre class="lang-cs prettyprint-override"><code>    public class AesProtectionProvider : IDataProtectionProvider
    {
        private readonly SystemSettings _settings;

        public AesProtectionProvider(SystemSettings settings)
        {
            _settings = settings;

            if(string.IsNullOrEmpty(_settings.Encryption.AESPasswordResetKey))
                throw new ArgumentNullException("AESPasswordResetKey must be set");
        }

        public IDataProtector CreateProtector(string purpose)
        {
            return new AesDataProtector(purpose, _settings.Encryption.AESPasswordResetKey);
        }
    }
</code>```

    public class AesDataProtector : IDataProtector
    {
        private readonly string _purpose;
        private readonly SymmetricSecurityKey _key;
        private readonly Encoding _encoding = Encoding.UTF8;

        public AesDataProtector(string purpose, string key)
        {
            _purpose = purpose;
            _key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
        }

        public byte[] Protect(byte[] userData)
        {
            return AESThenHMAC.SimpleEncryptWithPassword(userData, _encoding.GetString(_key.Key));
        }

        public byte[] Unprotect(byte[] protectedData)
        {
            return AESThenHMAC.SimpleDecryptWithPassword(protectedData, _encoding.GetString(_key.Key));
        }

        public IDataProtector CreateProtector(string purpose)
        {
            throw new NotSupportedException();
        }
    }
```

<p>and the SettingsSupplier i use in my project to supply my settings</p>

<pre class="lang-cs prettyprint-override"><code>    public interface ISettingSupplier
    {
        SystemSettings Supply();
    }

    public class SettingSupplier : ISettingSupplier
    {
        private IConfiguration Configuration { get; }

        public SettingSupplier(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public SystemSettings Supply()
        {
            var settings = new SystemSettings();
            Configuration.Bind("SystemSettings", settings);

            return settings;
        }
    }

    public class SystemSettings
    {
        public EncryptionSettings Encryption { get; set; } = new EncryptionSettings();
    }

    public class EncryptionSettings
    {
        public string AESPasswordResetKey { get; set; }
        public TimeSpan PasswordResetLifetime { get; set; } = new TimeSpan(3, 0, 0, 0);
    }
</code>```

finally register the provider in Startup:

 services
     .AddIdentity<AppUser, AppRole>()
     .AddEntityFrameworkStores<AppDbContext>()
     .AddDefaultTokenProviders()
     .AddTokenProvider<AesDataProtectorTokenProvider<AppUser>>(TokenOptions.DefaultProvider);

 services.AddScoped(typeof(ISettingSupplier), typeof(SettingSupplier));
```

<pre class="lang-cs prettyprint-override"><code>//AESThenHMAC.cs: See https://gist.github.com/jbtule/4336842#file-aesthenhmac-cs
</code>```

Body:
I'm using Asp.Net-Identity-2 and I'm trying to verify email verification code using the below method. But I am getting an "Invalid Token" error message.

My Application's User Manager is like this:

public class AppUserManager : UserManager<AppUser>
{
    public AppUserManager(IUserStore<AppUser> store) : base(store) { }

    public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
    {
        AppIdentityDbContext db = context.Get<AppIdentityDbContext>();
        AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db));

        manager.PasswordValidator = new PasswordValidator {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = false,
            RequireLowercase = true,
            RequireUppercase = true
        };

        manager.UserValidator = new UserValidator<AppUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = true,
            RequireUniqueEmail = true
        };

        var dataProtectionProvider = options.DataProtectionProvider;

        //token life span is 3 hours
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider =
               new DataProtectorTokenProvider<AppUser>
                  (dataProtectionProvider.Create("ConfirmationToken"))
               {
                   TokenLifespan = TimeSpan.FromHours(3)
               };
        }

        manager.EmailService = new EmailService();

        return manager;
    } //Create
  } //class
} //namespace

My Action to generate the token is (and even if I check the token here, I get "Invalid token" message):

[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ForgotPassword(string email)
{
    if (ModelState.IsValid)
    {
        AppUser user = UserManager.FindByEmail(email);
        if (user == null || !(UserManager.IsEmailConfirmed(user.Id)))
        {
            // Returning without warning anything wrong...
            return View("../Home/Index");

        } //if

        string code = UserManager.GeneratePasswordResetToken(user.Id);
        string callbackUrl = Url.Action("ResetPassword", "Admin", new { Id = user.Id, code = HttpUtility.UrlEncode(code) }, protocol: Request.Url.Scheme);

        UserManager.SendEmail(user.Id, "Reset password Link", "Use the following  link to reset your password: link");

        //This 2 lines I use tho debugger propose. The result is: "Invalid token" (???)
        IdentityResult result;
        result = UserManager.ConfirmEmail(user.Id, code);
    }

    // If we got this far, something failed, redisplay form
    return View();

} //ForgotPassword

My Action to check the token is (here, I always get "Invalid Token" when I check the result):

[AllowAnonymous]
public async Task<ActionResult> ResetPassword(string id, string code)
{

    if (id == null || code == null)
    {
        return View("Error", new string[] { "Invalid params to reset password." });
    }

    IdentityResult result;

    try
    {
        result = await UserManager.ConfirmEmailAsync(id, code);
    }
    catch (InvalidOperationException ioe)
    {
        // ConfirmEmailAsync throws when the id is not found.
        return View("Error", new string[] { "Error to reset password:

" + ioe.Message + "
" });
    }

    if (result.Succeeded)
    {
        AppUser objUser = await UserManager.FindByIdAsync(id);
        ResetPasswordModel model = new ResetPasswordModel();

        model.Id = objUser.Id;
        model.Name = objUser.UserName;
        model.Email = objUser.Email;

        return View(model);
    }

    // If we got this far, something failed.
    string strErrorMsg = "";
    foreach(string strError in result.Errors)
    {
        strErrorMsg += "
" + strError + "
";
    } //foreach

    return View("Error", new string[] { strErrorMsg });

} //ForgotPasswordConfirmation

I don't know what could be missing or what's wrong...

Body:
tl;dr: Register custom token provider in aspnet core 2.2 to use AES encryption instead of MachineKey protection, gist: https://gist.github.com/cyptus/dd9b2f90c190aaed4e807177c45c3c8b

i ran into the same issue with aspnet core 2.2, as cheny pointed out the instances of the token provider needs to be the same.
this does not work for me because

i got different API-projects which does generate the token and
receive the token to reset password

the APIs may run on different instances of virtual machines, so the machine key would not be the
same

the API may restart and the token would be invalid because it is
not the same instance any more

i could use
services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo("path"))
to save the token to the file system and avoid restart and multiple instance sharing issues, but could not get around the issue with multiple projects, as each project generates a own file.

the solution for me is to replace the MachineKey data protection logic with an own logic which does use AES then HMAC to symmetric encrypt the token with a key from my own settings which i can share across machines, instances and projects. I took the encryption logic from
Encrypt and decrypt a string in C#?
(Gist: https://gist.github.com/jbtule/4336842#file-aesthenhmac-cs)
and implemented a custom TokenProvider:

    public class AesDataProtectorTokenProvider<TUser> : DataProtectorTokenProvider<TUser> where TUser : class
    {
        public AesDataProtectorTokenProvider(IOptions<DataProtectionTokenProviderOptions> options, ISettingSupplier settingSupplier)
            : base(new AesProtectionProvider(settingSupplier.Supply()), options)
        {
            var settingsLifetime = settingSupplier.Supply().Encryption.PasswordResetLifetime;

            if (settingsLifetime.TotalSeconds > 1)
            {
                Options.TokenLifespan = settingsLifetime;
            }
        }
    }

    public class AesProtectionProvider : IDataProtectionProvider
    {
        private readonly SystemSettings _settings;

        public AesProtectionProvider(SystemSettings settings)
        {
            _settings = settings;

            if(string.IsNullOrEmpty(_settings.Encryption.AESPasswordResetKey))
                throw new ArgumentNullException("AESPasswordResetKey must be set");
        }

        public IDataProtector CreateProtector(string purpose)
        {
            return new AesDataProtector(purpose, _settings.Encryption.AESPasswordResetKey);
        }
    }

    public class AesDataProtector : IDataProtector
    {
        private readonly string _purpose;
        private readonly SymmetricSecurityKey _key;
        private readonly Encoding _encoding = Encoding.UTF8;

        public AesDataProtector(string purpose, string key)
        {
            _purpose = purpose;
            _key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
        }

        public byte[] Protect(byte[] userData)
        {
            return AESThenHMAC.SimpleEncryptWithPassword(userData, _encoding.GetString(_key.Key));
        }

        public byte[] Unprotect(byte[] protectedData)
        {
            return AESThenHMAC.SimpleDecryptWithPassword(protectedData, _encoding.GetString(_key.Key));
        }

        public IDataProtector CreateProtector(string purpose)
        {
            throw new NotSupportedException();
        }
    }

and the SettingsSupplier i use in my project to supply my settings

    public interface ISettingSupplier
    {
        SystemSettings Supply();
    }

    public class SettingSupplier : ISettingSupplier
    {
        private IConfiguration Configuration { get; }

        public SettingSupplier(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public SystemSettings Supply()
        {
            var settings = new SystemSettings();
            Configuration.Bind("SystemSettings", settings);

            return settings;
        }
    }

    public class SystemSettings
    {
        public EncryptionSettings Encryption { get; set; } = new EncryptionSettings();
    }

    public class EncryptionSettings
    {
        public string AESPasswordResetKey { get; set; }
        public TimeSpan PasswordResetLifetime { get; set; } = new TimeSpan(3, 0, 0, 0);
    }

finally register the provider in Startup:

 services
     .AddIdentity<AppUser, AppRole>()
     .AddEntityFrameworkStores<AppDbContext>()
     .AddDefaultTokenProviders()
     .AddTokenProvider<AesDataProtectorTokenProvider<AppUser>>(TokenOptions.DefaultProvider);

 services.AddScoped(typeof(ISettingSupplier), typeof(SettingSupplier));

//AESThenHMAC.cs: See https://gist.github.com/jbtule/4336842#file-aesthenhmac-cs


问:
Any Java experience on Raspberry PI?
Is it possible to run average java app server on e.g. jboss or glassfish server on Raspberry pi? Any limitations? Does anyone have an experience in Java development for raspberry pi?

At least any appropriate JVM for RPi will be nice.

答:
in case you want to use java 11 and javafx I found this is definitely possible with the Liberica JDK of BellSoft: https://bell-sw.com/pages/java-11.0.3

Install scripts and demo application are available on my blog: https://webtechie.be/2019/04/16/pijava-overview-java-11-and-javafx-11-on-raspberry-pi

To install JDK 11.0.2:

```<code># Make sure we are in the home directory
cd /home/pi

# Download the Java 11.0.2 distribution from BellSoft
wget https://download.bell-sw.com/java/11.0.2/bellsoft-jdk11.0.2-linux-arm32-vfp-hflt.tar.gz

# Move the downloaded file to /opt
sudo mv bellsoft-jdk11.0.2-linux-arm32-vfp-hflt.tar.gz /opt

# Use the /opt directory
cd /opt

# Untar the downloaded file
sudo tar -xvzf bellsoft-jdk11.0.2-linux-arm32-vfp-hflt.tar.gz

# Remove the downloaded file
sudo rm bellsoft-jdk11.0.2-linux-arm32-vfp-hflt.tar.gz
</code>```

Testing and running Java file without compiling:

```<code>cd /home/pi
nano HelloWorld.java

public class HelloWorld {
    public static void main (String[] args) {
        System.out.println("Hello World");
    }
}

/opt/jdk-11/bin/java /home/pi/HelloWorld.java
Hello World
</code>```

Title: Any Java experience on Raspberry PI?

Body:
in case you want to use java 11 and javafx I found this is definitely possible with the Liberica JDK of BellSoft: https://bell-sw.com/pages/java-11.0.3

Install scripts and demo application are available on my blog: https://webtechie.be/2019/04/16/pijava-overview-java-11-and-javafx-11-on-raspberry-pi

To install JDK 11.0.2:

# Make sure we are in the home directory
cd /home/pi

# Download the Java 11.0.2 distribution from BellSoft
wget https://download.bell-sw.com/java/11.0.2/bellsoft-jdk11.0.2-linux-arm32-vfp-hflt.tar.gz

# Move the downloaded file to /opt
sudo mv bellsoft-jdk11.0.2-linux-arm32-vfp-hflt.tar.gz /opt

# Use the /opt directory
cd /opt

# Untar the downloaded file
sudo tar -xvzf bellsoft-jdk11.0.2-linux-arm32-vfp-hflt.tar.gz

# Remove the downloaded file
sudo rm bellsoft-jdk11.0.2-linux-arm32-vfp-hflt.tar.gz

Testing and running Java file without compiling:

cd /home/pi
nano HelloWorld.java

public class HelloWorld {
    public static void main (String[] args) {
        System.out.println("Hello World");
    }
}

/opt/jdk-11/bin/java /home/pi/HelloWorld.java
Hello World


问:
Event handler raised twice in async method
I have async method where i am invoking event and it raised two times. I don't know what i am doing wrong. This is my method from where i am invoking:

```<code>public async Task SyncData(GAT t)
{
    try
    {
        GetInventoryDataResponse response = await GetInventoryData(t);

        List<InventoryData> inventoryData = response.InventoryDataColl;

        //Some logic

        NotifyDataEvent?.Invoke(this, new NotifyEventArgs(Result.Success));
    }
    catch (Exception ex)
    {
        Log.WarnWithException("Unable to sync", ex);
        throw;
    }
}
</code>```

This is my class where i register and un-register the event. In constructor i am registering it:

```<code>_stationAgent.NotifyDataEvent += NotifyData;
</code>```

In dispose method i unregister this event

```<code>_stationAgent.NotifyDataEvent -= NotifyData;
</code>```

But notifydata raised multiple times. What's the issue?

答:
Check invocation list of the event:

```<code>EventHandler e = NotifyDataEvent;
var count = e.GetInvocationList().Length;
</code>```

If count = 2 then you call NotifyDataEvent +=... twice. If  count = 1 then you call NotifyDataEvent.Invoke... twice.

Body:
I have async method where i am invoking event and it raised two times. I don't know what i am doing wrong. This is my method from where i am invoking:

public async Task SyncData(GAT t)
{
    try
    {
        GetInventoryDataResponse response = await GetInventoryData(t);

        List<InventoryData> inventoryData = response.InventoryDataColl;

        //Some logic

        NotifyDataEvent?.Invoke(this, new NotifyEventArgs(Result.Success));
    }
    catch (Exception ex)
    {
        Log.WarnWithException("Unable to sync", ex);
        throw;
    }
}

This is my class where i register and un-register the event. In constructor i am registering it:

_stationAgent.NotifyDataEvent += NotifyData;

In dispose method i unregister this event

_stationAgent.NotifyDataEvent -= NotifyData;

But notifydata raised multiple times. What's the issue?

Body:
Check invocation list of the event:

EventHandler e = NotifyDataEvent;
var count = e.GetInvocationList().Length;

If count = 2 then you call NotifyDataEvent +=... twice. If  count = 1 then you call NotifyDataEvent.Invoke... twice.


问:
Change background color of buttons onclick
I have two buttons called YES and NO whose color(i,e background-color) is light like this:

When the user click YES

YES button background color should change to green (i,e success) and NO should be in light color like this:

When the user click No

NO button background color should change to red (i,e danger) and Yes should be in light color like this:

DEMO

while surfing i saw this question. Here they are changing only one button color on click. But for my requirement both the button color should change on click.

CODE

HTML

```<code><ion-content padding>
  <ion-item lines="none">
  <ion-button class="btn-1" expand="full" color="light" >Yes</ion-button>
   <ion-button class="btn-2" expand="full"  color="light" >No</ion-button>
  </ion-item>
</ion-content>
</code>```

CSS

```<code>.btn-1{
width:45%;
float:left;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}
.btn-2{
width:45%;
float:right;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}
</code>```

TS

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

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.css'],
})
export class HomePage {

}
</code>```

答:
Try like this:

TS:

```<code>isYesClicked:boolean = false
isNoClicked:boolean = false
</code>```

HTML:

```<code><ion-button class="btn-1" expand="full" (click)="isYesClicked=true;isNoClicked=false" [color]="isYesClicked?'success':'light'"  >Yes</ion-button>

<ion-button class="btn-2" expand="full"  color="light" (click)="isYesClicked=false;isNoClicked=true" [color]="isNoClicked?'danger':'light'">No</ion-button>
</code>```

Body:
I have two buttons called YES and NO whose color(i,e background-color) is light like this:

When the user click YES

YES button background color should change to green (i,e success) and NO should be in light color like this:

When the user click No

NO button background color should change to red (i,e danger) and Yes should be in light color like this:

DEMO

while surfing i saw this question. Here they are changing only one button color on click. But for my requirement both the button color should change on click.

CODE

HTML

<ion-content padding>
  <ion-item lines="none">
  <ion-button class="btn-1" expand="full" color="light" >Yes</ion-button>
   <ion-button class="btn-2" expand="full"  color="light" >No</ion-button>
  </ion-item>
</ion-content>

CSS

.btn-1{
width:45%;
float:left;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}
.btn-2{
width:45%;
float:right;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}

TS

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

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.css'],
})
export class HomePage {

}

Body:
Try like this:

TS:

isYesClicked:boolean = false
isNoClicked:boolean = false

HTML:

<ion-button class="btn-1" expand="full" (click)="isYesClicked=true;isNoClicked=false" [color]="isYesClicked?'success':'light'"  >Yes</ion-button>

<ion-button class="btn-2" expand="full"  color="light" (click)="isYesClicked=false;isNoClicked=true" [color]="isNoClicked?'danger':'light'">No</ion-button>


问:
How to convert month name to number in unix?
Input :

```<code>01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
</code>```

Expected output :

```<code>01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
</code>```

How do I convert the abbreviated month name to month number and achieve the expected output?

答:
A brute-force method with arrays:

```<code>awk '
    BEGIN {
        FS = OFS = "-"
        split("", m)
        n = split("JAN-FEB-MAR-APR-MAY-JUN-JUL-AUG-SEP-OCT-NOV-DEC", s)
        for (i=1; i<=n; i++)
            m[s[i]] = sprintf("%0.2i", i)
    }
    { $2 = m[$2]; print }
    ' file
</code>```

Really brute force (& dead simple):

```<code>awk '
    BEGIN {
        FS = OFS = "-"
        split("", m)
        m["JAN"] = "01"
        m["FEB"] = "02"
        m["MAR"] = "02"
        m["APR"] = "03"
        m["MAY"] = "05"
        m["JUN"] = "06"
        m["JUL"] = "07"
        m["AUG"] = "08"
        m["SEP"] = "09"
        m["OCT"] = "10"
        m["NOV"] = "11"
        m["DEC"] = "12"
    }
    { $2 = m[$2]; print }
    ' file
</code>```

Or using index:

```<code>awk -F- -v OFS=- '{
    m = index("  JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC", $2) / 3
    $2 = sprintf("%0.2i", m)
    print
}' file
</code>```

Body:
Input :

01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"

Expected output :

01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"

How do I convert the abbreviated month name to month number and achieve the expected output?

Body:
A brute-force method with arrays:

awk '
    BEGIN {
        FS = OFS = "-"
        split("", m)
        n = split("JAN-FEB-MAR-APR-MAY-JUN-JUL-AUG-SEP-OCT-NOV-DEC", s)
        for (i=1; i<=n; i++)
            m[s[i]] = sprintf("%0.2i", i)
    }
    { $2 = m[$2]; print }
    ' file

Really brute force (& dead simple):

awk '
    BEGIN {
        FS = OFS = "-"
        split("", m)
        m["JAN"] = "01"
        m["FEB"] = "02"
        m["MAR"] = "02"
        m["APR"] = "03"
        m["MAY"] = "05"
        m["JUN"] = "06"
        m["JUL"] = "07"
        m["AUG"] = "08"
        m["SEP"] = "09"
        m["OCT"] = "10"
        m["NOV"] = "11"
        m["DEC"] = "12"
    }
    { $2 = m[$2]; print }
    ' file

Or using index:

awk -F- -v OFS=- '{
    m = index("  JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC", $2) / 3
    $2 = sprintf("%0.2i", m)
    print
}' file


问:
Graph Api Notification - Maximum length of subscription for user/group changes
What is  Maximum length of subscription for Graph Api Notification -about user/group resources changes?

Any option to set 'Never expiry' to Notification so no need to renew? If not possible why is it so ?

答:
What is Maximum length of subscription for Graph Api Notification
  -about user/group resources changes?

The Maximum length of subscription of User,group, other directory entities is 4230 minutes (under 3 days). You can refer to this document.

Any option to set 'Never expiry' to Notification so no need to renew?
  If not possible why is it so ?

Note: Existing applications and new applications should not exceed the supported value. In the future, any requests to create or renew a subscription beyond the maximum value will fail. Refer to this document.

If you still have concerns regarding this, you can send your feedback at the bottom of this document.


问:
getting rid of colon in grok
Basically I was setting up an Elasticsearch-Logstash-Kibana (elk) stack for monitoring syslogs. Now I have to write the grok pattern for logstash.

Here's an example of my log:

May  8 15:14:50 tileserver systemd[25780]: Startup finished in 29ms.

And that's my pattern (yet):

%{SYSLOGTIMESTAMP:zeit} %{HOSTNAME:host} %{SYSLOGPROG:program}

Usually I'm also using %{DATA:text} for the message but it just works on the link below.

I'm using Test grok patterns to test my patterns and these 3 work fine but there's the colon (from after PID) in front of the message and I don't want it to be there.
How do I get rid of it?

答:
try this:</p>

```<code>%{SYSLOGTIMESTAMP:zeit} %{HOSTNAME:host} %{GREEDYDATA:syslog_process}(:) %{GREEDYDATA:message}
</code>```

Title: getting rid of colon in grok

Body:
try this:

%{SYSLOGTIMESTAMP:zeit} %{HOSTNAME:host} %{GREEDYDATA:syslog_process}(:) %{GREEDYDATA:message}


问:
Django template filters
Which filter should i use in django templates in order to display my text in the way it was entered including all the spaces and  even alignments(whether it's Left, Right etc) For eg: I want to add some description about a title and i want it to be in this form:

```<code>"My my, 2018 is going by so quickly!

Maybe it went by fast because we were too busy loading up on all kinds of yummy food at all the new restaurants that opened up.
                    As usual, we took the liberty of curating a list of eateries that we think                      you should not keep waiting.

So, without much further adieu, there’s your Culinary Bucket List For The Rest Of 2018".
</code>```

Currently my title description is set in this format : {{value:Linebreaks}}

答: Use the inbuilt {{value | safe}}</p>

Title: Django template filters

Body:
Which filter should i use in django templates in order to display my text in the way it was entered including all the spaces and  even alignments(whether it's Left, Right etc) For eg: I want to add some description about a title and i want it to be in this form:

"My my, 2018 is going by so quickly!

Maybe it went by fast because we were too busy loading up on all kinds of yummy food at all the new restaurants that opened up.
                    As usual, we took the liberty of curating a list of eateries that we think                      you should not keep waiting.

So, without much further adieu, there’s your Culinary Bucket List For The Rest Of 2018".

Currently my title description is set in this format : {{value:Linebreaks}}

Body: Use the inbuilt {{value | safe}}


问:
Value inside array having same object id
Recently I was playing with arrays and found out a weird behavior. I created a new array using Array.new.

arr = Array.new(4,"happy")

["happy", "happy", "happy", "happy"]

I appended a word into the second element in that array like shown below

arr[1] <<" Dino"

When I looked at arr, I was expecting an array with the second element having an appended word. But to my surprise array returned with all elements with the appended word.

["happy Dino", "happy Dino", "happy Dino", "happy Dino"]

How can this happen? Are we creating copies of the same string when we are creating the array? It doesn't happen if we use arr[1]= " Dino". Somebody can explain why this is happening?

答:
When we take Array.new(4, "Happy") it will create 4 elements with same object id. We can observe in irb arr[1].object_id => 2880099 , arr[2].object_id => 2880099 and remaining 2 elements also will return same object id.

So when we try like arr[1] << "Something" , this string will append to all the same object id's.

Now if we take another element for arr like arr.push("newString"). Now if see the last element object id arr.last.object_id => 4889988,it's different now.

So if we try same command arr[1] << "Something" it won't be effect to newly inserted element because object id is different.

if you don't want this behaviour the use Array.new(4){ 'String' }


答:
Yes, you a right. See the ruby docs

When a size and an optional default are sent, an array is created with size copies of default. Take notice that all elements will reference the same object default.

You can initialize array in a way like this:

```<code>arr = Array.new(4){ 'happy' }
</code>```

Title: Value inside array having same object id

Body:
Recently I was playing with arrays and found out a weird behavior. I created a new array using Array.new.

arr = Array.new(4,"happy")

["happy", "happy", "happy", "happy"]

I appended a word into the second element in that array like shown below

arr[1] <<" Dino"

When I looked at arr, I was expecting an array with the second element having an appended word. But to my surprise array returned with all elements with the appended word.

["happy Dino", "happy Dino", "happy Dino", "happy Dino"]

How can this happen? Are we creating copies of the same string when we are creating the array? It doesn't happen if we use arr[1]= " Dino". Somebody can explain why this is happening?

Body:
Yes, you a right. See the ruby docs

When a size and an optional default are sent, an array is created with size copies of default. Take notice that all elements will reference the same object default.

You can initialize array in a way like this:

arr = Array.new(4){ 'happy' }


问:
Java: Detect duplicates in ArrayList?
How could I go about detecting (returning true/false) whether an ArrayList contains more than one of the same element in Java?

Many thanks,
Terry

Edit
Forgot to mention that I am not looking to compare "Blocks" with each other but their integer values. Each "block" has an int and this is what makes them different.
I find the int of a particular Block by calling a method named "getNum" (e.g. table1[0][2].getNum();

答:
Simply put:
1) make sure all items are comparable
2) sort the array
2) iterate over the array and find duplicates</p>

OwnerDisplayName: Terry

LastEditorDisplayName: Terry

ContentLicense: CC BY-SA 2.5

Title: Java: Detect duplicates in ArrayList?

OwnerDisplayName: Antonio


问:
Q: How to check the extension of an URL website?
I would like to know if there is a way to check the extension of an URL website ? For example, do something when the website is like http://example.es/ and do another thing when the website is like http://example.fr/

I have check that there is something like

```<code>$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
</code>```

which returns the current URL of the web page.

Thanks for help.

答:
From your example I assume that you are using PHP, then you can use parse_url to get the components.
https://www.php.net/parse-url

For example you can get the host example.fr and example.com, then do explode on host string to get the tld, .fr or .com, which should help you to do further if-else.

Body:
I would like to know if there is a way to check the extension of an URL website ? For example, do something when the website is like http://example.es/ and do another thing when the website is like http://example.fr/

I have check that there is something like

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

which returns the current URL of the web page.

Thanks for help.


问:
PHP count duplicates in text file
So I have a text file with a list of games people entered, all on a new like like this:

```<code><tr><td>proatowning</td><td>Final Fantasy X</td></tr>
<tr><td>drunkenveteran</td><td>Trials Evolution</td></tr>
</code>```

Now what I would like is some sort of code that allows me to count the duplicates and return them with the amount of times it's been used.

For example:

5 people submit "Final Fantasy X".

3 people submit "Trials Evolution".

Then it should return something like this:

```<code><tr><td>Final Fantasy X</td><td>5</td></tr>
<tr><td>Trials Evolution</td><td>3</td></tr>
</code>```

This so I can use it in a table. It would be awesome if it could only display the top 10 most voted (most duplicate) games.

Thanks.

答:
I have rewrote and simplified the code from Optox answer and it worked for me:</p>

```<code>$lines = file('myfile.txt');
$games = array();
foreach ($lines as $line_num => $line) {
    $pos = strpos($line,'<td>',8);//start the search for <td> after first one
    $game = substr($line,$pos);
    $game = substr($game,4,-4);//remove the <td> tags
    if (array_key_exists($game,$games) $games[$game] += 1;
    else $games[$game] = 1;
}
foreach($games as $name => $count){
    echo "<b>".$count."</b> people submitted \"".$name."\"\n";
}
</code>```

Title: PHP count duplicates in text file

Body:
So I have a text file with a list of games people entered, all on a new like like this:

proatowning	Final Fantasy X

drunkenveteran	Trials Evolution

Now what I would like is some sort of code that allows me to count the duplicates and return them with the amount of times it's been used.

For example:

5 people submit "Final Fantasy X".

3 people submit "Trials Evolution".

Then it should return something like this:

Final Fantasy X	5

Trials Evolution	3

This so I can use it in a table. It would be awesome if it could only display the top 10 most voted (most duplicate) games.

Thanks.

Body:
I have rewrote and simplified the code from Optox answer and it worked for me:

$lines = file('myfile.txt');
$games = array();
foreach ($lines as $line_num => $line) {
    $pos = strpos($line,'<td>',8);//start the search for <td> after first one
    $game = substr($line,$pos);
    $game = substr($game,4,-4);//remove the <td> tags
    if (array_key_exists($game,$games) $games[$game] += 1;
    else $games[$game] = 1;
}
foreach($games as $name => $count){
    echo "<b>".$count."</b> people submitted \"".$name."\"\n";
}


问:
angular disable button on dynamic list
My list is taking info from external API, Im creating it dynamically, When I click on the 'li' element (I create 10 of them) with (click) method bunch of info shows up (second ul list). The problem is that I want to disable all other elements (all other 9) that aren't clicked, ofc until I unclick that one I clicked before. Summing I want be able to click only 1 element at once others must be disable for that moment.
Could someone explain/show me how to do this?</p>

```<code><ng-container>
  <div class="wrapper">
    <ul class="exteriorUL" *ngFor="let planet of results$; let i = index;">
      <li (click)="hidden[i] = !hidden[i]">
          <b class="btn btn-success">{{planet.name}}</b>
      </li>
      <ul class="interiorUL" [hidden]="!hidden[i]">
        <li>
            <span>Rotation period:</span> {{planet.rotation_period}} h
        </li>
        <li>
            <span>Orbital period:</span> {{planet.orbital_period}} days
        </li>
        <li>
            <span>Climate:</span> {{planet.climate}}
        </li>
        <li>
            <span>Planet terrain:</span> {{planet.terrain}}
        </li>
        <li>
          <span>Population:</span> {{planet.population}}
        </li>
        <li>
            <span>Gravity:</span> {{planet.gravity}}
        </li>
        <li>
            <span>Diameter:</span> {{planet.diameter}} km
        </li>

        <hr>
      </ul>
    </ul>
  </div>
</ng-container>
</code>```

答:
Simply hold a value in a variable, and let that variable decide which li is displayed :

currentListItem = 'name';
```

<pre class="lang-html prettyprint-override"><code><li *ngIf="currentListItem === 'name' (click)='currentListItem = 'name'">...</li>
<li *ngIf="currentListItem === 'climate' (click)='currentListItem = 'climate'">...</li>
<li *ngIf="currentListItem === 'terrain' (click)='currentListItem = 'terrain'">...</li>
</code>```

Title: angular disable button on dynamic list

Body:
My list is taking info from external API, Im creating it dynamically, When I click on the 'li' element (I create 10 of them) with (click) method bunch of info shows up (second ul list). The problem is that I want to disable all other elements (all other 9) that aren't clicked, ofc until I unclick that one I clicked before. Summing I want be able to click only 1 element at once others must be disable for that moment.
Could someone explain/show me how to do this?

<ng-container>

          {{planet.name}}

            Rotation period: {{planet.rotation_period}} h

            Orbital period: {{planet.orbital_period}} days

            Climate: {{planet.climate}}

            Planet terrain: {{planet.terrain}}

          Population: {{planet.population}}

            Gravity: {{planet.gravity}}

            Diameter: {{planet.diameter}} km

</ng-container>

Body:
Simply hold a value in a variable, and let that variable decide which li is displayed :

currentListItem = 'name';

<li *ngIf="currentListItem === 'name' (click)='currentListItem = 'name'">...</li>
<li *ngIf="currentListItem === 'climate' (click)='currentListItem = 'climate'">...</li>
<li *ngIf="currentListItem === 'terrain' (click)='currentListItem = 'terrain'">...</li>