问:
EF Core Customize JSON Serialization with LINQ
I am building out a demo for an API in .NET Core and constructing a nested JSON object that needs to get constructed through a series of LINQ queries.

My current issue is that when i get about 4 layers deep, I want to customize what actually gets serialized, more specifically, i want to "Not Include" specific navigation properties for this query specifically, but not for general purpose, only for this specific query.

My first thought was to do a DTO, but that seems like an unnecessary extra model just for this one specific case...i'd like to work with LINQ directly to manipulate for my result.

I have already added the following to my Startup.cs file to avoid cycles:

            services.AddControllers().AddNewtonsoftJson(options =>
            options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            );
```

<p>I have 5 models currently in action that look like this:</p>

<pre class="lang-cs prettyprint-override"><code> public class Hotel
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string StreetAddress { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Phone { get; set; }
        public List<HotelRooms> HotelRooms { get; set; }
    }

    public class Room
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public Layout Layout { get; set; }

        public List<RoomAmenities> RoomAmenities { get; set; }
        public List<HotelRooms> HotelRooms { get; set; }
    }

    public class HotelRooms
    {
        public int HotelID { get; set; }
        public int RoomNumber { get; set; }
        public int RoomID { get; set; }
        public decimal Rate { get; set; }
        public bool PetFriendly { get; set; }
        public Hotel Hotel { get; set; }
        public Room Room { get; set; }
    }

    public class Amenities
    {
        public int ID { get; set; }
        public string Name { get; set; }

        // Navigation Properties
        public List<RoomAmenities> RoomAmenities { get; set; }
    }

    public class RoomAmenities
    {
        public int RoomID { get; set; }
        public int AmenitiesID { get; set; }

        public Room Room { get; set; }
        public Amenities Amenity { get; set; }
    }

</code>```

In my services, i have this logic that is actually doing the querying:

        public async Task<Hotel> GetById(int id)
        {
            var hotel = await _context.Hotel.FindAsync(id);
            // Get a list of rooms
            var rooms = await _context.HotelRooms.Where(r => r.HotelID == id)
                                            .Include(d => d.Room)
                                            .ThenInclude(a => a.RoomAmenities)
                                            .ThenInclude(x => x.Amenity).ToListAsync();
            hotel.HotelRooms = rooms;

            return hotel;
        }
```

<p>The current output is:</p>

```{
    "id": 1,
    "name": "Amanda's Hotel",
    "streetAddress": "123 CandyCane Lane",
    "city": "Seattle",
    "state": "WA",
    "phone": "123-456-8798",
    "hotelRooms": [
        {
            "hotelID": 1,
            "roomNumber": 101,
            "roomID": 2,
            "rate": 75.00,
            "petFriendly": false,
            "room": {
                "id": 2,
                "name": "Queen Suite",
                "layout": 2,
                "roomAmenities": [
                    {
                        "roomID": 2,
                        "amenitiesID": 1,
                        "amenity": {
                            "id": 1,
                            "name": "Coffee Maker",
                            "roomAmenities": [
                                {
                                    "roomID": 1,
                                    "amenitiesID": 1,
                                    "room": {
                                        "id": 1,
                                        "name": "Princess Suite",
                                        "layout": 1,
                                        "roomAmenities": [
                                            {
                                                "roomID": 1,
                                                "amenitiesID": 2,
                                                "amenity": {
                                                    "id": 2,
                                                    "name": "Mini Bar",
                                                    "roomAmenities": []
                                                }
                                            }
                                        ],
                                        "hotelRooms": [
                                            {
                                                "hotelID": 1,
                                                "roomNumber": 123,
                                                "roomID": 1,
                                                "rate": 120.00,
                                                "petFriendly": true
                                            }
                                        ]
                                    }
                                }
                            ]
                        }
                    }
                ],
                "hotelRooms": []
            }
        },
        {
            "hotelID": 1,
            "roomNumber": 123,
            "roomID": 1,
            "rate": 120.00,
            "petFriendly": true,
            "room": {
                "id": 1,
                "name": "Princess Suite",
                "layout": 1,
                "roomAmenities": [
                    {
                        "roomID": 1,
                        "amenitiesID": 1,
                        "amenity": {
                            "id": 1,
                            "name": "Coffee Maker",
                            "roomAmenities": [
                                {
                                    "roomID": 2,
                                    "amenitiesID": 1,
                                    "room": {
                                        "id": 2,
                                        "name": "Queen Suite",
                                        "layout": 2,
                                        "roomAmenities": [],
                                        "hotelRooms": [
                                            {
                                                "hotelID": 1,
                                                "roomNumber": 101,
                                                "roomID": 2,
                                                "rate": 75.00,
                                                "petFriendly": false
                                            }
                                        ]
                                    }
                                }
                            ]
                        }
                    },
                    {
                        "roomID": 1,
                        "amenitiesID": 2,
                        "amenity": {
                            "id": 2,
                            "name": "Mini Bar",
                            "roomAmenities": []
                        }
                    }
                ],
                "hotelRooms": []
            }
        }
    ]
}
```

<p>This is much too nested for me, i'd like the inner "roomAmenities" inside the "amenity" object to not be included. I'd like my object to look like this:</p>

```{
  "id": 1,
  "name": "Amanda's Hotel",
  "streetAddress": "123 CandyCane Lane",
  "city": "Seattle",
  "state": "WA",
  "phone": "123-456-8798",
  "hotelRooms": [
    {
      "hotelID": 1,
      "roomNumber": 101,
      "roomID": 2,
      "rate": 75,
      "petFriendly": false,
      "room": {
        "id": 2,
        "name": "Queen Suite",
        "layout": 2,
        "roomAmenities": [
          {
            "roomID": 2,
            "amenitiesID": 1,
            "amenity": {
              "id": 1,
              "name": "Coffee Maker"
            }
          }
        ],
        "hotelRooms": []
      }
    },
    {
      "hotelID": 1,
      "roomNumber": 123,
      "roomID": 1,
      "rate": 120,
      "petFriendly": true,
      "room": {
        "id": 1,
        "name": "Princess Suite",
        "layout": 1,
        "roomAmenities": [
          {
            "roomID": 1,
            "amenitiesID": 1,
            "amenity": {
              "id": 1,
              "name": "Coffee Maker"
            }
          },
          {
            "roomID": 1,
            "amenitiesID": 2,
            "amenity": {
              "id": 2,
              "name": "Mini Bar"
            }
          }
        ],
        "hotelRooms": []
      }
    }
  ]
}
```

Does anyone have any guidance on how i can achieve this with EFCore and LINQ?

答:
you can check this post
What is the difference between PreserveReferencesHandling and ReferenceLoopHandling in Json.Net?

I see that you have already implemented referenceloopHandling, but even when you are using that you can only make the inner reference as null but not totally remove the key- value pair from json

Body:
I am building out a demo for an API in .NET Core and constructing a nested JSON object that needs to get constructed through a series of LINQ queries.

My current issue is that when i get about 4 layers deep, I want to customize what actually gets serialized, more specifically, i want to "Not Include" specific navigation properties for this query specifically, but not for general purpose, only for this specific query.

My first thought was to do a DTO, but that seems like an unnecessary extra model just for this one specific case...i'd like to work with LINQ directly to manipulate for my result.

I have already added the following to my Startup.cs file to avoid cycles:

            services.AddControllers().AddNewtonsoftJson(options =>
            options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            );

I have 5 models currently in action that look like this:

 public class Hotel
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string StreetAddress { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Phone { get; set; }
        public List<HotelRooms> HotelRooms { get; set; }
    }

    public class Room
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public Layout Layout { get; set; }

        public List<RoomAmenities> RoomAmenities { get; set; }
        public List<HotelRooms> HotelRooms { get; set; }
    }

    public class HotelRooms
    {
        public int HotelID { get; set; }
        public int RoomNumber { get; set; }
        public int RoomID { get; set; }
        public decimal Rate { get; set; }
        public bool PetFriendly { get; set; }
        public Hotel Hotel { get; set; }
        public Room Room { get; set; }
    }

    public class Amenities
    {
        public int ID { get; set; }
        public string Name { get; set; }

        // Navigation Properties
        public List<RoomAmenities> RoomAmenities { get; set; }
    }

    public class RoomAmenities
    {
        public int RoomID { get; set; }
        public int AmenitiesID { get; set; }

        public Room Room { get; set; }
        public Amenities Amenity { get; set; }
    }

In my services, i have this logic that is actually doing the querying:

        public async Task<Hotel> GetById(int id)
        {
            var hotel = await _context.Hotel.FindAsync(id);
            // Get a list of rooms
            var rooms = await _context.HotelRooms.Where(r => r.HotelID == id)
                                            .Include(d => d.Room)
                                            .ThenInclude(a => a.RoomAmenities)
                                            .ThenInclude(x => x.Amenity).ToListAsync();
            hotel.HotelRooms = rooms;

            return hotel;
        }

The current output is:

{
    "id": 1,
    "name": "Amanda's Hotel",
    "streetAddress": "123 CandyCane Lane",
    "city": "Seattle",
    "state": "WA",
    "phone": "123-456-8798",
    "hotelRooms": [
        {
            "hotelID": 1,
            "roomNumber": 101,
            "roomID": 2,
            "rate": 75.00,
            "petFriendly": false,
            "room": {
                "id": 2,
                "name": "Queen Suite",
                "layout": 2,
                "roomAmenities": [
                    {
                        "roomID": 2,
                        "amenitiesID": 1,
                        "amenity": {
                            "id": 1,
                            "name": "Coffee Maker",
                            "roomAmenities": [
                                {
                                    "roomID": 1,
                                    "amenitiesID": 1,
                                    "room": {
                                        "id": 1,
                                        "name": "Princess Suite",
                                        "layout": 1,
                                        "roomAmenities": [
                                            {
                                                "roomID": 1,
                                                "amenitiesID": 2,
                                                "amenity": {
                                                    "id": 2,
                                                    "name": "Mini Bar",
                                                    "roomAmenities": []
                                                }
                                            }
                                        ],
                                        "hotelRooms": [
                                            {
                                                "hotelID": 1,
                                                "roomNumber": 123,
                                                "roomID": 1,
                                                "rate": 120.00,
                                                "petFriendly": true
                                            }
                                        ]
                                    }
                                }
                            ]
                        }
                    }
                ],
                "hotelRooms": []
            }
        },
        {
            "hotelID": 1,
            "roomNumber": 123,
            "roomID": 1,
            "rate": 120.00,
            "petFriendly": true,
            "room": {
                "id": 1,
                "name": "Princess Suite",
                "layout": 1,
                "roomAmenities": [
                    {
                        "roomID": 1,
                        "amenitiesID": 1,
                        "amenity": {
                            "id": 1,
                            "name": "Coffee Maker",
                            "roomAmenities": [
                                {
                                    "roomID": 2,
                                    "amenitiesID": 1,
                                    "room": {
                                        "id": 2,
                                        "name": "Queen Suite",
                                        "layout": 2,
                                        "roomAmenities": [],
                                        "hotelRooms": [
                                            {
                                                "hotelID": 1,
                                                "roomNumber": 101,
                                                "roomID": 2,
                                                "rate": 75.00,
                                                "petFriendly": false
                                            }
                                        ]
                                    }
                                }
                            ]
                        }
                    },
                    {
                        "roomID": 1,
                        "amenitiesID": 2,
                        "amenity": {
                            "id": 2,
                            "name": "Mini Bar",
                            "roomAmenities": []
                        }
                    }
                ],
                "hotelRooms": []
            }
        }
    ]
}

This is much too nested for me, i'd like the inner "roomAmenities" inside the "amenity" object to not be included. I'd like my object to look like this:

{
  "id": 1,
  "name": "Amanda's Hotel",
  "streetAddress": "123 CandyCane Lane",
  "city": "Seattle",
  "state": "WA",
  "phone": "123-456-8798",
  "hotelRooms": [
    {
      "hotelID": 1,
      "roomNumber": 101,
      "roomID": 2,
      "rate": 75,
      "petFriendly": false,
      "room": {
        "id": 2,
        "name": "Queen Suite",
        "layout": 2,
        "roomAmenities": [
          {
            "roomID": 2,
            "amenitiesID": 1,
            "amenity": {
              "id": 1,
              "name": "Coffee Maker"
            }
          }
        ],
        "hotelRooms": []
      }
    },
    {
      "hotelID": 1,
      "roomNumber": 123,
      "roomID": 1,
      "rate": 120,
      "petFriendly": true,
      "room": {
        "id": 1,
        "name": "Princess Suite",
        "layout": 1,
        "roomAmenities": [
          {
            "roomID": 1,
            "amenitiesID": 1,
            "amenity": {
              "id": 1,
              "name": "Coffee Maker"
            }
          },
          {
            "roomID": 1,
            "amenitiesID": 2,
            "amenity": {
              "id": 2,
              "name": "Mini Bar"
            }
          }
        ],
        "hotelRooms": []
      }
    }
  ]
}

Does anyone have any guidance on how i can achieve this with EFCore and LINQ?


来源: stackexchange

问:
How do I download only files that start with a value and end with other values?
I'm trying to use aws s3 cp s3a://path/to/directory/dt=2019* ./home/directory/ --recursive. It's on aws obviously but I don't want any parquet files coming from other years like 2017 and 2018 or 2020. I only want data from 2019, which means that the file is going to be dt=2019 plus -01-01, -01-02 , -01-03, ... etc.

How do I do this?

答:
According to the documentation here you need to provide exclude and include arguments:</p>

```<code>aws s3 cp s3://path/to/directory/ ./home/directory/ --recursive --exclude "*" --include "dt=2019*"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
According to the documentation here you need to provide exclude and include arguments:

aws s3 cp s3://path/to/directory/ ./home/directory/ --recursive --exclude "*" --include "dt=2019*"


问:
Android close keyboard by pressing 'done' called from a SearchView inside an AlertDialog
From a Fragment, I am using a SearchView inside an AlertDialog and I would like the keyboard's 'Done' button to dismiss the keyboard. For some reason it is not working.

Here is my AlertDialog"

```<code>val mBuilder =
        AlertDialog.Builder(context!!, Theme_DeviceDefault_Light_NoActionBar_Fullscreen)
val mView = View.inflate(activity!!, R.layout.list_search, null)
mBuilder.setView(mView)
val dialog = mBuilder.create()
val searchView = view.findViewById<SearchView>(R.id.search_view)
dialog.show()

searchView.setImeOptions(EditorInfo.IME_ACTION_DONE)

searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
    override fun onQueryTextChange(newText: String): Boolean {
        adapterWithSearch.filter(newText)
        return true
    }

    override fun onQueryTextSubmit(query: String): Boolean {
        adapterWithSearch.filter(query)
        return true
    }
})
</code>```

And here is my SearchView:

```<code><SearchView
    android:id="@+id/searchView"
    style="@style/AppTheme.Searches"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:actionViewClass="android.support.v7.widget.SearchView"
    android:iconifiedByDefault="false"
    android:imeOptions="actionDone"
    android:inputType="text"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:clickable="true" />
</code>```

I would like the keyboard to be dismissed, not the AlertDialog.
Anyone has an idea of why the keyboard isn't being dismissed?

答:
Probably I am not seeing correctly what you are trying to do but I can not see where are you trying to dismiss the keyboard. For this action you have two alternatives:

Try to see this and hope it is helpful

Close/hide the Android Soft Keyboard with Kotlin

You have here different ways to dismiss a keyboard. I don't see more complexity in this question.

Also I found this -->
How to dismiss keyboard in Android SearchView?

Body:
From a Fragment, I am using a SearchView inside an AlertDialog and I would like the keyboard's 'Done' button to dismiss the keyboard. For some reason it is not working.

Here is my AlertDialog"

val mBuilder =
        AlertDialog.Builder(context!!, Theme_DeviceDefault_Light_NoActionBar_Fullscreen)
val mView = View.inflate(activity!!, R.layout.list_search, null)
mBuilder.setView(mView)
val dialog = mBuilder.create()
val searchView = view.findViewById<SearchView>(R.id.search_view)
dialog.show()

searchView.setImeOptions(EditorInfo.IME_ACTION_DONE)

searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
    override fun onQueryTextChange(newText: String): Boolean {
        adapterWithSearch.filter(newText)
        return true
    }

    override fun onQueryTextSubmit(query: String): Boolean {
        adapterWithSearch.filter(query)
        return true
    }
})

And here is my SearchView:

<SearchView
    android:id="@+id/searchView"
    style="@style/AppTheme.Searches"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:actionViewClass="android.support.v7.widget.SearchView"
    android:iconifiedByDefault="false"
    android:imeOptions="actionDone"
    android:inputType="text"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:clickable="true" />

I would like the keyboard to be dismissed, not the AlertDialog.
Anyone has an idea of why the keyboard isn't being dismissed?


问:
Dereference Operator Before an Array Element?
What does the notation in something like int y = *x[0] do, i.e. when you have a dereference operator right before an array element?

答:
this will only make sense if you have an array of pointers to intgers :

```<code> int var = *x[0]
</code>```

means that x is a table of pointers and var will take the value pointed by the first element (pointer) in this array

Body:
this will only make sense if you have an array of pointers to intgers :

 int var = *x[0]

means that x is a table of pointers and var will take the value pointed by the first element (pointer) in this array


问:
How do I find the mean of summed values across multiple Dataframes?
Edit: I've realized that I did not ask my question in the right way. I'm not going to accept one answer over another, but am going to leave all content here for anyone's future use.

I have a value that I'm looking to compute across on-going DataFrames.

I have df1:

```<code>Name    |   Col1   | Col2
----------------------------
'Silvers'|    7    |   1
'Jones'  |    7    |   2
'Jackson'|    4    |  NaN
'Merole' |   NaN   |   2
'Kanoff' |   NaN   |   5
'Walker' |   NaN   |   8
'Smith'  |    8    |   0
</code>```

I'd like to sum the Col1 and Col2 columns that results in a new column, Col3. I already have a solution that sums correctly if there is a value present in both columns, returns the non-null value if there is a NaN value present, and returns NaN if both values are NaN. So that resulting DataFrame, df2 would look like this:

```<code>Name    |   Col1  |  Col2  |  Col_Sum
-------------------------------------
'Silvers'|    7    |   1   |     8
'Jones'  |    7    |   2   |     9
'Jackson'|    4    |  NaN  |     4
'Merole' |   NaN   |   2   |     2
'Kanoff' |   NaN   |   NaN |    NaN
'Walker' |   NaN   |   8   |     8
'Smith'  |   NaN   |  NaN  |    NaN
</code>```

For df3, when I have new data, I'd like to perform the same sum operations as I did above, but then find the average of only the non-null values that were included in the summation in prior DataFrames.

I want this for df3:

```<code>Name    |   Col1   |  Col2 |  Col_Sum |    Cols_Avg
-------------------------------------------------------
'Silvers'|    3    |   3   |     6    |      3.5
'Jones'  |    1    |   6   |     7    |       4
'Jackson'|   NaN   |   9   |     9    |      6.5
'Merole' |   NaN   |  NaN  |    NaN   |       2
'Kanoff' |   NaN   |   7   |     7    |       7
'Walker' |    4    |   8   |     12   |      6.67
'Smith'  |   NaN   |  NaN  |    NaN   |      NaN
</code>```

I'd then like to continue that trend with each new DataFrame of data that I get, summing the values and computing their averages based on how many values there are for the same row across all the Dataframes. I'm not sure how to accomplish this or if I'm even using the correct tools to do so. Any help is much appreciated. Thanks!

答:
Probably you can use pd.merge:

```<code>df2 = pd.DataFrame({'Name':['Silvers', 'Jones', 'Jackson', 'Merole'], 'Col1':[7,7,4,np.nan], 'Col2':[1,2,np.nan,2]})
df3 = pd.DataFrame({'Name':['Silvers', 'Jones', 'Jackson', 'Merole'], 'Col1':[3,1,np.nan,np.nan], 'Col2':[3,6,9,np.nan]})

dfn = pd.merge(df2, df3, on='Name')
dfn['ColsAvg'] = dfn.mean(axis=1)
</code>```

For ease I put everything in a new DataFrame dfn. If you want to put ColsAvg in df3 as you write, sure this is possible.

Body:
Edit: I've realized that I did not ask my question in the right way. I'm not going to accept one answer over another, but am going to leave all content here for anyone's future use.

I have a value that I'm looking to compute across on-going DataFrames.

I have df1:

Name    |   Col1   | Col2
----------------------------
'Silvers'|    7    |   1
'Jones'  |    7    |   2
'Jackson'|    4    |  NaN
'Merole' |   NaN   |   2
'Kanoff' |   NaN   |   5
'Walker' |   NaN   |   8
'Smith'  |    8    |   0

I'd like to sum the Col1 and Col2 columns that results in a new column, Col3. I already have a solution that sums correctly if there is a value present in both columns, returns the non-null value if there is a NaN value present, and returns NaN if both values are NaN. So that resulting DataFrame, df2 would look like this:

Name    |   Col1  |  Col2  |  Col_Sum
-------------------------------------
'Silvers'|    7    |   1   |     8
'Jones'  |    7    |   2   |     9
'Jackson'|    4    |  NaN  |     4
'Merole' |   NaN   |   2   |     2
'Kanoff' |   NaN   |   NaN |    NaN
'Walker' |   NaN   |   8   |     8
'Smith'  |   NaN   |  NaN  |    NaN

For df3, when I have new data, I'd like to perform the same sum operations as I did above, but then find the average of only the non-null values that were included in the summation in prior DataFrames.

I want this for df3:

Name    |   Col1   |  Col2 |  Col_Sum |    Cols_Avg
-------------------------------------------------------
'Silvers'|    3    |   3   |     6    |      3.5
'Jones'  |    1    |   6   |     7    |       4
'Jackson'|   NaN   |   9   |     9    |      6.5
'Merole' |   NaN   |  NaN  |    NaN   |       2
'Kanoff' |   NaN   |   7   |     7    |       7
'Walker' |    4    |   8   |     12   |      6.67
'Smith'  |   NaN   |  NaN  |    NaN   |      NaN

I'd then like to continue that trend with each new DataFrame of data that I get, summing the values and computing their averages based on how many values there are for the same row across all the Dataframes. I'm not sure how to accomplish this or if I'm even using the correct tools to do so. Any help is much appreciated. Thanks!

Body:
Probably you can use pd.merge:

df2 = pd.DataFrame({'Name':['Silvers', 'Jones', 'Jackson', 'Merole'], 'Col1':[7,7,4,np.nan], 'Col2':[1,2,np.nan,2]})
df3 = pd.DataFrame({'Name':['Silvers', 'Jones', 'Jackson', 'Merole'], 'Col1':[3,1,np.nan,np.nan], 'Col2':[3,6,9,np.nan]})

dfn = pd.merge(df2, df3, on='Name')
dfn['ColsAvg'] = dfn.mean(axis=1)

For ease I put everything in a new DataFrame dfn. If you want to put ColsAvg in df3 as you write, sure this is possible.


问:
Session vs URI multi language identifier
I am working on a multilingual website (php/mysql) and my question is what would be the best solution for language identification - sessions/cookies or URI identification.  I mean in terms of SEO, what would be more accurate.

Thanks

答:
There are different types of projects which shouldn't use the same language implementation.

Let me give some examples:

The first project has an single domain name, let's say example.com. This website, should be available in three languages. In order to let the search engine clearly crawl and index each language - the correct solution here would be passing it by url. example.com/fr/ for french.

The second project, has an domain name for each language, example.fr, example.co.uk. It would be best that each domain is only indexed by the search engine by it's primary language. Therefor, the solution I'd pick would be storing the language in a cookie when switching. (or redirect to the other domain entirely).

If we'd pick the solution of example 1 for example 2, both example.co.uk/fr/ and example.fr would have the same content, which isn't SEO friendly.

ContentLicense: CC BY-SA 3.0


问:
Send custom data to google analytics from server side
I want to send these information title, target amount, category, account name to GA for every user who creates a page in our website. And if anyone make transaction on that page I want to generate a revenue of 5% based on the transaction amount for every transaction. I've no clue how to do that.

So far what I've achieved is I set up the service account by following this link and create a custom dimension. Playing with the code snippet I can update the name of the dimension and other things but not sure how to send an object value with all the fields that I need in this custom dimension. My question is if I call this again will it update and replace the old value with the new value? I don't want that. Every time I want to insert a new value in the old value. Shall I need another dimension and what if I want to relate this custom dimension data to ecommerce later on. How can I do that?

```<code>try:
  analytics.management().customDimensions().update(
      accountId='123456',
      webPropertyId='UA-123456-1',
      customDimensionId='ga:dimension2',
      body={
          'name': 'Campaign Group',
          'scope': 'SESSION',
          'active': True
      }
  ).execute()
</code>```

Can someone please suggest me what should I do here.

答:
This article should help you achieve what you want.
Basically the custom dimensions in your url should be like cd1, cd2 so on...

https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters?hl=en#customs

Here is a code sample that might help
https://www.simoahava.com/analytics/13-useful-custom-dimensions-for-google-analytics/#23-payload-length

Body:
I want to send these information title, target amount, category, account name to GA for every user who creates a page in our website. And if anyone make transaction on that page I want to generate a revenue of 5% based on the transaction amount for every transaction. I've no clue how to do that.

So far what I've achieved is I set up the service account by following this link and create a custom dimension. Playing with the code snippet I can update the name of the dimension and other things but not sure how to send an object value with all the fields that I need in this custom dimension. My question is if I call this again will it update and replace the old value with the new value? I don't want that. Every time I want to insert a new value in the old value. Shall I need another dimension and what if I want to relate this custom dimension data to ecommerce later on. How can I do that?

try:
  analytics.management().customDimensions().update(
      accountId='123456',
      webPropertyId='UA-123456-1',
      customDimensionId='ga:dimension2',
      body={
          'name': 'Campaign Group',
          'scope': 'SESSION',
          'active': True
      }
  ).execute()

Can someone please suggest me what should I do here.


问:
how to concatenate parameters with variable of body in react native
i have to concatenate the variable with parameters to get the json response

```<code>body: `category_id=208&sort_by=low`
</code>```

i have to pass like this token value in vaiagtion between screens but while concatenating the value it shows token is an templatestring

```<code>let Token = this.params.token;
let Token = 209;
body:`category_id=`+{Token}+`&sort_by=low`,
</code>```

this is the error response:-

```<code>error response: TypeError: {
                    Token: Token
                  } is not a function. (In '{
                    Token: Token
                  }(_templateObject())', '{
                    Token: Token
                  }' is an instance of Object)
</code>```

so how should i concatenate the parameters with variable ?

答:
It looks like you might be mixing the syntax for string concatenation and template literals.

You can concatenate the strings: 'category_id=' + Token + '&sort_by=low'

Or you can use template literals (introduced in ES6): `category_id=${Token}&sort_by=low`

You can read more about template literals here.

Hope that helps!

Body:
i have to concatenate the variable with parameters to get the json response

body: `category_id=208&sort_by=low`

i have to pass like this token value in vaiagtion between screens but while concatenating the value it shows token is an templatestring

let Token = this.params.token;
let Token = 209;
body:`category_id=`+{Token}+`&sort_by=low`,

this is the error response:-

error response: TypeError: {
                    Token: Token
                  } is not a function. (In '{
                    Token: Token
                  }(_templateObject())', '{
                    Token: Token
                  }' is an instance of Object)

so how should i concatenate the parameters with variable ?


问:
Programmatically Triggering CloudWatch Events From Inside AWS Lambda
I wrote an AWS lambda that processes data from S3 and gets some result X (map String -> Date). Now I wanted to send the result X as a custom CloudWatch Event event so a CloudWatch Alarm can pick the event and trigger the alarm so the person addressing the alarm can see the result X.

I am stuck on how to programmatically send an event (CloudWatch Event) to CloudWatch so CloudWatch Alarm can pick it. Any help is appreciated.

答:
putEvents from https://docs.aws.amazon.com/sdk-for-java/v2/developer-guide/examples-cloudwatch-send-events.html:

```<code>CloudWatchEventsClient cwe =
        CloudWatchEventsClient.builder().build();

final String EVENT_DETAILS =
    "{ \"key1\": \"value1\", \"key2\": \"value2\" }";

PutEventsRequestEntry request_entry = PutEventsRequestEntry.builder()
    .detail(EVENT_DETAILS)
    .detailType("sampleSubmitted")
    .resources(resource_arn)
    .source("aws-sdk-java-cloudwatch-example").build();

PutEventsRequest request = PutEventsRequest.builder()
    .entries(request_entry).build();

PutEventsResponse response = cwe.putEvents(request);
</code>```

Body:
putEvents from https://docs.aws.amazon.com/sdk-for-java/v2/developer-guide/examples-cloudwatch-send-events.html:

CloudWatchEventsClient cwe =
        CloudWatchEventsClient.builder().build();

final String EVENT_DETAILS =
    "{ \"key1\": \"value1\", \"key2\": \"value2\" }";

PutEventsRequestEntry request_entry = PutEventsRequestEntry.builder()
    .detail(EVENT_DETAILS)
    .detailType("sampleSubmitted")
    .resources(resource_arn)
    .source("aws-sdk-java-cloudwatch-example").build();

PutEventsRequest request = PutEventsRequest.builder()
    .entries(request_entry).build();

PutEventsResponse response = cwe.putEvents(request);


问:
Changing formulas on the fly with VBA RegEx
i'm trying to change formulas in excel, i need to change the row number of the formulas.

I'm trying do use replace regex to do this. I use an loop to iterate through the rows of the excel and need to change the formula for the row that is iterating at the time. Here is an exemple of the code:

```<code>    For i = 2 To rows_aux
            DoEvents

            Formula_string= "=IFS(N19='Z001';'xxxxxx';N19='Z007';'xxxxxx';0=0;'xxxxxxx')"
            Formula_string_new = regEx.Replace(Formula_string, "$1" & i)
            wb.Cells(i, 33) = ""
            wb.Cells(i, 33).Formula = Formula_string_new
      .
      .
      .
   Next i
</code>```

I need to replace rows references but not the ones in quotes or double quotes. Example:
If i = 2 i want the new string to be this:

```<code>"=IFS(N2='Z001';'xxxxxx';N2='Z007';'xxxxxx';0=0;'xxxxxxx')"
</code>```

I'm trying to use this regex:

```<code>([a-zA-Z]+)(\d+)
</code>```

But its changing everything in quotes too. Like this:
If i = 2:

```<code>"=IFS(N2='Z2';'xxxxxx';N2='Z2';'xxxxxx';0=0;'xxxxxxx')"
</code>```

If anyone can help me i will be very grateful!
Thanks in advance.

答:
As others have written, there are probably better ways to write this code.  But for a regex that will capture just the Column letter in capturing group #1, try:

```<code>\$?\b(XF[A-D]|X[A-E][A-Z]|[A-W][A-Z]{2}|[A-Z]{2}|[A-Z])\$?(?:104857[0-6]|10485[0-6]\d|1048[0-4]\d{2}|104[0-7]\d{3}|10[0-3]\d{4}|[1-9]\d{1,5}|[1-9])d?
</code>```

Note that is will NOT include the $ absolute addressing token, but could be altered if that were necessary.

Note that you can avoid the loop completely with:

```<code>    Formula_string = "=IFS(N19=""Z001"",""xxxxxx"",N$19=""Z007"",""xxxxxx"",0=0,""xxxxxxx"")"
    Formula_string_new = regEx.Replace(Formula_string, "$1" & firstRow)

With Range(wb.Cells(firstRow, 33), wb.Cells(lastRow, 33))
    .Clear
    .Formula = Formula_string_new
End With
</code>```

When we write a formula to a range like this, the references will automatically adjust the way you were doing in your loop.

Depending on unstated factors, you may want to use the FormulaLocal property vice the Formula property.

Edit:

To make this a little more robust, in case there happens to be, within the quote marks, a string that exactly mimics a valid address, you can try checking to be certain that a quote (single or double) neither precedes nor follows the target.

```<code>Pattern:    ([^"'])\$?\b(XF[A-D]|X[A-E][A-Z]|[A-W][A-Z]{2}|[A-Z]{2}|[A-Z])\$?(?:104857[0-6]|10485[0-6]\d|1048[0-4]\d{2}|104[0-7]\d{3}|10[0-3]\d{4}|[1-9]\d{1,5}|[1-9])d?\b(?!['"])

Replace:    "$1$2" & i
</code>```

However, this is not "bulletproof" as various combinations of included data might match. If it is a problem, let me know and I'll come up with something more robust.

Body:
i'm trying to change formulas in excel, i need to change the row number of the formulas.

I'm trying do use replace regex to do this. I use an loop to iterate through the rows of the excel and need to change the formula for the row that is iterating at the time. Here is an exemple of the code:

    For i = 2 To rows_aux
            DoEvents

            Formula_string= "=IFS(N19='Z001';'xxxxxx';N19='Z007';'xxxxxx';0=0;'xxxxxxx')"
            Formula_string_new = regEx.Replace(Formula_string, "$1" & i)
            wb.Cells(i, 33) = ""
            wb.Cells(i, 33).Formula = Formula_string_new
      .
      .
      .
   Next i

I need to replace rows references but not the ones in quotes or double quotes. Example:
If i = 2 i want the new string to be this:

"=IFS(N2='Z001';'xxxxxx';N2='Z007';'xxxxxx';0=0;'xxxxxxx')"

I'm trying to use this regex:

([a-zA-Z]+)(\d+)

But its changing everything in quotes too. Like this:
If i = 2:

"=IFS(N2='Z2';'xxxxxx';N2='Z2';'xxxxxx';0=0;'xxxxxxx')"

If anyone can help me i will be very grateful!
Thanks in advance.

Body:
As others have written, there are probably better ways to write this code.  But for a regex that will capture just the Column letter in capturing group #1, try:

\$?\b(XF[A-D]|X[A-E][A-Z]|[A-W][A-Z]{2}|[A-Z]{2}|[A-Z])\$?(?:104857[0-6]|10485[0-6]\d|1048[0-4]\d{2}|104[0-7]\d{3}|10[0-3]\d{4}|[1-9]\d{1,5}|[1-9])d?

Note that is will NOT include the $ absolute addressing token, but could be altered if that were necessary.

Note that you can avoid the loop completely with:

    Formula_string = "=IFS(N19=""Z001"",""xxxxxx"",N$19=""Z007"",""xxxxxx"",0=0,""xxxxxxx"")"
    Formula_string_new = regEx.Replace(Formula_string, "$1" & firstRow)

With Range(wb.Cells(firstRow, 33), wb.Cells(lastRow, 33))
    .Clear
    .Formula = Formula_string_new
End With

When we write a formula to a range like this, the references will automatically adjust the way you were doing in your loop.

Depending on unstated factors, you may want to use the FormulaLocal property vice the Formula property.

Edit:

To make this a little more robust, in case there happens to be, within the quote marks, a string that exactly mimics a valid address, you can try checking to be certain that a quote (single or double) neither precedes nor follows the target.

Pattern:    ([^"'])\$?\b(XF[A-D]|X[A-E][A-Z]|[A-W][A-Z]{2}|[A-Z]{2}|[A-Z])\$?(?:104857[0-6]|10485[0-6]\d|1048[0-4]\d{2}|104[0-7]\d{3}|10[0-3]\d{4}|[1-9]\d{1,5}|[1-9])d?\b(?!['"])

Replace:    "$1$2" & i

However, this is not "bulletproof" as various combinations of included data might match. If it is a problem, let me know and I'll come up with something more robust.


问:
Build cython extension in fresh environment: cannot find /lib/libpthread.so.0
I am trying to deploy a package that uses some cython extensions. I have written the following setup script:

```<code>import os
import sys
from setuptools import setup, Extension

# factory function
def my_build_ext(pars):
    # import delayed:
    from setuptools.command.build_ext import build_ext as _build_ext

    # include_dirs adjusted:
    class build_ext(_build_ext):
        def finalize_options(self):
            _build_ext.finalize_options(self)
            # Prevent numpy from thinking it is still in its setup process:
            __builtins__.__NUMPY_SETUP__ = False
            import numpy
            self.include_dirs.append(numpy.get_include())

    #object returned:
    return build_ext(pars)

# cython c++ extensions
extnames = [
    'npextc',
    'intquickheapdict',
    'FixedOrderedIntDict'
    ]

...

PATHADD = 'vemomoto_core/npcollections/'
PACKAGEADD = PATHADD.replace("/", ".")

ext = '.pyx'

extensions = [Extension(PACKAGEADD+name, [PATHADD+name+ext],
                        extra_compile_args=['-std=c++11', '-O3']+parcompileargs,
                        extra_link_args=parlinkargs,
                        )
              for name in extnames]
for e in extensions:
    e.language_level = 3
    e.language = 'c++'

setup(
    name="vemomoto_core_npcollections",
    version="0.9.0.a7",
    cmdclass={'build_ext' : my_build_ext},
    setup_requires=['numpy', 'setuptools>=18.0'],
    install_requires=['numpy', 'scipy'],
    python_requires='>=3.6',
    packages=['vemomoto_core', PACKAGEADD[:-1]],
    ext_modules=extensions,
    package_data={
        '': ['*.pxd', '*.pyx', '*.c', '*.cpp'],
    },
    zip_safe=False,
)
</code>```

When I build the package via executing pip install . in the directory of the setup.py, everything works fine as long as I work in my default environment. However, when I test the process in a fresh testing environment, I get the error

```<code>    /home/user/anaconda3/envs/test37/compiler_compat/ld: cannot find /lib/libpthread.so.0
    /home/user/anaconda3/envs/test37/compiler_compat/ld: cannot find /usr/lib/libpthread_nonshared.a
    collect2: error: ld returned 1 exit status
    error: command 'g++' failed with exit status 1
</code>```

(Full output is below.)

I assume that there is some dependency missing here, but I have no idea how I could find out what it is and thus how to resolve the error. What could I do?

Full error message:

```<code>Building wheels for collected packages: vemomoto-core-npcollections                                                                                [76/1898]
  Building wheel for vemomoto-core-npcollections (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: /home/user/anaconda3/envs/test37/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-req-build-0_ns61r9/setup.py'"'"'; __file__='"'"'/tmp/pip-req-build-0_ns61r9/se
tup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-4zeu
yeay
       cwd: /tmp/pip-req-build-0_ns61r9/
  Complete output (49 lines):
  /home/user/anaconda3/envs/test37/lib/python3.7/site-packages/setuptools/dist.py:476: UserWarning: Normalizing '0.9.0.a1' to '0.9.0a1'
    normalized_version,
  running bdist_wheel
  running build
  running build_py
  package init file 'vemomoto_core/__init__.py' not found (or not a regular file)
  creating build
  creating build/lib.linux-x86_64-3.7
  creating build/lib.linux-x86_64-3.7/vemomoto_core
  creating build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/_setup_npextc.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/sparse3d.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/_setup_FixedOrderedIntDict.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/_FixedOrderedIntDict_reduce.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/__init__.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections                                                                                copying vemomoto_core/npcollections/_setup_intquickheapdict.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections                                                                                copying vemomoto_core/npcollections/npext.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/_npextc_utils.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/__init__.pxd -> build/lib.linux-x86_64-3.7/vemomoto_core
  copying vemomoto_core/npcollections/FixedOrderedIntDict.pxd -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/npextc.pxd -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/intquickheapdict.pxd -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/intquickheapdict.pyx -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections                                                                                copying vemomoto_core/npcollections/npextc.pyx -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/FixedOrderedIntDict.pyx -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/heapoperations_c.c -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/sectionsum.c -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections                                                                                copying vemomoto_core/npcollections/intquickheapdict.cpp -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections                                                                                copying vemomoto_core/npcollections/FixedOrderedIntDict.cpp -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/npextc.cpp -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  running build_ext
  building 'vemomoto_core.npcollections.npextc' extension
  creating build/temp.linux-x86_64-3.7
  creating build/temp.linux-x86_64-3.7/vemomoto_core
  creating build/temp.linux-x86_64-3.7/vemomoto_core/npcollections                                                                                gcc -pthread -B /home/user/anaconda3/envs/test37/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/user/anaconda3/envs/test37/include/python3.7m -I/home/user/anaconda3/envs/test37/lib/python3.7/site-packages/numpy/core/include -c vemomoto_core/npcollections/npextc.cpp -o build/temp.linux-x86_64-3.7/vemomoto_core/npcollections/npextc.o -std=c++11 -O3 -fopenmp
  cc1plus: warning: command line option '-Wstrict-prototypes' is valid for C/ObjC but not for C++
  In file included from /home/user/anaconda3/envs/test37/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1832:0,
                   from /home/user/anaconda3/envs/test37/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,
                   from /home/user/anaconda3/envs/test37/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,
                   from vemomoto_core/npcollections/npextc.cpp:636:
  /home/user/anaconda3/envs/test37/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning "Using deprecated NumPy API, disable it with " "#define NPY_NO_DEP
RECATED_API NPY_1_7_API_VERSION" [-Wcpp]
   #warning "Using deprecated NumPy API, disable it with " \
    ^~~~~~~
  g++ -pthread -shared -B /home/user/anaconda3/envs/test37/compiler_compat -L/home/user/anaconda3/envs/test37/lib -Wl,-rpath=/home/user/anaconda3/envs/test37/lib -Wl,--no-as-needed -Wl,--sysroot=
/ -Wl,-O2 -Wl,--sort-common -Wl,--as-needed -Wl,-z,relro -Wl,-z,now -Wl,--disable-new-dtags -Wl,--gc-sections build/temp.linux-x86_64-3.7/vemomoto_core/npcollections/npextc.o -o build/lib.linux-x86_64-3.7/ve
momoto_core/npcollections/npextc.cpython-37m-x86_64-linux-gnu.so -fopenmp
  /home/user/anaconda3/envs/test37/compiler_compat/ld: cannot find /lib/libpthread.so.0
  /home/user/anaconda3/envs/test37/compiler_compat/ld: cannot find /usr/lib/libpthread_nonshared.a
  collect2: error: ld returned 1 exit status
  error: command 'g++' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for vemomoto-core-npcollections
  Running setup.py clean for vemomoto-core-npcollections
Failed to build vemomoto-core-npcollections

</code>```

答:
To solve the issue, I have compared the fresh anaconda environment with the one I used. To this end, I used

```<code>conda list
</code>```

in both the older and the fresh installation and compared the output. Then I looked for packages that were included in the old environment but not in the new environment and that had a name suggesting that they may include the right files.

After installing the candidates and retrying the build, I found that gxx_linux-64 (and for another package cmake) were necessary requirements to build. As these packages seem not to be available on PyPI, I will require end users to use the anaconda commands

```<code>conda install gxx_linux-64
conda install cmake
</code>```

Before installing my package. It would be nice to include this dependency in the setup script, but this is another question...

Body:
I am trying to deploy a package that uses some cython extensions. I have written the following setup script:

import os
import sys
from setuptools import setup, Extension

# factory function
def my_build_ext(pars):
    # import delayed:
    from setuptools.command.build_ext import build_ext as _build_ext

    # include_dirs adjusted:
    class build_ext(_build_ext):
        def finalize_options(self):
            _build_ext.finalize_options(self)
            # Prevent numpy from thinking it is still in its setup process:
            __builtins__.__NUMPY_SETUP__ = False
            import numpy
            self.include_dirs.append(numpy.get_include())

    #object returned:
    return build_ext(pars)

# cython c++ extensions
extnames = [
    'npextc',
    'intquickheapdict',
    'FixedOrderedIntDict'
    ]

...

PATHADD = 'vemomoto_core/npcollections/'
PACKAGEADD = PATHADD.replace("/", ".")

ext = '.pyx'

extensions = [Extension(PACKAGEADD+name, [PATHADD+name+ext],
                        extra_compile_args=['-std=c++11', '-O3']+parcompileargs,
                        extra_link_args=parlinkargs,
                        )
              for name in extnames]
for e in extensions:
    e.language_level = 3
    e.language = 'c++'

setup(
    name="vemomoto_core_npcollections",
    version="0.9.0.a7",
    cmdclass={'build_ext' : my_build_ext},
    setup_requires=['numpy', 'setuptools>=18.0'],
    install_requires=['numpy', 'scipy'],
    python_requires='>=3.6',
    packages=['vemomoto_core', PACKAGEADD[:-1]],
    ext_modules=extensions,
    package_data={
        '': ['*.pxd', '*.pyx', '*.c', '*.cpp'],
    },
    zip_safe=False,
)

When I build the package via executing pip install . in the directory of the setup.py, everything works fine as long as I work in my default environment. However, when I test the process in a fresh testing environment, I get the error

    /home/user/anaconda3/envs/test37/compiler_compat/ld: cannot find /lib/libpthread.so.0
    /home/user/anaconda3/envs/test37/compiler_compat/ld: cannot find /usr/lib/libpthread_nonshared.a
    collect2: error: ld returned 1 exit status
    error: command 'g++' failed with exit status 1

(Full output is below.)

I assume that there is some dependency missing here, but I have no idea how I could find out what it is and thus how to resolve the error. What could I do?

Full error message:

Building wheels for collected packages: vemomoto-core-npcollections                                                                                [76/1898]
  Building wheel for vemomoto-core-npcollections (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: /home/user/anaconda3/envs/test37/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-req-build-0_ns61r9/setup.py'"'"'; __file__='"'"'/tmp/pip-req-build-0_ns61r9/se
tup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-4zeu
yeay
       cwd: /tmp/pip-req-build-0_ns61r9/
  Complete output (49 lines):
  /home/user/anaconda3/envs/test37/lib/python3.7/site-packages/setuptools/dist.py:476: UserWarning: Normalizing '0.9.0.a1' to '0.9.0a1'
    normalized_version,
  running bdist_wheel
  running build
  running build_py
  package init file 'vemomoto_core/__init__.py' not found (or not a regular file)
  creating build
  creating build/lib.linux-x86_64-3.7
  creating build/lib.linux-x86_64-3.7/vemomoto_core
  creating build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/_setup_npextc.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/sparse3d.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/_setup_FixedOrderedIntDict.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/_FixedOrderedIntDict_reduce.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/__init__.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections                                                                                copying vemomoto_core/npcollections/_setup_intquickheapdict.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections                                                                                copying vemomoto_core/npcollections/npext.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/_npextc_utils.py -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/__init__.pxd -> build/lib.linux-x86_64-3.7/vemomoto_core
  copying vemomoto_core/npcollections/FixedOrderedIntDict.pxd -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/npextc.pxd -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/intquickheapdict.pxd -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/intquickheapdict.pyx -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections                                                                                copying vemomoto_core/npcollections/npextc.pyx -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/FixedOrderedIntDict.pyx -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/heapoperations_c.c -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/sectionsum.c -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections                                                                                copying vemomoto_core/npcollections/intquickheapdict.cpp -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections                                                                                copying vemomoto_core/npcollections/FixedOrderedIntDict.cpp -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  copying vemomoto_core/npcollections/npextc.cpp -> build/lib.linux-x86_64-3.7/vemomoto_core/npcollections
  running build_ext
  building 'vemomoto_core.npcollections.npextc' extension
  creating build/temp.linux-x86_64-3.7
  creating build/temp.linux-x86_64-3.7/vemomoto_core
  creating build/temp.linux-x86_64-3.7/vemomoto_core/npcollections                                                                                gcc -pthread -B /home/user/anaconda3/envs/test37/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/user/anaconda3/envs/test37/include/python3.7m -I/home/user/anaconda3/envs/test37/lib/python3.7/site-packages/numpy/core/include -c vemomoto_core/npcollections/npextc.cpp -o build/temp.linux-x86_64-3.7/vemomoto_core/npcollections/npextc.o -std=c++11 -O3 -fopenmp
  cc1plus: warning: command line option '-Wstrict-prototypes' is valid for C/ObjC but not for C++
  In file included from /home/user/anaconda3/envs/test37/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1832:0,
                   from /home/user/anaconda3/envs/test37/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,
                   from /home/user/anaconda3/envs/test37/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,
                   from vemomoto_core/npcollections/npextc.cpp:636:
  /home/user/anaconda3/envs/test37/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning "Using deprecated NumPy API, disable it with " "#define NPY_NO_DEP
RECATED_API NPY_1_7_API_VERSION" [-Wcpp]
   #warning "Using deprecated NumPy API, disable it with " \
    ^~~~~~~
  g++ -pthread -shared -B /home/user/anaconda3/envs/test37/compiler_compat -L/home/user/anaconda3/envs/test37/lib -Wl,-rpath=/home/user/anaconda3/envs/test37/lib -Wl,--no-as-needed -Wl,--sysroot=
/ -Wl,-O2 -Wl,--sort-common -Wl,--as-needed -Wl,-z,relro -Wl,-z,now -Wl,--disable-new-dtags -Wl,--gc-sections build/temp.linux-x86_64-3.7/vemomoto_core/npcollections/npextc.o -o build/lib.linux-x86_64-3.7/ve
momoto_core/npcollections/npextc.cpython-37m-x86_64-linux-gnu.so -fopenmp
  /home/user/anaconda3/envs/test37/compiler_compat/ld: cannot find /lib/libpthread.so.0
  /home/user/anaconda3/envs/test37/compiler_compat/ld: cannot find /usr/lib/libpthread_nonshared.a
  collect2: error: ld returned 1 exit status
  error: command 'g++' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for vemomoto-core-npcollections
  Running setup.py clean for vemomoto-core-npcollections
Failed to build vemomoto-core-npcollections

Body:
To solve the issue, I have compared the fresh anaconda environment with the one I used. To this end, I used

conda list

in both the older and the fresh installation and compared the output. Then I looked for packages that were included in the old environment but not in the new environment and that had a name suggesting that they may include the right files.

After installing the candidates and retrying the build, I found that gxx_linux-64 (and for another package cmake) were necessary requirements to build. As these packages seem not to be available on PyPI, I will require end users to use the anaconda commands

conda install gxx_linux-64
conda install cmake

Before installing my package. It would be nice to include this dependency in the setup script, but this is another question...


问:
What will be the correct type of "any"?
I am using the following in my code base :

https://github.com/google-map-react/google-map-react

But they have not explained the types used for map and maps which is giving me typescript error. Changing it to object does not help much.

const handleApiLoaded = (map: any, maps: any) => {

What is the correct types of map and maps. Thank you.

答:
This worked for me. Thanks</p>

```<code>      map: google.maps.Map;
      maps: {
        LatLngBounds: new () => google.maps.LatLngBounds;
      };```
</code>```

Title: What will be the correct type of "any"?

Body:
This worked for me. Thanks

      map: google.maps.Map;
      maps: {
        LatLngBounds: new () => google.maps.LatLngBounds;
      };```


问:
How do you fight design complexity?
I often find myself fighting overengineering -- the person in charge of designing the software comes up with an architecture that's, way, way overcomplicated.

It's all fine and dandy to have all the esoteric features that users will never know about and get that sense of achievement when you're doing something that all the magazine articles are telling you is the latest, cool thing, but we are going to spend half of our  engineering time on this monument to our cleverness, and not, you know, the actual product that our users need and upper management expects to be completed within a reasonable or at least a bounded time frame.

And you'll probably just have to revert back to the simpler solution anyway when you start running out of time, that is, if you get that chance.

We've all heard the refrain: Keep It Simple, Stupid™.

How do you fight with overcomplexity in your team?

One example I've had to work with repeatedly lately is when the decision has been made to go to a fully denormalized database design rather than an RDBMS. "because it's faster!" Fully denormalized databases are really hard to get right, and are only appropriate for really specialized data problems like Flickr or ebay, and which can be extremely expensive in terms of developer time relative to the rest of your development.

答:
It's all fine and dandy to have all
  the esoteric features that users will
  never know about and...

This would be feature creep, not unnecessarily complicated design. It's different from your example on databases.

One example I've had to work with
  repeatedly lately is when the decision
  has been made to go to a fully
  denormalized database design rather
  than an RDBMS. "because it's faster!"

In this case several things may be going on. One of them is, you might be wrong and these people could really know what they are saying because they have worked with very similar examples. Another is they might be wrong, i.e. their design doesn't offer the speed advantages they claim. In this case there could be two different situations: (1) They are giving speed too much weight in their design, or (2) speed is really critical. If speed is indeed so relevant, the team shouldn't rely only in assumptions - they should try different prototypes and evaluate their speed in the critical paths. You don't build an F1 car in one way just "because it's faster", instead you keep trying several alternative design solutions and pick the fastest one which still doesn't increase maintenance costs too much.

Sometimes you can argue it and reach an agreement, sometimes you can't. It's life.

A final word, though. You don't fight complexity. You treat it. You identify the really important things and act accordingly.

OwnerDisplayName: ʞɔıu

ContentLicense: CC BY-SA 2.5

Title: How do you fight design complexity?

LastEditorDisplayName: philippe

OwnerDisplayName: Daniel Daranas

LastEditorDisplayName: Daniel Daranas


问:
c++ self in initialisation list
i have this code snippet

```<code>class Osoba{
         Osoba(char* imie,int wiek){
                     this->imie=new char[strlen(imie)+1];
                     strcpy(this->imie,imie);
                     this->wiek=wiek;
                     cout<<"Utworzono Osobe "<<this->imie<<endl;
         }
         Osoba(Osoba& x){
                 Osoba(x.imie,x.wiek);
         }
[...]
</code>```

and when i call the copy constructor it doesnt work (creates and destroyes object).

Edit:
if i use

```<code>         Osoba(Osoba& x): Osoba(x.imie,x.wiek){
</code>```

i get type 'class Osoba' is not a direct base of 'Osoba'

how is this done ?

答:
You cannot call a constructor except for creating another different object.

If you need to have some code in common between constructors you can place it in a separate method and call that method. Note that in the constructor you can call methods of the object but virtual methods are not going to dispatch do derived classes.

In other words if you have

```<code>struct Foo
{
    virtual void doit() { ... }
    Foo() {
        doit();
    }
};

struct Bar : Foo
{
    virtual void doit() { ... }
};
</code>```

during the constructor of Bar the implementation of doit called will be the one defined in Foo because during the constructor of the base part of the derived object, the object is only a "base" object. Only at the end of the constructor it becomes a "derived" object right before executing any eventually present code in the "derived" constructor.

Be careful that other object oriented languages use a different approach...

For an explanation of what happens exactly in C++ see this article.

If you like instead a legalese description this is what is stated in the C++ standard at 12.7.4:

Member functions, including virtual
  functions (10.3), can be called during
  construction or destruction (12.6.2).
  When a virtual function is called
  directly or indirectly from a
  constructor (including from the
  mem-initializer for a data member) or
  from a destructor, and the object to
  which the call applies is the object
  under construction or destruction, the
  function called is the one defined in
  the constructor or destructor’s own
  class or in one of its bases, but not
  a function overriding it in a class
  derived from the constructor or
  destructor’s class, or overriding it
  in one of the other base classes of
  the most derived object (1.8). If the
  virtual function call uses an explicit
  class member access (5.2.5) and the
  object-expression refers to the object
  under construction or destruction but
  its type is neither the constructor or
  destructor’s own class or one of its
  bases, the result of the call is
  undefined.

Title: c++ self in initialisation list

Body:
i have this code snippet

class Osoba{
         Osoba(char* imie,int wiek){
                     this->imie=new char[strlen(imie)+1];
                     strcpy(this->imie,imie);
                     this->wiek=wiek;
                     cout<<"Utworzono Osobe "<<this->imie<<endl;
         }
         Osoba(Osoba& x){
                 Osoba(x.imie,x.wiek);
         }
[...]

and when i call the copy constructor it doesnt work (creates and destroyes object).

Edit:
if i use

         Osoba(Osoba& x): Osoba(x.imie,x.wiek){

i get type 'class Osoba' is not a direct base of 'Osoba'

how is this done ?

Body:
You cannot call a constructor except for creating another different object.

If you need to have some code in common between constructors you can place it in a separate method and call that method. Note that in the constructor you can call methods of the object but virtual methods are not going to dispatch do derived classes.

In other words if you have

struct Foo
{
    virtual void doit() { ... }
    Foo() {
        doit();
    }
};

struct Bar : Foo
{
    virtual void doit() { ... }
};

during the constructor of Bar the implementation of doit called will be the one defined in Foo because during the constructor of the base part of the derived object, the object is only a "base" object. Only at the end of the constructor it becomes a "derived" object right before executing any eventually present code in the "derived" constructor.

Be careful that other object oriented languages use a different approach...

For an explanation of what happens exactly in C++ see this article.

If you like instead a legalese description this is what is stated in the C++ standard at 12.7.4:

Member functions, including virtual
  functions (10.3), can be called during
  construction or destruction (12.6.2).
  When a virtual function is called
  directly or indirectly from a
  constructor (including from the
  mem-initializer for a data member) or
  from a destructor, and the object to
  which the call applies is the object
  under construction or destruction, the
  function called is the one defined in
  the constructor or destructor’s own
  class or in one of its bases, but not
  a function overriding it in a class
  derived from the constructor or
  destructor’s class, or overriding it
  in one of the other base classes of
  the most derived object (1.8). If the
  virtual function call uses an explicit
  class member access (5.2.5) and the
  object-expression refers to the object
  under construction or destruction but
  its type is neither the constructor or
  destructor’s own class or one of its
  bases, the result of the call is
  undefined.


问:
Sort object by property in JObject
I have a list defined as:

```<code>    List<SensorData> tempSensorData = new List<SensorData>();
</code>```

This is how I am populating this list:

```<code>    tempSensorData.Add(new SensorData
    {
         Data = JObject.Parse(values[r, 4].ToString()),
         SensorGuid = values[r, 2].ToString()
    });
</code>```

This is my definition of SensorData class:

```<code>public class SensorData
    {
        public JObject Data { get; set; }

        public string SensorGuid { get; set; }
    }
</code>```

There is a property in Data Property called timestamp.  I want my list to be sorted by that value.  How can I do that?
I have tried doing:

```<code>     tempSensorData.OrderBy(o => o.Data.SelectToken("timestamp"));
</code>```

But it doesn't help

This is the JSON value in Data:

```<code>{{
  "Record": "A",
  "timestamp": 1572987031,
  "signal_strength": "021",
  "vbatt": "3.10",
  "temperature": "21.5"
}}
</code>```

答:
You can try something like that

var result = tempSensorData.OrderBy(o => o.Data["timestamp"].Value<long>());
```

Get a long value of timestamp property using Value<T> method of JToken, then use this value in a Func<TSource,TKey> key selector in OrderBy.

Unlike Sort method of List<T> class, OrderBy method returns an IOrderedEnumerable as a result instead of changing a source list, so you should assign return value to the variable

Title: Sort object by property in JObject

Body:
I have a list defined as:

    List<SensorData> tempSensorData = new List<SensorData>();

This is how I am populating this list:

    tempSensorData.Add(new SensorData
    {
         Data = JObject.Parse(values[r, 4].ToString()),
         SensorGuid = values[r, 2].ToString()
    });

This is my definition of SensorData class:

public class SensorData
    {
        public JObject Data { get; set; }

        public string SensorGuid { get; set; }
    }

There is a property in Data Property called timestamp.  I want my list to be sorted by that value.  How can I do that?
I have tried doing:

     tempSensorData.OrderBy(o => o.Data.SelectToken("timestamp"));

But it doesn't help

This is the JSON value in Data:

{{
  "Record": "A",
  "timestamp": 1572987031,
  "signal_strength": "021",
  "vbatt": "3.10",
  "temperature": "21.5"
}}

Body:
You can try something like that

var result = tempSensorData.OrderBy(o => o.Data["timestamp"].Value<long>());

Get a long value of timestamp property using Value<T> method of JToken, then use this value in a Func<TSource,TKey> key selector in OrderBy.

Unlike Sort method of List<T> class, OrderBy method returns an IOrderedEnumerable as a result instead of changing a source list, so you should assign return value to the variable


问:
A problem with trying to import "from flask_ask import..."?
On repl.it, I'm trying to import certain things from a specific library however, it brings back an error "No module named 'flask_ask' ". I've posted this before and the solution worked a little bit but caused more errors. Any help would be much appreciated.

```<code>from array import *
from flask import Flask
from flask_ask import Ask, statement, question, session
import json
</code>```

If you would like the rest of the code, I will post it in the comment section.

答:
It looks like you can actually manually add it to your repl. On the left side of the screen, click on packages and look for 'Flask-Ask'.

Note: No text for the image since I'm pointing to something inside repl. It's explained in the documentation here

Body:
On repl.it, I'm trying to import certain things from a specific library however, it brings back an error "No module named 'flask_ask' ". I've posted this before and the solution worked a little bit but caused more errors. Any help would be much appreciated.

from array import *
from flask import Flask
from flask_ask import Ask, statement, question, session
import json

If you would like the rest of the code, I will post it in the comment section.


问:
Fail to import watermark from jupyter notebook with anaconda
I see I have watermark installed:

```<code>(testenv) ➜  ~ conda install watermark
Fetching package metadata ...........
Solving package specifications: .

# All requested packages already installed.
# packages in environment at /Users/myuser/anaconda3/envs/testenv:
#
watermark                 1.5.0                    py36_0    conda-forge
(testenv) ➜  ~
</code>```

I then run jupyter notebook it starts up:

```<code>(testenv) ➜  ~ jupyter notebook
[I 11:30:56.897 NotebookApp] JupyterLab alpha preview extension loaded from /Users/myuser/anaconda3/lib/python3.6/site-packages/jupyterlab
JupyterLab v0.27.0
Known labextensions:
[I 11:30:56.899 NotebookApp] Running the core application with no additional extensions or settings
[I 11:30:56.905 NotebookApp] Serving notebooks from local directory: /Users/myuser
[I 11:30:56.905 NotebookApp] 0 active kernels
[I 11:30:56.905 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/?token=a17e10f9a22d9bbee4bc55d24741c56408278254edb57a22
[I 11:30:56.905 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 11:30:56.909 NotebookApp]

    Copy/paste this URL into your browser when you connect for the first time,
    to login with a token:
        http://localhost:8888/?token=a17e10f9a22d9bbee4bc55d24741c56408278254edb57a22
[I 11:30:57.152 NotebookApp] Accepting one-time-token-authenticated connection from ::1
</code>```

But when I run in jupyter I can't import watermark, anything i'm doing wrong?

```<code>from __future__ import print_function
from distutils.version import LooseVersion as Version
import sys

importlib.import_module('watermark')

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-6-b1c6f1862f9d> in <module>()
      3 import sys
      4
----> 5 importlib.import_module('watermark')

~/.pyenv/versions/3.6.4rc1/lib/python3.6/importlib/__init__.py in import_module(name, package)
    124                 break
    125             level += 1
--> 126     return _bootstrap._gcd_import(name[level:], package, level)
    127
    128

~/.pyenv/versions/3.6.4rc1/lib/python3.6/importlib/_bootstrap.py in _gcd_import(name, package, level)

~/.pyenv/versions/3.6.4rc1/lib/python3.6/importlib/_bootstrap.py in _find_and_load(name, import_)

~/.pyenv/versions/3.6.4rc1/lib/python3.6/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)

ModuleNotFoundError: No module named 'watermark'
</code>```

答:
The watermark line magic can be installed by executing

pip install watermark

Alternatively, you can install the latest development version directly from GitHub via

pip install -e git+https://github.com/rasbt/watermark#egg=watermark

Body:
I see I have watermark installed:

(testenv) ➜  ~ conda install watermark
Fetching package metadata ...........
Solving package specifications: .

# All requested packages already installed.
# packages in environment at /Users/myuser/anaconda3/envs/testenv:
#
watermark                 1.5.0                    py36_0    conda-forge
(testenv) ➜  ~

I then run jupyter notebook it starts up:

(testenv) ➜  ~ jupyter notebook
[I 11:30:56.897 NotebookApp] JupyterLab alpha preview extension loaded from /Users/myuser/anaconda3/lib/python3.6/site-packages/jupyterlab
JupyterLab v0.27.0
Known labextensions:
[I 11:30:56.899 NotebookApp] Running the core application with no additional extensions or settings
[I 11:30:56.905 NotebookApp] Serving notebooks from local directory: /Users/myuser
[I 11:30:56.905 NotebookApp] 0 active kernels
[I 11:30:56.905 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/?token=a17e10f9a22d9bbee4bc55d24741c56408278254edb57a22
[I 11:30:56.905 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 11:30:56.909 NotebookApp]

    Copy/paste this URL into your browser when you connect for the first time,
    to login with a token:
        http://localhost:8888/?token=a17e10f9a22d9bbee4bc55d24741c56408278254edb57a22
[I 11:30:57.152 NotebookApp] Accepting one-time-token-authenticated connection from ::1

But when I run in jupyter I can't import watermark, anything i'm doing wrong?

from __future__ import print_function
from distutils.version import LooseVersion as Version
import sys

importlib.import_module('watermark')

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-6-b1c6f1862f9d> in <module>()
      3 import sys
      4
----> 5 importlib.import_module('watermark')

~/.pyenv/versions/3.6.4rc1/lib/python3.6/importlib/__init__.py in import_module(name, package)
    124                 break
    125             level += 1
--> 126     return _bootstrap._gcd_import(name[level:], package, level)
    127
    128

~/.pyenv/versions/3.6.4rc1/lib/python3.6/importlib/_bootstrap.py in _gcd_import(name, package, level)

~/.pyenv/versions/3.6.4rc1/lib/python3.6/importlib/_bootstrap.py in _find_and_load(name, import_)

~/.pyenv/versions/3.6.4rc1/lib/python3.6/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)

ModuleNotFoundError: No module named 'watermark'


问:
Conditional Postgres Query
The PG table looks like this:

```<code>id - name   - type
1  - Name 1 - Type A
2  - Name 1 - Type B
3  - Name 2 - Type A
4  - Name 2 - Type B
5  - Name 3 - Type A
</code>```

I would like to write a query that only lists rows in which Name has a 'Type A' record but not a Type B record.

This is the result I am hoping for:

```<code>5  - Name 3 - Type A
</code>```

答:
One method is group by:

```<code>select name
from t
group by t
having min(type) = max(type) and min(type) = 'Type A';
</code>```

Title: Conditional Postgres Query

Body:
The PG table looks like this:

id - name   - type
1  - Name 1 - Type A
2  - Name 1 - Type B
3  - Name 2 - Type A
4  - Name 2 - Type B
5  - Name 3 - Type A

I would like to write a query that only lists rows in which Name has a 'Type A' record but not a Type B record.

This is the result I am hoping for:

5  - Name 3 - Type A

Body:
One method is group by:

select name
from t
group by t
having min(type) = max(type) and min(type) = 'Type A';


问:
How do I get some data from a website which requires authentication with Ansbile?
I have been trying to login a web page and get/download some specific data from there, but couldn't make it. Is it possible? </p>

答:
If you need arbitrary auth, why not just write it in normal python/bash and trigger the script with Ansible so that you aren't constrained by Ansible's auth support?

https://docs.ansible.com/ansible/latest/modules/script_module.html


问:
how to differentiate layouts files (.xml files ) in different-different layout folders in Android
how to differentiate layouts files  (.xml files ) in different-different layout folders in Android</p>

答:
You mean differenciate by portrait/landscape?

```<code>layout-land/
layout-port/
</code>```

You can read more about this here: http://developer.android.com/guide/topics/resources/localization.html

There are more possibilities like:

```<code>res/layout/my_layout.xml             // layout for normal screen size ("default")
res/layout-small/my_layout.xml       // layout for small screen size
res/layout-large/my_layout.xml       // layout for large screen size
res/layout-xlarge/my_layout.xml      // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation

res/drawable-mdpi/my_icon.png        // bitmap for medium density
res/drawable-hdpi/my_icon.png        // bitmap for high density
res/drawable-xhdpi/my_icon.png       // bitmap for extra high density
</code>```

You can read more here: http://developer.android.com/guide/practices/screens_support.html

Body:
You mean differenciate by portrait/landscape?

layout-land/
layout-port/

You can read more about this here: http://developer.android.com/guide/topics/resources/localization.html

There are more possibilities like:

res/layout/my_layout.xml             // layout for normal screen size ("default")
res/layout-small/my_layout.xml       // layout for small screen size
res/layout-large/my_layout.xml       // layout for large screen size
res/layout-xlarge/my_layout.xml      // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation

res/drawable-mdpi/my_icon.png        // bitmap for medium density
res/drawable-hdpi/my_icon.png        // bitmap for high density
res/drawable-xhdpi/my_icon.png       // bitmap for extra high density

You can read more here: http://developer.android.com/guide/practices/screens_support.html


问:
Adding MenuItem to Group programmatically doesn't add radio button
I'm adding MenuItems programmatically and I want to include a radio button when doing so.

Any advice?

Menu.xml

```<code><item
        android:id="@+id/filter_lines"
        android:title="Lines">

        <menu
            android:id="@+id/lines_sub_menu"
            android:checkableBehavior="single">

            <group
                android:orderInCategory="101"
                android:id="@+id/lines_group"
                android:checkableBehavior="single">

                <item
                    android:id="@+id/youi"
                    android:title="Hello World"/>

            </group>

        </menu>
    </item>
</code>```

Adding the MenuItem like this

```<code> val item = linesSubMenu.add(R.id.lines_group, 100, Menu.NONE, lineName)
</code>```

EDIT: Tried setCheckable(true) doesn't have singleselectionbehavior

答:
So the answer is to use this method:

linesSubMenu.setGroupCheckable(R.id.lines_group, true, true)

Found here: https://developer.android.com/reference/android/view/Menu#setGroupCheckable(int,%20boolean,%20boolean)

Body:
I'm adding MenuItems programmatically and I want to include a radio button when doing so.

Any advice?

Menu.xml

<item
        android:id="@+id/filter_lines"
        android:title="Lines">

        <menu
            android:id="@+id/lines_sub_menu"
            android:checkableBehavior="single">

            <group
                android:orderInCategory="101"
                android:id="@+id/lines_group"
                android:checkableBehavior="single">

                <item
                    android:id="@+id/youi"
                    android:title="Hello World"/>

            </group>

        </menu>
    </item>

Adding the MenuItem like this

 val item = linesSubMenu.add(R.id.lines_group, 100, Menu.NONE, lineName)

EDIT: Tried setCheckable(true) doesn't have singleselectionbehavior


问:
CSV File to SQL Insert Statement
I have a CSV file that looks something like this:

```<code>Date,Person,Time Out,Time Back,Restaurant,Calories,Delicious?
6/20/2016,August,11:58,12:45,Black Bear,850,Y
6/20/2016,Marcellus,12:00,12:30,Brought Lunch,,Y
6/20/2016,Jessica,11:30,12:30,Wendy's,815,N
6/21/2016,August,12:05,1:01,Brought Lunch,,Y
</code>```

So far I have managed to print each row into a list of strings (ex. - ['Date', 'Person', 'Time Out', etc.] or ['6/20/2016', 'August', '11:58' etc.]).

Now I need to do 2 more things:

Add an ID header and sequential numeric string to each row (for ex. - ['ID', 'Date',
'Person', etc.] and ['1', '6/20/2016', 'August', etc.])

Separate each row so that they can be formatted into insert
statements rather than just having the program print out every single row one after another (for ex. - INSERT INTO Table ['ID', 'Date', 'Person', etc.] VALUES ['1', '6/20/2016', 'August', etc.])

Here is the code that has gotten me as far as I am now:

```<code>import csv

openFile = open('test.csv', 'r')
csvFile = csv.reader(openFile)
for row in csvFile:
    print (row)
openFile.close()
</code>```

答:
You can use this functions if you want to mantain type conversion, i have used it to put data into google big query with a string sql statement.

PS: You can put other types on the function

```<code>import csv

def convert(value):
    for type in [int, float]:
        try:
            return type(value)
        except ValueError:
            continue
    # All other types failed it is a string
    return value

def construct_string_sql(file_path, table_name, schema_name):
    string_SQL = ''
    try:
        with open(file_path, 'r') as file:
            reader = csv.reader(file)
            headers = ','.join(next(reader))
            for row in reader:
                row = [convert(x) for x in row].__str__()[1:-1]
                string_SQL += f'INSERT INTO {schema_name}.{table_name}({headers}) VALUES ({row});'
    except:
        return ''

    return string_SQL
</code>```

Title: CSV File to SQL Insert Statement

Body:
I have a CSV file that looks something like this:

Date,Person,Time Out,Time Back,Restaurant,Calories,Delicious?
6/20/2016,August,11:58,12:45,Black Bear,850,Y
6/20/2016,Marcellus,12:00,12:30,Brought Lunch,,Y
6/20/2016,Jessica,11:30,12:30,Wendy's,815,N
6/21/2016,August,12:05,1:01,Brought Lunch,,Y

So far I have managed to print each row into a list of strings (ex. - ['Date', 'Person', 'Time Out', etc.] or ['6/20/2016', 'August', '11:58' etc.]).

Now I need to do 2 more things:

Add an ID header and sequential numeric string to each row (for ex. - ['ID', 'Date',
'Person', etc.] and ['1', '6/20/2016', 'August', etc.])

Separate each row so that they can be formatted into insert
statements rather than just having the program print out every single row one after another (for ex. - INSERT INTO Table ['ID', 'Date', 'Person', etc.] VALUES ['1', '6/20/2016', 'August', etc.])

Here is the code that has gotten me as far as I am now:

import csv

openFile = open('test.csv', 'r')
csvFile = csv.reader(openFile)
for row in csvFile:
    print (row)
openFile.close()

Body:
You can use this functions if you want to mantain type conversion, i have used it to put data into google big query with a string sql statement.

PS: You can put other types on the function

import csv

def convert(value):
    for type in [int, float]:
        try:
            return type(value)
        except ValueError:
            continue
    # All other types failed it is a string
    return value

def construct_string_sql(file_path, table_name, schema_name):
    string_SQL = ''
    try:
        with open(file_path, 'r') as file:
            reader = csv.reader(file)
            headers = ','.join(next(reader))
            for row in reader:
                row = [convert(x) for x in row].__str__()[1:-1]
                string_SQL += f'INSERT INTO {schema_name}.{table_name}({headers}) VALUES ({row});'
    except:
        return ''

    return string_SQL


问:
Changing order of the elements in javascript object according to given key
I'm attempting to change the order of the Object in javascript by given key. Here is my code for the same but it says "shift is not a function". Is it not applicable on objects? Please give a solution.</p>

```<code>    periods = {
      "Su": 6,
      "Mo": 10,
      "Ma": 7,
      "Ra": 18,
      "Ju": 16,
      "Sa": 19,
      "Me": 17,
      "Ke": 7,
      "Ve": 20,
    };
    rotateOrder(key:any, entities:any) {
            let result = entities;
            for(var k in entities) {
              if(entities.hasOwnProperty(k) && k != key){
                result.push(result.shift());
              }
              else {
                return result;
              }
            }
          }
console.log(this.rotateOrder("Ve", this.periods));
</code>```

答:
We can re-arrange / change the array by using object.entries and sort function  :

Code:

 let periods = {
      "Su": 6,
      "Mo": 10,
      "Ma": 7,
      "Ra": 18,
      "Ju": 16,
      "Sa": 19,
      "Me": 17,
      "Ke": 7,
      "Ve": 20,
    };

    let keysSorted = Object.entries(periods).sort(function (a, b) {
      return a[1] - b[1]
    })
    console.log(keysSorted);```

Body:
I'm attempting to change the order of the Object in javascript by given key. Here is my code for the same but it says "shift is not a function". Is it not applicable on objects? Please give a solution.

    periods = {
      "Su": 6,
      "Mo": 10,
      "Ma": 7,
      "Ra": 18,
      "Ju": 16,
      "Sa": 19,
      "Me": 17,
      "Ke": 7,
      "Ve": 20,
    };
    rotateOrder(key:any, entities:any) {
            let result = entities;
            for(var k in entities) {
              if(entities.hasOwnProperty(k) && k != key){
                result.push(result.shift());
              }
              else {
                return result;
              }
            }
          }
console.log(this.rotateOrder("Ve", this.periods));


问:
Create lines of string where the number of lines is equal to the number of elements in a list
I am trying to create a function where it takes the length of a list and can produce lines of string where the number of lines is equal to the number of elements in said list.

For example, if for list x, len(x) = 2, and I want to produce:

Hello
Hello
```

<p>Or if <code>len(x) = 3</code></p>

<pre class="lang-py prettyprint-override"><code>Hello
Hello
Hello
</code>```

How could I code this for any length, which is bigger than 0?

Thanks in advance!

答:
Use a for loop that iterates over each item in the list, and in the loop body, print your desired message.

```<code>for x in mylist:
    print("Hello")
</code>```

Body:
I am trying to create a function where it takes the length of a list and can produce lines of string where the number of lines is equal to the number of elements in said list.

For example, if for list x, len(x) = 2, and I want to produce:

Hello
Hello

Or if len(x) = 3

Hello
Hello
Hello

How could I code this for any length, which is bigger than 0?

Thanks in advance!

Body:
Use a for loop that iterates over each item in the list, and in the loop body, print your desired message.

for x in mylist:
    print("Hello")


问:
what does launchd status 78 mean?? why my user agent not running??
I want to run a unison sync service running in the background whenever I login. But the status code of my agent is 78. I don't know why, I tried some fix posted online, but it just doesn't work.

What's the problem?? below is the plist file for my service.

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>syncmyproject</string>
    <key>StandardOutPath</key>
    <string>/var/log/syncmyproject.log</string>
    <key>StandardErrorPath</key>
    <string>/var/log/syncmyproject.log</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>Debug</key>
    <true/>
    <key>EnableGlobbing</key>
    <true/>
    <key>ProgramArguments</key>
    <array>
      <string>/usr/local/bin/unison</string>
      <string>-auto</string>
      <string>-batch</string>
      <string>-repeat watch</string>
      <string>~/home/project</string>
      <string>~/project</string>
    </array>
</dict>
</plist>
</code>```

答:
To view a description of all error codes, type

launchctl error <insert numerical error code here>

e.g.:

% launchctl error 77
77: No locks available

Body:
I want to run a unison sync service running in the background whenever I login. But the status code of my agent is 78. I don't know why, I tried some fix posted online, but it just doesn't work.

What's the problem?? below is the plist file for my service.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>syncmyproject</string>
    <key>StandardOutPath</key>
    <string>/var/log/syncmyproject.log</string>
    <key>StandardErrorPath</key>
    <string>/var/log/syncmyproject.log</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>Debug</key>
    <true/>
    <key>EnableGlobbing</key>
    <true/>
    <key>ProgramArguments</key>
    <array>
      <string>/usr/local/bin/unison</string>
      <string>-auto</string>
      <string>-batch</string>
      <string>-repeat watch</string>
      <string>~/home/project</string>
      <string>~/project</string>
    </array>
</dict>
</plist>


问:
How to get title of current tab
How would one get the name of the active tab / JPanel within a JTabbedPane in order to compare it to a string? It is a simple question but I cannot find a solution to this.</p>

答:
With getSelextedIndex you get the index of the active tab and with getTitleAt you get the title of that index:

```<code>JTabbedPane tabbedPane ...
int selectedIndex = tabbedPane.getSelectedIndex();
tabbedPane.getTitleAt(selectedIndex);
</code>```

Title: How to get title of current tab

Body:
With getSelextedIndex you get the index of the active tab and with getTitleAt you get the title of that index:

JTabbedPane tabbedPane ...
int selectedIndex = tabbedPane.getSelectedIndex();
tabbedPane.getTitleAt(selectedIndex);