问:
Bind more popups to the same marker or merge popups content
I have a JSON in which there are places with their coordinates and their textual content to be inserted in the relative marker's popup.

If in the JSON there is 2 times the same place (with the same coordinates), I have to bind 2 popups with their respective contents on the same marker (or at most I have to update the popup with the new content while keeping the old one).

```<code><html>
<head>
    <!-- Libraries leaflet/jquery for may project-->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
   <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" />
   <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script>
</head>

<body>
     <div id="map" style="width:100%; height: 100%"></div>

     <script>
     // my json data
     var data = [
        {
          "name" : "Location A",
          "lat" :"27",
          "long" : "29",
          "popupContent" : "content 1"
        },
        {
          "name" : "Location B",
          "lat" :"51",
          "long" : "12",
          "popupContent" : "content 2"
        },
        {
          "name" : "Location A",
          "lat" :"27",
          "long" : "29",
          "popupContent" : "content 3"
        }
     ]

     //init leaflet  map
     var map = new L.Map('map');

     L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© <a href="http://openstreetmap.org">OpenStreetMap</a> contributors',
        maxZoom: 18
     }).addTo(map);
     var italy = new L.LatLng(42.504154,12.646361);
     map.setView(italy, 6);

     //iterate my json data and create markers with popups
     for(let key in data){
       L.marker([data[key].lat,data[key].long]).bindPopup(data[key].popupContent).addTo(map)
     }
     </script>

</body>
</html>
</code>```

With this code, the third place overrides the first, and I have a single marker and a single popup with written "content 3".

I would like 2 popups (one with written "content 1" and one with "content 3") or one single popup with all two contents.

答:
The easiest way to address similar use case is simply to use a clustering plugin, typically Leaflet.markercluster, so that it separates your Markers which are on the same position or very close (actually your 3rd place does not "override" the first, in the sense of replacing, it just sits on top of it, in the sense of overlapping).

The added advantage is that it naturally separates Markers which are very close one to each other, but still at slightly different positions, which below heuristics will not catch.

var mcg = L.markerClusterGroup();

     //iterate my json data and create markers with popups
     for(let key in data){
       L.marker(latLng).addTo(mcg) // Add into the MCG instead of directly to the map.
     }

mcg.addTo(map);
```
<p>Demo: https://plnkr.co/edit/B0XF5SSpQ27paWt1</p>
<p>Now in your case, you may not be wary of closeby Markers, but really have data that apply to same places (in your <code>data</code>, name and coordinates of items 1 and 3 are identical).</p>
<p>In that case, a solution could simply be to rework your data first (possibly in runtime) to <em>merge</em> the popup content of all items that have the same name and/or coordinates (depending on how exactly you can identify identical items).</p>
<p>For example using Lodash <code>groupBy</code>:</p>
<pre class="lang-js prettyprint-override"><code>var groupedData = _.groupBy(data, "name"); // Depends on how you identify identical items

     //iterate my json data and create markers with popups
     for(let key in groupedData){
       var items = groupedData[key];

       // Coordinates of first item, all items of this group are supposed to be on same place
       var latLng = [items[0].lat, items[0].long];

       // Merge all popup contents
       var popupContent = items.map(item => item.popupContent).join("<br/>")
       L.marker(latLng).bindPopup(popupContent).addTo(map)
     }
</code>```

Demo: https://plnkr.co/edit/D7TzdaBVRvJr2sid

Body:
I have a JSON in which there are places with their coordinates and their textual content to be inserted in the relative marker's popup.

If in the JSON there is 2 times the same place (with the same coordinates), I have to bind 2 popups with their respective contents on the same marker (or at most I have to update the popup with the new content while keeping the old one).

   <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" />

With this code, the third place overrides the first, and I have a single marker and a single popup with written "content 3".

I would like 2 popups (one with written "content 1" and one with "content 3") or one single popup with all two contents.

Body:
The easiest way to address similar use case is simply to use a clustering plugin, typically Leaflet.markercluster, so that it separates your Markers which are on the same position or very close (actually your 3rd place does not "override" the first, in the sense of replacing, it just sits on top of it, in the sense of overlapping).

The added advantage is that it naturally separates Markers which are very close one to each other, but still at slightly different positions, which below heuristics will not catch.

var mcg = L.markerClusterGroup();

     //iterate my json data and create markers with popups
     for(let key in data){
       L.marker(latLng).addTo(mcg) // Add into the MCG instead of directly to the map.
     }

mcg.addTo(map);

Demo: https://plnkr.co/edit/B0XF5SSpQ27paWt1

Now in your case, you may not be wary of closeby Markers, but really have data that apply to same places (in your data, name and coordinates of items 1 and 3 are identical).

In that case, a solution could simply be to rework your data first (possibly in runtime) to merge the popup content of all items that have the same name and/or coordinates (depending on how exactly you can identify identical items).

For example using Lodash groupBy:

var groupedData = _.groupBy(data, "name"); // Depends on how you identify identical items

     //iterate my json data and create markers with popups
     for(let key in groupedData){
       var items = groupedData[key];

       // Coordinates of first item, all items of this group are supposed to be on same place
       var latLng = [items[0].lat, items[0].long];

       // Merge all popup contents
       var popupContent = items.map(item => item.popupContent).join("<br/>")
       L.marker(latLng).bindPopup(popupContent).addTo(map)
     }

Demo: https://plnkr.co/edit/D7TzdaBVRvJr2sid


来源: stackexchange

问:
ASP.NET Core API Endpoint which delivers a Stream instead of big JSONArray
I have a pretty big list of objects, which needs to be received fast from the client. Currently it takes about 2-4 seconds. I now try to use streams to send chunks (e.g. 100 objects in each) I know that GRPC can use streams but in ASP.NET core, how can I achieve this? The normal ASP.NET has PushStreamContent which is not available in Core. Any solutions out there? I can't really find a proper one online.

So what my Controller currently looks like:

```<code> [HttpGet]
 public async Task<ActionResult<IEnumerable<Price>>> GetPrices()
 {
     return await _context.Prices.ToListAsync();
 }
</code>```

This list currently contains around 18700 Items but this number will increase by time.

答:
I'm guessing you're using EF Core based on your example.

If you take a look at Efficient Querying - Buffering and streaming, they recommend using AsEnumerable to stream the data instead of ToList, which essentially loads all data into memory before (in your case) returning it to the client. The async version is AsAsyncEnumerable.

So you should be able to simply change your controller action into:

```<code>[HttpGet]
public async Task<ActionResult<IEnumerable<Price>>> GetPrices()
{
    return await _context.Prices.AsAsyncEnumerable();
}
</code>```

Note, that streaming rather than buffering/loading into memory does not mean performance improvements in all cases, but with a large dataset there's a good chance you'll see better performance.

is it a code smell / bad practice to send such big JSON data?

Not necessarily. If you actually need to have the entire dataset client-side, then this is probably the most efficient approach. However, if your dataset is large, you should expect that it takes some time to download. If your download speed is 5 MB/s and your Price data is 10 MB, then you'll never make it faster than 2 seconds without a better connection. Even if you use a stream from your backend.

Another approach (if that fits your needs) is to introduce paging. That way you can retrieve e.g. 50 items at a time instead of everything and then page through it. But whether it makes sense to use paging from your client is up to you.

ContentLicense: CC BY-SA 4.0

Body:
I have a pretty big list of objects, which needs to be received fast from the client. Currently it takes about 2-4 seconds. I now try to use streams to send chunks (e.g. 100 objects in each) I know that GRPC can use streams but in ASP.NET core, how can I achieve this? The normal ASP.NET has PushStreamContent which is not available in Core. Any solutions out there? I can't really find a proper one online.

So what my Controller currently looks like:

 [HttpGet]
 public async Task<ActionResult<IEnumerable<Price>>> GetPrices()
 {
     return await _context.Prices.ToListAsync();
 }

This list currently contains around 18700 Items but this number will increase by time.

Body:
I'm guessing you're using EF Core based on your example.

If you take a look at Efficient Querying - Buffering and streaming, they recommend using AsEnumerable to stream the data instead of ToList, which essentially loads all data into memory before (in your case) returning it to the client. The async version is AsAsyncEnumerable.

So you should be able to simply change your controller action into:

[HttpGet]
public async Task<ActionResult<IEnumerable<Price>>> GetPrices()
{
    return await _context.Prices.AsAsyncEnumerable();
}

Note, that streaming rather than buffering/loading into memory does not mean performance improvements in all cases, but with a large dataset there's a good chance you'll see better performance.

is it a code smell / bad practice to send such big JSON data?

Not necessarily. If you actually need to have the entire dataset client-side, then this is probably the most efficient approach. However, if your dataset is large, you should expect that it takes some time to download. If your download speed is 5 MB/s and your Price data is 10 MB, then you'll never make it faster than 2 seconds without a better connection. Even if you use a stream from your backend.

Another approach (if that fits your needs) is to introduce paging. That way you can retrieve e.g. 50 items at a time instead of everything and then page through it. But whether it makes sense to use paging from your client is up to you.


答:
Try this to get, e.g., the 49th element:

```<code>A[0][49]
</code>```

To save the numbers in a 1D array, use this:

```<code>A = A[0]
</code>```

Title: Extracting elements from a list of size 1

Body:
I have a np array of this type. It is of size 1 but there are 90 numbers in it. Is there any way I can extract all those numbers and save them as a new 1D numpy array?

    Array of int64    list    (90,)  A = [7.065590000000000000e+05   7.221840000000000000e+05
    7.378090000000000000e+05
    1.503434000000000000e+06
    ...
    2.381593400000000000e+07
    2.383155900000000000e+07
    2.384718400000000000e+07]

Body:
Try this to get, e.g., the 49th element:

A[0][49]

To save the numbers in a 1D array, use this:

A = A[0]


问:
React useEffect causing: Can't perform a React state update on an unmounted component
When fetching data I'm getting: Can't perform a React state update on an unmounted component. The app still works, but react is suggesting I might be causing a memory leak.

This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."

Why do I keep getting this warning?

I tried researching these solutions:

https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal

https://developer.mozilla.org/en-US/docs/Web/API/AbortController

but this still was giving me the warning.

```<code>const  ArtistProfile = props => {
  const [artistData, setArtistData] = useState(null)
  const token = props.spotifyAPI.user_token

  const fetchData = () => {
    const id = window.location.pathname.split("/").pop()
    console.log(id)
    props.spotifyAPI.getArtistProfile(id, ["album"], "US", 10)
    .then(data => {setArtistData(data)})
  }
  useEffect(() => {
    fetchData()
    return () => { props.spotifyAPI.cancelRequest() }
  }, [])

  return (
    <ArtistProfileContainer>
      <AlbumContainer>
        {artistData ? artistData.artistAlbums.items.map(album => {
          return (
            <AlbumTag
              image={album.images[0].url}
              name={album.name}
              artists={album.artists}
              key={album.id}
            />
          )
        })
        : null}
      </AlbumContainer>
    </ArtistProfileContainer>
  )
}
</code>```

Edit:

In my api file I added an AbortController() and used a signal so I can cancel a request.

```<code>export function spotifyAPI() {
  const controller = new AbortController()
  const signal = controller.signal

// code ...

  this.getArtist = (id) => {
    return (
      fetch(
        `https://api.spotify.com/v1/artists/${id}`, {
        headers: {"Authorization": "Bearer " + this.user_token}
      }, {signal})
      .then(response => {
        return checkServerStat(response.status, response.json())
      })
    )
  }

  // code ...

  // this is my cancel method
  this.cancelRequest = () => controller.abort()
}
</code>```

My spotify.getArtistProfile() looks like this

```<code>this.getArtistProfile = (id,includeGroups,market,limit,offset) => {
  return Promise.all([
    this.getArtist(id),
    this.getArtistAlbums(id,includeGroups,market,limit,offset),
    this.getArtistTopTracks(id,market)
  ])
  .then(response => {
    return ({
      artist: response[0],
      artistAlbums: response[1],
      artistTopTracks: response[2]
    })
  })
}
</code>```

but because my signal is used for individual api calls that are resolved in a Promise.all I can't abort() that promise so I will always be setting the state.

答:
This works for me :')</p>
```<code>   const [state, setState] = useState({});
    useEffect( async ()=>{
          let data= await props.data; // data from API too
          setState(users);
        },[props.data]);
</code>```

Body:
When fetching data I'm getting: Can't perform a React state update on an unmounted component. The app still works, but react is suggesting I might be causing a memory leak.

This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."

Why do I keep getting this warning?

I tried researching these solutions:

https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal

https://developer.mozilla.org/en-US/docs/Web/API/AbortController

but this still was giving me the warning.

const  ArtistProfile = props => {
  const [artistData, setArtistData] = useState(null)
  const token = props.spotifyAPI.user_token

  const fetchData = () => {
    const id = window.location.pathname.split("/").pop()
    console.log(id)
    props.spotifyAPI.getArtistProfile(id, ["album"], "US", 10)
    .then(data => {setArtistData(data)})
  }
  useEffect(() => {
    fetchData()
    return () => { props.spotifyAPI.cancelRequest() }
  }, [])

  return (
    <ArtistProfileContainer>
      <AlbumContainer>
        {artistData ? artistData.artistAlbums.items.map(album => {
          return (
            <AlbumTag
              image={album.images[0].url}
              name={album.name}
              artists={album.artists}
              key={album.id}
            />
          )
        })
        : null}
      </AlbumContainer>
    </ArtistProfileContainer>
  )
}

Edit:

In my api file I added an AbortController() and used a signal so I can cancel a request.

export function spotifyAPI() {
  const controller = new AbortController()
  const signal = controller.signal

// code ...

  this.getArtist = (id) => {
    return (
      fetch(
        `https://api.spotify.com/v1/artists/${id}`, {
        headers: {"Authorization": "Bearer " + this.user_token}
      }, {signal})
      .then(response => {
        return checkServerStat(response.status, response.json())
      })
    )
  }

  // code ...

  // this is my cancel method
  this.cancelRequest = () => controller.abort()
}

My spotify.getArtistProfile() looks like this

this.getArtistProfile = (id,includeGroups,market,limit,offset) => {
  return Promise.all([
    this.getArtist(id),
    this.getArtistAlbums(id,includeGroups,market,limit,offset),
    this.getArtistTopTracks(id,market)
  ])
  .then(response => {
    return ({
      artist: response[0],
      artistAlbums: response[1],
      artistTopTracks: response[2]
    })
  })
}

but because my signal is used for individual api calls that are resolved in a Promise.all I can't abort() that promise so I will always be setting the state.

Body:
This works for me :')

   const [state, setState] = useState({});
    useEffect( async ()=>{
          let data= await props.data; // data from API too
          setState(users);
        },[props.data]);


问:
Python pandas how to use a lamda function to convert duplicated code in 1 line
I have a pandas python code like this:

```<code>def mul3(df):
    df['mul31'] = df['tpx1'].values * df['tqy1'].values * df['vtin1'].values * df[
        'slife1'].values
    df['mul32'] = df['tpx2'].values * df['tqy2'].values * df['vtin2'].values * df[
        'slife1'].values
    df['mul33'] = df['tpx3'].values * df['tqy3'].values * df['vtin3'].values * df[
        'slife1'].values
    df['mul34'] = df['tpx4'].values * df['tqy4'].values * df['vtin4'].values * df[
        'slife1'].values
    df['mul35'] = df['tpx5'].values * df['tqy5'].values * df['vtin5'].values * df[
        'slife1'].values
    return df
</code>```

Is there anyway I can use a lamda function to replace it to 1 line code?
Any friend can help?

答:
This is exactly like @richardec's solution. The only difference is it uses a dict comprehension and assign.

```<code>df = df.assign(**{f'mul3{i}': df[f'tpx{i}'] * df[f'tqy{i}'] * df[f'vtin{i}'] * df['slife1'] for i in range(1,6)})
</code>```

Body:
I have a pandas python code like this:

def mul3(df):
    df['mul31'] = df['tpx1'].values * df['tqy1'].values * df['vtin1'].values * df[
        'slife1'].values
    df['mul32'] = df['tpx2'].values * df['tqy2'].values * df['vtin2'].values * df[
        'slife1'].values
    df['mul33'] = df['tpx3'].values * df['tqy3'].values * df['vtin3'].values * df[
        'slife1'].values
    df['mul34'] = df['tpx4'].values * df['tqy4'].values * df['vtin4'].values * df[
        'slife1'].values
    df['mul35'] = df['tpx5'].values * df['tqy5'].values * df['vtin5'].values * df[
        'slife1'].values
    return df

Is there anyway I can use a lamda function to replace it to 1 line code?
Any friend can help?

Body:
This is exactly like @richardec's solution. The only difference is it uses a dict comprehension and assign.

df = df.assign(**{f'mul3{i}': df[f'tpx{i}'] * df[f'tqy{i}'] * df[f'vtin{i}'] * df['slife1'] for i in range(1,6)})


问:
Getting datetime count range in SQL Server
I try to get the date range between the data changes in SQL Server
my query is

```<code>select count(1) as qty, Info, convert(char,dFError,100) dErr
from TableData
group by Info, convert(char,dFError,100)
order by dErr asc
</code>```

I have this
qty has the number of reques to a server, info are the servers ip and the date it's when a request it's sended to another server.

qty
Info
dErr

1
1.97
Aug 11 2021  9:01AM

1
1.97
Aug 11 2021  9:06AM

88
1.33
Dec 21 2021  2:04PM

1
1.95
Dec 22 2021  9:44PM

9
1.95
Dec 22 2021  9:45PM

1
1.33
Dec 22 2021  9:51PM

19
1.33
Dec 22 2021  9:52PM

3
1.33
Dec 22 2021  9:53PM

6
1.33
Dec 27 2021  7:10PM

17
1.33
Dec 27 2021  7:11PM

15
1.95
Dec 27 2021  7:17PM

8
1.95
Dec 27 2021  7:18PM

and I want this, in Aug 11 at 9:06AM all are going to 1.97, at Dec 21 at 2:04PM all are going to 1.33, that means the date and the info

qty
Info
dErr

2
1.97
Aug 11 2021  9:06AM

88
1.33
Dec 21 2021  2:04PM

10
1.95
Dec 22 2021  9:45PM

46
1.33
Dec 27 2021  7:11PM

23
1.95
Dec 27 2021  7:18PM

in the same day can be the same group of numbers on distinct hour

qty
Info
dErr

1
1.97
Jan 24 2022  9:39AM

1
1.97
Jan 24 2022  9:51AM

1
1.97
Jan 24 2022  9:58AM

4
1.97
Jan 24 2022 10:08AM

1
1.97
Jan 24 2022 10:12AM

8
1.95
Jan 24 2022 10:24AM

2
1.95
Jan 24 2022 10:32AM

10
1.33
Jan 24 2022 10:33AM

1
1.33
Jan 24 2022 11:37AM

8
1.95
Jan 24 2022 11:59AM

1
1.95
Jan 24 2022 12:00PM

2
1.95
Jan 24 2022 12:08PM

and need to be displayed like

qty
Info
dErr

8
1.97
Jan 24 2022  10:12AM

10
1.95
Jan 24 2022 10:32AM

11
1.33
Jan 24 2022 11:37AM

11
1.95
Jan 24 2022 12:08PM

答:
```<code>select
    SUM(P_COUNT) as "COUNT",
    P_DATA as "DATA",
    MAX(FECHA) as "FECHA"
from
    TABLEA
GROUP BY
    P_DATA, CONVERT(DATE, FECHA)
ORDER BY "FECHA"
</code>```

Body:
I try to get the date range between the data changes in SQL Server
my query is

select count(1) as qty, Info, convert(char,dFError,100) dErr
from TableData
group by Info, convert(char,dFError,100)
order by dErr asc

I have this
qty has the number of reques to a server, info are the servers ip and the date it's when a request it's sended to another server.

qty
Info
dErr

1
1.97
Aug 11 2021  9:01AM

1
1.97
Aug 11 2021  9:06AM

88
1.33
Dec 21 2021  2:04PM

1
1.95
Dec 22 2021  9:44PM

9
1.95
Dec 22 2021  9:45PM

1
1.33
Dec 22 2021  9:51PM

19
1.33
Dec 22 2021  9:52PM

3
1.33
Dec 22 2021  9:53PM

6
1.33
Dec 27 2021  7:10PM

17
1.33
Dec 27 2021  7:11PM

15
1.95
Dec 27 2021  7:17PM

8
1.95
Dec 27 2021  7:18PM

and I want this, in Aug 11 at 9:06AM all are going to 1.97, at Dec 21 at 2:04PM all are going to 1.33, that means the date and the info

qty
Info
dErr

2
1.97
Aug 11 2021  9:06AM

88
1.33
Dec 21 2021  2:04PM

10
1.95
Dec 22 2021  9:45PM

46
1.33
Dec 27 2021  7:11PM

23
1.95
Dec 27 2021  7:18PM

in the same day can be the same group of numbers on distinct hour

qty
Info
dErr

1
1.97
Jan 24 2022  9:39AM

1
1.97
Jan 24 2022  9:51AM

1
1.97
Jan 24 2022  9:58AM

4
1.97
Jan 24 2022 10:08AM

1
1.97
Jan 24 2022 10:12AM

8
1.95
Jan 24 2022 10:24AM

2
1.95
Jan 24 2022 10:32AM

10
1.33
Jan 24 2022 10:33AM

1
1.33
Jan 24 2022 11:37AM

8
1.95
Jan 24 2022 11:59AM

1
1.95
Jan 24 2022 12:00PM

2
1.95
Jan 24 2022 12:08PM

and need to be displayed like

qty
Info
dErr

8
1.97
Jan 24 2022  10:12AM

10
1.95
Jan 24 2022 10:32AM

11
1.33
Jan 24 2022 11:37AM

11
1.95
Jan 24 2022 12:08PM


问:
summing up values in R dataframe without aggregation
How can I add up row values in a dataframe based on conditions without having to aggregate the whole table?

I have this df:

```<code>  town party votes
1    a     A     1
2    a     B     2
3    a     C     3
4    b     A     4
5    b     B     5
6    b     C     6
7    c     A     7
8    c     B     8
9    c     C     9
</code>```

I would like to add the votes of one party to those of another by town, without touching the values of the third one.

Basically to run df$votes[df$party == A] = df$votes[df$party == A] + df$votes[df$party == B] for each category of df$town

答:
You can try mutate with dplyr if you want to keep the structure of the dataframe

```<code>library(dplyr)

df %>%
  group_by(town) %>%
  mutate(sum=ifelse(party!="C", sum(votes[party!="C"]), votes)) %>%
  ungroup()
# A tibble: 9 × 4
  town  party votes   sum
  <chr> <chr> <int> <int>
1 a     A         1     3
2 a     B         2     3
3 a     C         3     3
4 b     A         4     9
5 b     B         5     9
6 b     C         6     6
7 c     A         7    15
8 c     B         8    15
9 c     C         9     9
</code>```

Another way using summarise

```<code>df %>%
  filter(party!="C") %>%
  group_by(town) %>%
  summarise(sum=sum(votes))
# A tibble: 3 × 2
  town    sum
  <chr> <int>
1 a         3
2 b         9
3 c        15
</code>```

Body:
How can I add up row values in a dataframe based on conditions without having to aggregate the whole table?

I have this df:

  town party votes
1    a     A     1
2    a     B     2
3    a     C     3
4    b     A     4
5    b     B     5
6    b     C     6
7    c     A     7
8    c     B     8
9    c     C     9

I would like to add the votes of one party to those of another by town, without touching the values of the third one.

Basically to run df$votes[df$party == A] = df$votes[df$party == A] + df$votes[df$party == B] for each category of df$town

Body:
You can try mutate with dplyr if you want to keep the structure of the dataframe

library(dplyr)

df %>%
  group_by(town) %>%
  mutate(sum=ifelse(party!="C", sum(votes[party!="C"]), votes)) %>%
  ungroup()
# A tibble: 9 × 4
  town  party votes   sum
  <chr> <chr> <int> <int>
1 a     A         1     3
2 a     B         2     3
3 a     C         3     3
4 b     A         4     9
5 b     B         5     9
6 b     C         6     6
7 c     A         7    15
8 c     B         8    15
9 c     C         9     9

Another way using summarise

df %>%
  filter(party!="C") %>%
  group_by(town) %>%
  summarise(sum=sum(votes))
# A tibble: 3 × 2
  town    sum
  <chr> <int>
1 a         3
2 b         9
3 c        15


问:
Appending a cloned row of a table to a specified position on table
```<code>function CreateInterface(){
    document.getElementById("welcome").innerHTML=
       '<form action="?" method="get" onsubmit=" return validate(this)">' +
       '<table id="dataTable" summary="" cellspacing="3" cellpadding="0" border="0">' +
       '<tr id="tablerow">' + '<td><INPUT type="checkbox" name="chk"/></td> '+
       '<th>Userid   : </th>' + '<td ><input name="userid" type="text" class="text" value="" maxlength="10" /></td>' +
       '</tr>' + '<tr><td colspan="2" align="center">'+
       '<INPUT type="button" value="Add" onclick="addRow()" />' +
       '<INPUT type="button" value="Delete" onclick="delRow()" />' +
       '<input type="submit" value="submit" />'+'</td></tr>' +
       '</table>' +
       '</form>';
}

function addRow(){

  var clnNode=document.getElementById("tablerow").cloneNode(true);
  document.getElementById("dataTable").appendChild(clnNode);
}
</code>```

This is my code , i want this cloned node to be inserted above the buttons. In fact this code is not working, i.e. node is not getting added to table. Please help me solve this

答:
Do not use id="tablerow" as duplicate ids will cause malformed HTML.

Change
 in your string to just

Script

```<code>function addRow() {
    var referenceNodes = document.getElementById("dataTable").getElementsByTagName("tr");
    //-2 because last row is button row
    var referenceNode = referenceNodes[referenceNodes.length - 2];
    var newNode = referenceNode.cloneNode(true);
    newNode.getElementsByTagName("input")[0].checked = false;
    newNode.getElementsByTagName("input")[1].value = "";
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
</code>```

Demo: http://jsfiddle.net/naveen/wbFMm/

ContentLicense: CC BY-SA 3.0

Body:
function CreateInterface(){
    document.getElementById("welcome").innerHTML=
       '<form action="?" method="get" onsubmit=" return validate(this)">' +
       '
' +
       '
' + '<INPUT type="checkbox" name="chk"/>	 '+
       'Userid   : 	' + '<input name="userid" type="text" class="text" value="" maxlength="10" />	' +
       '
' + '
'+
       '<INPUT type="button" value="Add" onclick="addRow()" />' +
       '<INPUT type="button" value="Delete" onclick="delRow()" />' +
       '<input type="submit" value="submit" />'+'
' +
       '
' +
       '</form>';
}

function addRow(){

  var clnNode=document.getElementById("tablerow").cloneNode(true);
  document.getElementById("dataTable").appendChild(clnNode);
}

This is my code , i want this cloned node to be inserted above the buttons. In fact this code is not working, i.e. node is not getting added to table. Please help me solve this

Body:
Do not use id="tablerow" as duplicate ids will cause malformed HTML.

Change <tr id="tablerow"> in your string to just <tr>

Script

function addRow() {
    var referenceNodes = document.getElementById("dataTable").getElementsByTagName("tr");
    //-2 because last row is button row
    var referenceNode = referenceNodes[referenceNodes.length - 2];
    var newNode = referenceNode.cloneNode(true);
    newNode.getElementsByTagName("input")[0].checked = false;
    newNode.getElementsByTagName("input")[1].value = "";
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

Demo: http://jsfiddle.net/naveen/wbFMm/


问:
Is there a way of shuffling partition data on Apache Ignite?
I've got a question that is related to data repartitioning.
Suppose there's a cache with a pre-defined affinity key. Assume I need to repartition data with a new affinity key. I'm wondering whether there is a way of shuffling partition data across all nodes by a new affinity key?</p>

答:
You need to repopulate the data in that case.

First, it's a static configuration and can't be changed on the fly.

The second, most likely you will need to clear meta-information for that particular type, i.e. clean work/binary_meta folder.

The last one - once you changed it, you won't be able to locate the data since most likely it will be stored in a different partition.

In other words, say, you had a cache key with two fields A and B: K(A,B) where A is your affinity key. Say, your Key(1,2) was mapped to a partition 5. In that case, to locate the value, Ignite will search for this partition 5 depending on which node hold the primary copy of it. Later you wanted to have B as the affinity key and re-configure the cache accordingly. In that case, Key(1,2) might now be mapped to a partition 780, meaning that Ignite will never search for a partition 5 and won't be able to locate the previous data.


问:
NEAR Indexer and 2FA secured wallet transactions
In the Near, transactions signed by a 2FA-protected wallet are done in a special way (contract confirmation) and are not like regular transactions.
Signer and receiver id the same wallet.
Sample transaction:
https://explorer.near.org/transactions/9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY

How to work with them properly, where to find them in Indexer?
How do I get the data correctly, what contract and method the user signs?

答:
NEAR Indexer for Explorer core contributor and maintainer here.

Looking at the transaction you've provided in your question https://explorer.near.org/transactions/9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY it was a FUNCTION CALL of the method confirm

And I believe your concern is that you cannot see the result of your transaction in the public NEAR Indexer for Explorer database by querying the transactions table with the hash.

And by saying that 2FA transactions "are not like regular transactions" you mean the nature of cross-contract calls involved.

Here's how to find out what is happening

First of all, let's look for your initial transaction and the Receipt ID it was converted to.

```<code>SELECT transaction_hash, converted_into_receipt_id FROM transactions WHERE transaction_hash = '9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY';

               transaction_hash               |          converted_into_receipt_id
----------------------------------------------+----------------------------------------------
 9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY | FP5UmXxdDBBicGkzgXXdhS28hxgBWVByFcqbwh25qHzN
</code>```

According to the fact that this transaction you've sent was a confirmation of some ft_transfer call, we expect that there will happen a cross contract call to the gems.l2e.near contract.

We want to find all the receipts produced after execution of the receipt id FP5UmXxdDBBicGkzgXXdhS28hxgBWVByFcqbwh25qHzN (we found it in step 1)

Search for all receipts that were created during the execution of the initial one

```<code>SELECT produced_receipt_id FROM execution_outcome_receipts WHERE executed_receipt_id = 'FP5UmXxdDBBicGkzgXXdhS28hxgBWVByFcqbwh25qHzN';
             produced_receipt_id
----------------------------------------------
 9zem8CxJvdTHKkZKCc1pFhg4Ky4st6TBrQmE19gv4sAU
 3mtnLaGFYpXXzZ4H9vYczSXz9JbdS7XueSobDjQDAYb3
(2 rows)
</code>```

So we have two other receipts, but we don't actually know what action they are containing. Let's find it out.

```<code>SELECT receipt_id, action_kind, receipt_predecessor_account_id, receipt_receiver_account_id, args FROM action_receipt_actions WHERE receipt_id IN ('9zem8CxJvdTHKkZKCc1pFhg4Ky4st6TBrQmE19gv4sAU', '3mtnLaGFYpXXzZ4H9vYczSXz9JbdS7XueSobDjQDAYb3');
                  receipt_id                  |  action_kind  | receipt_predecessor_account_id | receipt_receiver_account_id |                                                                                args
----------------------------------------------+---------------+--------------------------------+-----------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 3mtnLaGFYpXXzZ4H9vYczSXz9JbdS7XueSobDjQDAYb3 | TRANSFER      | system                         | shishkerin.near             | {"deposit": "12306467158537048105440"}
 9zem8CxJvdTHKkZKCc1pFhg4Ky4st6TBrQmE19gv4sAU | FUNCTION_CALL | shishkerin.near                | gems.l2e.near               | {"gas": 220000000000000, "deposit": "1", "args_json": {"amount": "2970000", "receiver_id": "hot1.l2e.near"}, "args_base64": "eyJyZWNlaXZlcl9pZCI6ImhvdDEubDJlLm5lYXIiLCJhbW91bnQiOiIyOTcwMDAwIn0=", "method_name": "ft_transfer"}
(2 rows)
</code>```

Here we can see that Receipt 9zem8CxJvdTHKkZKCc1pFhg4Ky4st6TBrQmE19gv4sAU is actually making a FUNCTION_CALL to gems.l2e.near signed by shishkerin.near

We can also look at args and find out that the method is calls is ft_transfer and arguments are {"amount": "2970000", "receiver_id": "hot1.l2e.near"}

(The other receipt 3mtnLaGFYpXXzZ4H9vYczSXz9JbdS7XueSobDjQDAYb3 is a transfer signed by system which is basically a cash-back for attached gas)

And just for sanity we'd like to know the execution status of the receipt

```<code>SELECT receipt_id, status FROM execution_outcomes WHERE receipt_id = '9zem8CxJvdTHKkZKCc1pFhg4Ky4st6TBrQmE19gv4sAU';
                  receipt_id                  |    status
----------------------------------------------+---------------
 9zem8CxJvdTHKkZKCc1pFhg4Ky4st6TBrQmE19gv4sAU | SUCCESS_VALUE
</code>```

And I hope this answers your question.

Shared Public Access to NEAR Indexer for Explorer PostgreSQL database

Decisions on what tables to query and what columns to get are made with Database structure image in mind

Body:
NEAR Indexer for Explorer core contributor and maintainer here.

Looking at the transaction you've provided in your question https://explorer.near.org/transactions/9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY it was a FUNCTION CALL of the method confirm

And I believe your concern is that you cannot see the result of your transaction in the public NEAR Indexer for Explorer database by querying the transactions table with the hash.

And by saying that 2FA transactions "are not like regular transactions" you mean the nature of cross-contract calls involved.

Here's how to find out what is happening

First of all, let's look for your initial transaction and the Receipt ID it was converted to.

SELECT transaction_hash, converted_into_receipt_id FROM transactions WHERE transaction_hash = '9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY';

               transaction_hash               |          converted_into_receipt_id
----------------------------------------------+----------------------------------------------
 9uPvkdmcL4iNnWrHXZocf7NLAJUUVa4zSMrtFtJhrjcY | FP5UmXxdDBBicGkzgXXdhS28hxgBWVByFcqbwh25qHzN

According to the fact that this transaction you've sent was a confirmation of some ft_transfer call, we expect that there will happen a cross contract call to the gems.l2e.near contract.

We want to find all the receipts produced after execution of the receipt id FP5UmXxdDBBicGkzgXXdhS28hxgBWVByFcqbwh25qHzN (we found it in step 1)

Search for all receipts that were created during the execution of the initial one

SELECT produced_receipt_id FROM execution_outcome_receipts WHERE executed_receipt_id = 'FP5UmXxdDBBicGkzgXXdhS28hxgBWVByFcqbwh25qHzN';
             produced_receipt_id
----------------------------------------------
 9zem8CxJvdTHKkZKCc1pFhg4Ky4st6TBrQmE19gv4sAU
 3mtnLaGFYpXXzZ4H9vYczSXz9JbdS7XueSobDjQDAYb3
(2 rows)

So we have two other receipts, but we don't actually know what action they are containing. Let's find it out.

SELECT receipt_id, action_kind, receipt_predecessor_account_id, receipt_receiver_account_id, args FROM action_receipt_actions WHERE receipt_id IN ('9zem8CxJvdTHKkZKCc1pFhg4Ky4st6TBrQmE19gv4sAU', '3mtnLaGFYpXXzZ4H9vYczSXz9JbdS7XueSobDjQDAYb3');
                  receipt_id                  |  action_kind  | receipt_predecessor_account_id | receipt_receiver_account_id |                                                                                args
----------------------------------------------+---------------+--------------------------------+-----------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 3mtnLaGFYpXXzZ4H9vYczSXz9JbdS7XueSobDjQDAYb3 | TRANSFER      | system                         | shishkerin.near             | {"deposit": "12306467158537048105440"}
 9zem8CxJvdTHKkZKCc1pFhg4Ky4st6TBrQmE19gv4sAU | FUNCTION_CALL | shishkerin.near                | gems.l2e.near               | {"gas": 220000000000000, "deposit": "1", "args_json": {"amount": "2970000", "receiver_id": "hot1.l2e.near"}, "args_base64": "eyJyZWNlaXZlcl9pZCI6ImhvdDEubDJlLm5lYXIiLCJhbW91bnQiOiIyOTcwMDAwIn0=", "method_name": "ft_transfer"}
(2 rows)

Here we can see that Receipt 9zem8CxJvdTHKkZKCc1pFhg4Ky4st6TBrQmE19gv4sAU is actually making a FUNCTION_CALL to gems.l2e.near signed by shishkerin.near

We can also look at args and find out that the method is calls is ft_transfer and arguments are {"amount": "2970000", "receiver_id": "hot1.l2e.near"}

(The other receipt 3mtnLaGFYpXXzZ4H9vYczSXz9JbdS7XueSobDjQDAYb3 is a transfer signed by system which is basically a cash-back for attached gas)

And just for sanity we'd like to know the execution status of the receipt

SELECT receipt_id, status FROM execution_outcomes WHERE receipt_id = '9zem8CxJvdTHKkZKCc1pFhg4Ky4st6TBrQmE19gv4sAU';
                  receipt_id                  |    status
----------------------------------------------+---------------
 9zem8CxJvdTHKkZKCc1pFhg4Ky4st6TBrQmE19gv4sAU | SUCCESS_VALUE

And I hope this answers your question.

Shared Public Access to NEAR Indexer for Explorer PostgreSQL database

Decisions on what tables to query and what columns to get are made with Database structure image in mind


问:
Json schema precedence with multiple patternProperties
I'm writing a schema that has multiple patternProperties elements. Is there a way to specify the precedence these patterns should be checked?

Given this schema:

{
  $id: "https://example.com/mySchema",
  type: "object",
  patternProperties: {
    "^foo\\.bar\\.[a-zA-Z0-9-]+\\.(?:string|boolean|date|)$": { // #1
      type: "object",
      properties: { ... }
    },
    "^bar\\.foo\\.[a-zA-Z0-9-]+\\.(?:string|boolean|date|)$": { // #2
      type: "object",
      properties: { ... }
    },
    "^foo\\.[a-zA-Z0-9-]+\\.[a-zA-Z0-9-]+\\.(?:string|boolean|date|)$": { // #3
      type: "object",
      properties: { ... }
    },
  }
}
```
<p>And the json being validated:</p>
<pre class="lang-json prettyprint-override"><code>{
  foo.bar.baz.boolean: { ... }
}
</code>```

The validation is failing because it is checking against pattern #3 instead of pattern #1. Is it possible to validate using the most restrictive pattern first?

For more context: I'm currently using AJV for implementing the validation. If there's a better alternative, I'm open the suggestions

答:
The specification doesn't indicate an order in which the patterns should be applied, so an implementation could do anything, from running them in sorted alphabetical order or any other ordering of its choosing.

However, all patterns that match each property must evaluate their subschemas, so the ordering that they are checked should not be significant. If you are finding that the implementation stops matching a particular property as soon as a matching pattern is found, that would be a bug that should be fixed.

Body:
I'm writing a schema that has multiple patternProperties elements. Is there a way to specify the precedence these patterns should be checked?

Given this schema:

{
  $id: "https://example.com/mySchema",
  type: "object",
  patternProperties: {
    "^foo\\.bar\\.[a-zA-Z0-9-]+\\.(?:string|boolean|date|)$": { // #1
      type: "object",
      properties: { ... }
    },
    "^bar\\.foo\\.[a-zA-Z0-9-]+\\.(?:string|boolean|date|)$": { // #2
      type: "object",
      properties: { ... }
    },
    "^foo\\.[a-zA-Z0-9-]+\\.[a-zA-Z0-9-]+\\.(?:string|boolean|date|)$": { // #3
      type: "object",
      properties: { ... }
    },
  }
}

And the json being validated:

{
  foo.bar.baz.boolean: { ... }
}

The validation is failing because it is checking against pattern #3 instead of pattern #1. Is it possible to validate using the most restrictive pattern first?

For more context: I'm currently using AJV for implementing the validation. If there's a better alternative, I'm open the suggestions


问:
Java add a Dashed or dotted border to a JPanel
I am having problems with this thing: can I, in some way, add a dashed (or dotted, no matter) border to a JPanel?

I searched SO questions but seems that no one asked this before.

I'm wondering if is there any class to use. actually I am using:

```<code>myPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
</code>```

Obviously this is a standard class that give only few standard borders, no one is useful for me.

答:
Using Java 6 I had issues with getting a custom AbstractBorder from Timmos solution (above) to work. The drawing would show odd artifacts like only a few pixels would draw sporadically. The insets needed to be defined and can be done by adding the following methods:

```<code>public Insets getBorderInsets(Component c)
{
    return new Insets(thickness, thickness, thickness, thickness);
}

public Insets getBorderInsets(Component c, Insets insets)
    insets.left = insets.right = insets.top = insets.bottom = thickness;
    return insets;
}
</code>```

Where the thickness is whatever you want for your border. e.g. 1

Body:
I am having problems with this thing: can I, in some way, add a dashed (or dotted, no matter) border to a JPanel?

I searched SO questions but seems that no one asked this before.

I'm wondering if is there any class to use. actually I am using:

myPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

Obviously this is a standard class that give only few standard borders, no one is useful for me.

Body:
Using Java 6 I had issues with getting a custom AbstractBorder from Timmos solution (above) to work. The drawing would show odd artifacts like only a few pixels would draw sporadically. The insets needed to be defined and can be done by adding the following methods:

public Insets getBorderInsets(Component c)
{
    return new Insets(thickness, thickness, thickness, thickness);
}

public Insets getBorderInsets(Component c, Insets insets)
    insets.left = insets.right = insets.top = insets.bottom = thickness;
    return insets;
}

Where the thickness is whatever you want for your border. e.g. 1


问:
Symmetrical link between two objects in Django
I have a model with all the info of a plant and another model which consists of creating links between these plants. But when I create a link between two plants for example I create an ideal link between basil and garlic in the Django admin, I don't have the symmetrical link between garlic and basil. Should we add symmetrical = true in the model?

Here is Plant model :

from django.db import models

class Plant(models.Model):
    class LEVEL(models.TextChoices):
        NONE = None
        EASY = 'easy',
        MEDIUM = 'medium',
        HARD = 'hard'

    class SUNSHINE(models.TextChoices):
        NONE = None
        FULL_SUN = 'full_sun',
        SHADOW = 'shadow',
        SUNNY = 'sunny',
        MODERATE = 'moderate'

    class IRRIGATION(models.TextChoices):
        NONE = None
        WET = 'wet',
        WEAKLY = 'weakly',
        MOIST = 'keep_soil_moist',
        GENEROUSLY = 'generously',
        SLIGHTLY_DAMP = 'slightly_damp',
        COVERED_WITH_WATER = 'covered_with_water'

    class SOIL_N(models.TextChoices):
        NONE = None
        HUMUS = 'humus',
        LIGHT = 'light',
        CLAY = 'clay',
        DRAINED = 'drained',
        ALL_TYPE = 'all_types'

    class SOIL_T(models.TextChoices):
        NONE = None
        POOR = 'poor',
        MEDIUM_SOIL = 'medium_soil',
        RICH = 'rich',
        FERTILE = 'fertile',
        DRAINED = 'drained',
        ADD_PEBBLES = 'add_pebbles',
        ALL_TYPE = 'all_types'

    class HARDINESS(models.TextChoices):
        NONE = None
        VERY_FRAGILE = 'very_fragile',
        FRAGILE = 'fragile',
        RUSTIC = 'rustic',
        MEDIUM = 'medium',
        SUPPORT_FRESHNESS = 'support_freshness',
        # COLD_RESISTANT = 'cold_resistant'

    name = models.CharField(max_length=150, unique=True)
    family = models.ForeignKey('perma_families.Family', on_delete=models.CASCADE, default=3)
    category = models.ForeignKey('perma_plant_categories.PlantCategory', on_delete=models.CASCADE, default=1)
    facility_rate = models.CharField(max_length=50, choices=LEVEL.choices, default=LEVEL.NONE, blank=True, null=True)
    seedling_depth = models.CharField(max_length=50, blank=True, null=True)
    seedling_distance = models.CharField(max_length=50, blank=True, null=True)
    row_spacing = models.CharField(max_length=50, blank=True, null=True)
    sunshine_index = models.CharField(max_length=50, choices=SUNSHINE.choices, default=SUNSHINE.NONE, blank=True, null=True)
    irrigation_index = models.CharField(max_length=50, choices=IRRIGATION.choices, default=IRRIGATION.NONE, blank=True, null=True)
    soil_nature = models.CharField(max_length=50, choices=SOIL_N.choices, default=SOIL_N.NONE, blank=True, null=True)
    soil_type = models.CharField(max_length=50, choices=SOIL_T.choices, default=SOIL_T.NONE, blank=True, null=True)
    fertilizer_type = models.CharField(max_length=50, blank=True, null=True)
    acidity_index = models.CharField(max_length=50, blank=True, null=True)
    days_before_sprouting = models.CharField(max_length=50, blank=True, null=True)
    average_harvest_time = models.CharField(max_length=50, blank=True, null=True)
    soil_depth = models.CharField(max_length=50, blank=True, null=True)
    plant_height = models.CharField(max_length=50, blank=True, null=True)
    suitable_for_indoor_growing = models.BooleanField(default=True, null=True)
    suitable_for_outdoor_growing = models.BooleanField(default=True, null=True)
    suitable_for_pot_culture = models.BooleanField(default=True, null=True)
    hardiness_index = models.CharField(max_length=70, choices=HARDINESS.choices, default=HARDINESS.NONE, blank=True, null=True)
    no_of_plants_per_meter = models.CharField(max_length=50, blank=True, null=True)
    no_of_plants_per_square_meter = models.CharField(max_length=50, blank=True, null=True)
    min_temperature = models.CharField(max_length=20, blank=True, null=True)
    max_temperature = models.CharField(max_length=20, blank=True, null=True)
    time_to_transplant = models.CharField(max_length=50, blank=True, null=True)

    def __str__(self):
        return self.name```
</div>
</div>
</p>
<p>Here is Plant associated model :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>from django.db import models
from apps.perma_plants.models import Plant

class LnkPlantPlant(models.Model):
    class MAGNET_CHOICES(models.TextChoices):
        NONE = None
        IDEAL = 'ideal',
        GOOD = 'good',
        MEDIOCRE = 'mediocre',
        BAD = 'bad'

    plant = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant')
    plant_associated = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant_associated')
    link = models.CharField(max_length=10, choices=MAGNET_CHOICES.choices, default=MAGNET_CHOICES.NONE, blank=True, null=True)
    description = models.CharField(max_length=255, blank=True, null=True)</code>```

Thanks

答:
According to Jeff's answer, it can be done manually:</p>
```<code># using Model.object.create is a shortcut to instantiating, then calling save()
linkplt = LnkPlantPlant.objects.create(link='something', description='something')
garlic = Plant.objects.create(name='garlic')
basil = Plant.objects.create(name='basil')

linkplt.plant.add(garlic)
linkplt.plant_associated.add(basil)

linkplt.plant.add(basil)
linkplt.plant_associated.add(garlic)
</code>```

Body:
I have a model with all the info of a plant and another model which consists of creating links between these plants. But when I create a link between two plants for example I create an ideal link between basil and garlic in the Django admin, I don't have the symmetrical link between garlic and basil. Should we add symmetrical = true in the model?

Here is Plant model :

from django.db import models

class Plant(models.Model):
    class LEVEL(models.TextChoices):
        NONE = None
        EASY = 'easy',
        MEDIUM = 'medium',
        HARD = 'hard'

    class SUNSHINE(models.TextChoices):
        NONE = None
        FULL_SUN = 'full_sun',
        SHADOW = 'shadow',
        SUNNY = 'sunny',
        MODERATE = 'moderate'

    class IRRIGATION(models.TextChoices):
        NONE = None
        WET = 'wet',
        WEAKLY = 'weakly',
        MOIST = 'keep_soil_moist',
        GENEROUSLY = 'generously',
        SLIGHTLY_DAMP = 'slightly_damp',
        COVERED_WITH_WATER = 'covered_with_water'

    class SOIL_N(models.TextChoices):
        NONE = None
        HUMUS = 'humus',
        LIGHT = 'light',
        CLAY = 'clay',
        DRAINED = 'drained',
        ALL_TYPE = 'all_types'

    class SOIL_T(models.TextChoices):
        NONE = None
        POOR = 'poor',
        MEDIUM_SOIL = 'medium_soil',
        RICH = 'rich',
        FERTILE = 'fertile',
        DRAINED = 'drained',
        ADD_PEBBLES = 'add_pebbles',
        ALL_TYPE = 'all_types'

    class HARDINESS(models.TextChoices):
        NONE = None
        VERY_FRAGILE = 'very_fragile',
        FRAGILE = 'fragile',
        RUSTIC = 'rustic',
        MEDIUM = 'medium',
        SUPPORT_FRESHNESS = 'support_freshness',
        # COLD_RESISTANT = 'cold_resistant'

    name = models.CharField(max_length=150, unique=True)
    family = models.ForeignKey('perma_families.Family', on_delete=models.CASCADE, default=3)
    category = models.ForeignKey('perma_plant_categories.PlantCategory', on_delete=models.CASCADE, default=1)
    facility_rate = models.CharField(max_length=50, choices=LEVEL.choices, default=LEVEL.NONE, blank=True, null=True)
    seedling_depth = models.CharField(max_length=50, blank=True, null=True)
    seedling_distance = models.CharField(max_length=50, blank=True, null=True)
    row_spacing = models.CharField(max_length=50, blank=True, null=True)
    sunshine_index = models.CharField(max_length=50, choices=SUNSHINE.choices, default=SUNSHINE.NONE, blank=True, null=True)
    irrigation_index = models.CharField(max_length=50, choices=IRRIGATION.choices, default=IRRIGATION.NONE, blank=True, null=True)
    soil_nature = models.CharField(max_length=50, choices=SOIL_N.choices, default=SOIL_N.NONE, blank=True, null=True)
    soil_type = models.CharField(max_length=50, choices=SOIL_T.choices, default=SOIL_T.NONE, blank=True, null=True)
    fertilizer_type = models.CharField(max_length=50, blank=True, null=True)
    acidity_index = models.CharField(max_length=50, blank=True, null=True)
    days_before_sprouting = models.CharField(max_length=50, blank=True, null=True)
    average_harvest_time = models.CharField(max_length=50, blank=True, null=True)
    soil_depth = models.CharField(max_length=50, blank=True, null=True)
    plant_height = models.CharField(max_length=50, blank=True, null=True)
    suitable_for_indoor_growing = models.BooleanField(default=True, null=True)
    suitable_for_outdoor_growing = models.BooleanField(default=True, null=True)
    suitable_for_pot_culture = models.BooleanField(default=True, null=True)
    hardiness_index = models.CharField(max_length=70, choices=HARDINESS.choices, default=HARDINESS.NONE, blank=True, null=True)
    no_of_plants_per_meter = models.CharField(max_length=50, blank=True, null=True)
    no_of_plants_per_square_meter = models.CharField(max_length=50, blank=True, null=True)
    min_temperature = models.CharField(max_length=20, blank=True, null=True)
    max_temperature = models.CharField(max_length=20, blank=True, null=True)
    time_to_transplant = models.CharField(max_length=50, blank=True, null=True)

    def __str__(self):
        return self.name

Here is Plant associated model :

from django.db import models
from apps.perma_plants.models import Plant

class LnkPlantPlant(models.Model):
    class MAGNET_CHOICES(models.TextChoices):
        NONE = None
        IDEAL = 'ideal',
        GOOD = 'good',
        MEDIOCRE = 'mediocre',
        BAD = 'bad'

    plant = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant')
    plant_associated = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant_associated')
    link = models.CharField(max_length=10, choices=MAGNET_CHOICES.choices, default=MAGNET_CHOICES.NONE, blank=True, null=True)
    description = models.CharField(max_length=255, blank=True, null=True)

Thanks

Body:
According to Jeff's answer, it can be done manually:

# using Model.object.create is a shortcut to instantiating, then calling save()
linkplt = LnkPlantPlant.objects.create(link='something', description='something')
garlic = Plant.objects.create(name='garlic')
basil = Plant.objects.create(name='basil')

linkplt.plant.add(garlic)
linkplt.plant_associated.add(basil)

linkplt.plant.add(basil)
linkplt.plant_associated.add(garlic)


问:
Jenkins Scan Multibranch Pipeline stopped detecting develop branch
I am using an organization folder in Jenkins to discover all repositories that contain a Jenkinsfile.

It had been working fine until recently. At some point, the develop branch of one of the repositories was removed. That branch does exist and contains a valid Jenkinsfile.

When I rescan the project the log shows how it examines the branch but says nothing about finding or not finding the Jenkinsfile:

```<code>Looking up myorg/myrepo for branches
Checking branch develop from myorg/myrepo
Checking branch master from myorg/myrepo
      ‘Jenkinsfile’ found
    Met criteria
...
</code>```

What could be the problem here? Any advice about how to troubleshoot this?

I've tried the usual solutions: delete the branch, create new ones that are detected without any problem, recreate the develop branch...

答:
For anyone who is sure that Jenkinsfile has no errors, and still looking for a solution to this, following would be good place to start with.

Ensure the below options are enabled:
In SCM configuration > Branch Sources > Discover branches
In SCM configuration > Branch Sources > Filter by name (with wildcards) > Include > <branch_name>

Body:
I am using an organization folder in Jenkins to discover all repositories that contain a Jenkinsfile.

It had been working fine until recently. At some point, the develop branch of one of the repositories was removed. That branch does exist and contains a valid Jenkinsfile.

When I rescan the project the log shows how it examines the branch but says nothing about finding or not finding the Jenkinsfile:

Looking up myorg/myrepo for branches
Checking branch develop from myorg/myrepo
Checking branch master from myorg/myrepo
      ‘Jenkinsfile’ found
    Met criteria
...

What could be the problem here? Any advice about how to troubleshoot this?

I've tried the usual solutions: delete the branch, create new ones that are detected without any problem, recreate the develop branch...


问:
How to convert all Series values of a Dataframe from timedelta to minutes
I have this dataframe where every value's type is timedelta:

And I want to transform all values to minutes, but when coding:

```<code>df['time'] = df['time'].seconds/60
</code>```

I get the following error:

```<code>AttributeError: 'Series' object has no attribute 'seconds'
</code>```

How can I transform every value of the column in a simple way?

Thanks.

答:
Use .dt.total_seconds() instead of .seconds:

```<code>df['time'] = df['time'].dt.total_seconds() / 60
</code>```

Body:
I have this dataframe where every value's type is timedelta:

And I want to transform all values to minutes, but when coding:

df['time'] = df['time'].seconds/60

I get the following error:

AttributeError: 'Series' object has no attribute 'seconds'

How can I transform every value of the column in a simple way?

Thanks.

Body:
Use .dt.total_seconds() instead of .seconds:

df['time'] = df['time'].dt.total_seconds() / 60


问:
Using pyaudio to build a Metronome; wrong timing
So I wanted to build a metronome and decided to use pyaudio. I know there are other ways but I want to make something else later with that.

Thats my Code so far:

```<code>
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
def play_audio(filename):
    wf=wave.open(filename,"rb")
    p=pyaudio.PyAudio()
    stream_play=p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)
    data = wf.readframes(CHUNK)
    while True:
        if data != '':
            stream_play.write(data)
            data = wf.readframes(CHUNK)
        if data == b"":
            break
    stream_play.stop_stream()
    stream_play.close()
    p.terminate()

def metronom(bpm):
    while True:
        play_callback(beep)
        time.sleep(60/bpm)

beep="beep-07a.wav"

</code>```

I thought it worked out, but unfortunately the timing is completely off. I also tried it with a callback function, but had the same wrong timing.

THE SOLUTION NOW LOOKS LIKE THIS

```<code>def metronom(bpm):
    while True:
        startTime = time.time()
        play_callback(beep)
        endTime=time.time()-startTime
        time.sleep(60/bpm-endTime)
</code>```

答:
If you metronome  just need a tick sound and if you are on windows OS you can easily use Winsound to create a metronome,
try following.</p>
```<code>import winsound
frequency = 25  # Set Frequency To 25 Hertz
duration = 5*1000  # Set Duration To 5000 ms or 5 second
winsound.Beep(frequency, duration)
</code>```

Body:
So I wanted to build a metronome and decided to use pyaudio. I know there are other ways but I want to make something else later with that.

Thats my Code so far:

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
def play_audio(filename):
    wf=wave.open(filename,"rb")
    p=pyaudio.PyAudio()
    stream_play=p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)
    data = wf.readframes(CHUNK)
    while True:
        if data != '':
            stream_play.write(data)
            data = wf.readframes(CHUNK)
        if data == b"":
            break
    stream_play.stop_stream()
    stream_play.close()
    p.terminate()

def metronom(bpm):
    while True:
        play_callback(beep)
        time.sleep(60/bpm)

beep="beep-07a.wav"

I thought it worked out, but unfortunately the timing is completely off. I also tried it with a callback function, but had the same wrong timing.

THE SOLUTION NOW LOOKS LIKE THIS

def metronom(bpm):
    while True:
        startTime = time.time()
        play_callback(beep)
        endTime=time.time()-startTime
        time.sleep(60/bpm-endTime)

Body:
If you metronome  just need a tick sound and if you are on windows OS you can easily use Winsound to create a metronome,
try following.

import winsound
frequency = 25  # Set Frequency To 25 Hertz
duration = 5*1000  # Set Duration To 5000 ms or 5 second
winsound.Beep(frequency, duration)


问:
What modification to my spec file accomplishes the same thing as adding the command line option --onefile when using pyinstaller?
I have a simple script, hello_world.py, and want to create a Windows 10 executable with the aid of Pyinstaller. I'm using Python 3.9, on a Mac (11.6.1) with a Windows 10 virtual machine along with the most recent version of Pyinstaller.

Of course, the simplest way to create the .exe as a single file is to type pyinstaller hello_world.py --onefile at the command line. This produces a folder, dist, which contains just the .exe itself.

However, for my more complicated application, I'll need to include many datas and hidden imports, which I do by modifying the spec file produced by typing pyinstaller hello_world and edit accordingly. Here's a simple example of a modified spec file for hello_world.py:

```<code>block_cipher = None

data=[('Desktop/my_image.png', '.')]

a = Analysis(['hello_world.py'],
         pathex=[],
         binaries=[],
         datas=[],
         hiddenimports=[networkx],
         hookspath=[],
         hooksconfig={},
         runtime_hooks=[],
         excludes=[],
         win_no_prefer_redirects=False,
         win_private_assemblies=False,
         cipher=block_cipher,
         noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
         cipher=block_cipher)

exe = EXE(pyz,
      a.scripts,
      [],
      exclude_binaries=True,
      name='hello_world',
      debug=False,
      bootloader_ignore_signals=False,
      strip=False,
      upx=True,
      console=True,
      disable_windowed_traceback=False,
      target_arch=None,
      codesign_identity=None,
      entitlements_file=None )
coll = COLLECT(exe,
           a.binaries,
           a.zipfiles,
           a.datas,
           strip=False,
           upx=True,
           upx_exclude=[],
           name='hello_world')
</code>```

This is the spec file produced by first typing pyinstaller hello_world.py at the command line and then editing the resulting spec file by adding an image to the data and a single hidden import. (I chose networkx, not that it matters.)

Now typing pyinstaller produces a dist folder which contains another folder, hello_world as opposed to a dist folder containing just hello_world.exe. This isn't what I want.

I realize I can include other options at the command line to add data and hidden imports, but my actual application contains so many of these things that it's more efficient to work with the spec file.

So the ultimate question is what modification to my spec file achieves the same outcome as adding the --onefile option at the command line?

答: Thanks to the assistance of E.Fahlgren on the Pyinstaller"s Google Mailing list, I learned that the problem is resolved if one deletes coll and adds exclude_binaries=False to exe.

Body:
I have a simple script, hello_world.py, and want to create a Windows 10 executable with the aid of Pyinstaller. I'm using Python 3.9, on a Mac (11.6.1) with a Windows 10 virtual machine along with the most recent version of Pyinstaller.

Of course, the simplest way to create the .exe as a single file is to type pyinstaller hello_world.py --onefile at the command line. This produces a folder, dist, which contains just the .exe itself.

However, for my more complicated application, I'll need to include many datas and hidden imports, which I do by modifying the spec file produced by typing pyinstaller hello_world and edit accordingly. Here's a simple example of a modified spec file for hello_world.py:

block_cipher = None

data=[('Desktop/my_image.png', '.')]

a = Analysis(['hello_world.py'],
         pathex=[],
         binaries=[],
         datas=[],
         hiddenimports=[networkx],
         hookspath=[],
         hooksconfig={},
         runtime_hooks=[],
         excludes=[],
         win_no_prefer_redirects=False,
         win_private_assemblies=False,
         cipher=block_cipher,
         noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
         cipher=block_cipher)

exe = EXE(pyz,
      a.scripts,
      [],
      exclude_binaries=True,
      name='hello_world',
      debug=False,
      bootloader_ignore_signals=False,
      strip=False,
      upx=True,
      console=True,
      disable_windowed_traceback=False,
      target_arch=None,
      codesign_identity=None,
      entitlements_file=None )
coll = COLLECT(exe,
           a.binaries,
           a.zipfiles,
           a.datas,
           strip=False,
           upx=True,
           upx_exclude=[],
           name='hello_world')

This is the spec file produced by first typing pyinstaller hello_world.py at the command line and then editing the resulting spec file by adding an image to the data and a single hidden import. (I chose networkx, not that it matters.)

Now typing pyinstaller produces a dist folder which contains another folder, hello_world as opposed to a dist folder containing just hello_world.exe. This isn't what I want.

I realize I can include other options at the command line to add data and hidden imports, but my actual application contains so many of these things that it's more efficient to work with the spec file.

So the ultimate question is what modification to my spec file achieves the same outcome as adding the --onefile option at the command line?


答:
tidyverse

df <- data.frame(
  stringsAsFactors = FALSE,
              town = c("a", "a", "a", "b", "b", "b", "c", "c", "c"),
             party = c("A", "B", "C", "A", "B", "C", "A", "B", "C"),
             votes = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L)
)

library(tidyverse)
df %>%
  group_by(town, grp_party = party %in% c("A", "B")) %>%
  mutate(new_party = paste0(party, collapse = ""), new_votes = sum(votes)) %>%
  ungroup() %>%
  select(-grp_party)
#> # A tibble: 9 x 5
#>   town  party votes new_party new_votes
#>   <chr> <chr> <int> <chr>         <int>
#> 1 a     A         1 AB                3
#> 2 a     B         2 AB                3
#> 3 a     C         3 C                 3
#> 4 b     A         4 AB                9
#> 5 b     B         5 AB                9
#> 6 b     C         6 C                 6
#> 7 c     A         7 AB               15
#> 8 c     B         8 AB               15
#> 9 c     C         9 C                 9
```
<p><sup>Created on 2022-02-08 by the reprex package (v2.0.1)</sup></p>
<p><strong>data.table</strong></p>
<pre class="lang-r prettyprint-override"><code>library(data.table)
setDT(df)[, votes:= lapply(.SD, sum), by = list(town, party %in% c("A", "B"))][]
#>    town party votes
#> 1:    a     A     3
#> 2:    a     B     3
#> 3:    a     C     3
#> 4:    b     A     9
#> 5:    b     B     9
#> 6:    b     C     6
#> 7:    c     A    15
#> 8:    c     B    15
#> 9:    c     C     9
</code>```

Created on 2022-02-08 by the reprex package (v2.0.1)

Title: summing up values in R dataframe without aggregation

Body:
tidyverse

df <- data.frame(
  stringsAsFactors = FALSE,
              town = c("a", "a", "a", "b", "b", "b", "c", "c", "c"),
             party = c("A", "B", "C", "A", "B", "C", "A", "B", "C"),
             votes = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L)
)

library(tidyverse)
df %>%
  group_by(town, grp_party = party %in% c("A", "B")) %>%
  mutate(new_party = paste0(party, collapse = ""), new_votes = sum(votes)) %>%
  ungroup() %>%
  select(-grp_party)
#> # A tibble: 9 x 5
#>   town  party votes new_party new_votes
#>   <chr> <chr> <int> <chr>         <int>
#> 1 a     A         1 AB                3
#> 2 a     B         2 AB                3
#> 3 a     C         3 C                 3
#> 4 b     A         4 AB                9
#> 5 b     B         5 AB                9
#> 6 b     C         6 C                 6
#> 7 c     A         7 AB               15
#> 8 c     B         8 AB               15
#> 9 c     C         9 C                 9

Created on 2022-02-08 by the reprex package (v2.0.1)

data.table

library(data.table)
setDT(df)[, votes:= lapply(.SD, sum), by = list(town, party %in% c("A", "B"))][]
#>    town party votes
#> 1:    a     A     3
#> 2:    a     B     3
#> 3:    a     C     3
#> 4:    b     A     9
#> 5:    b     B     9
#> 6:    b     C     6
#> 7:    c     A    15
#> 8:    c     B    15
#> 9:    c     C     9

Created on 2022-02-08 by the reprex package (v2.0.1)


问:
Is there possibility to compress audio and video file in android programmatically?
As I record the video file for 1min it take 3mb of size as i want to post this file to server it is taking more time.So I need to decrease the time by compassing the recorded video file and send it to server.Is there possibility to compress the video file programmatically.
Thanks in advance.
Teja.  </p>

答:
Note that simply compressing it with some zip-algorithm (relatively easy to do in Java) wouldn't help you much. Try compressing the file yourself. (If it did make the file smaller, it would most likely already be a part of the video-file format, wouldn't it :-)

If you want to compress the video, you have to re-encode it with a lower bit-rate / lower resolution or something similar.


问:
verfiy password for a PKCS#12 file
In my php program I try to verify the password for a PKCS#12 file (.p12/.pfx) with this OpenSSL command :

```<code>openssl pkcs12 -info -in myDigitalID.p12 -noout -passin pass:mypassword
</code>```

output:

```<code>MAC: sha1, Iteration 2048
MAC length: 20, salt length: 8
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048
Error outputting keys and certificates
C4500000:error:0308010C:digital envelope routines:inner_evp_generic_fetch:unsupported:crypto\evp\evp_fetch.c:349:Global default library context, Algorithm (RC2-40-CBC : 0), Properties ()
</code>```

But I don't understand why it doesn't work! please can any one help?
thanks

答:
If the command used to work in previous OpenSSL version try the following

Failing command:

```<code>openssl pkcs12 -info -in myDigitalID.p12 -noout -passin pass:mypassword
</code>```

Failing command output:

```<code>MAC: sha1, Iteration 2000
MAC length: 20, salt length: 8
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2000
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2000
Error outputting keys and certificates
0C670000:error:0308010C:digital envelope routines:inner_evp_generic_fetch:unsupported:crypto\evp\evp_fetch.c:349:Global default library context, Algorithm (RC2-40-CBC : 0), Properties ()
</code>```

Ensure you have the legacy library (file named legacy*., e.g. legacy-x64.dll). Instead of configuring environment variables it may be easier to just copy the library as legacy. (e.g. legacy.dll) in both the libraries path and the path containing openssl executable.

Then try command:

```<code>openssl pkcs12 -info -in myDigitalID.p12 -noout -passin pass:mypassword -legacy -provider-path "C:\path\to\legacy_dir" -provider default
</code>```

This time it should work and show something like this:

```<code>MAC: sha1, Iteration 2000
MAC length: 20, salt length: 8
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2000
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2000
Certificate bag
</code>```

Title: verfiy password for a PKCS#12 file

Body:
In my php program I try to verify the password for a PKCS#12 file (.p12/.pfx) with this OpenSSL command :

openssl pkcs12 -info -in myDigitalID.p12 -noout -passin pass:mypassword

output:

MAC: sha1, Iteration 2048
MAC length: 20, salt length: 8
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048
Error outputting keys and certificates
C4500000:error:0308010C:digital envelope routines:inner_evp_generic_fetch:unsupported:crypto\evp\evp_fetch.c:349:Global default library context, Algorithm (RC2-40-CBC : 0), Properties ()

But I don't understand why it doesn't work! please can any one help?
thanks

Body:
If the command used to work in previous OpenSSL version try the following

Failing command:

openssl pkcs12 -info -in myDigitalID.p12 -noout -passin pass:mypassword

Failing command output:

MAC: sha1, Iteration 2000
MAC length: 20, salt length: 8
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2000
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2000
Error outputting keys and certificates
0C670000:error:0308010C:digital envelope routines:inner_evp_generic_fetch:unsupported:crypto\evp\evp_fetch.c:349:Global default library context, Algorithm (RC2-40-CBC : 0), Properties ()

Ensure you have the legacy library (file named legacy*., e.g. legacy-x64.dll). Instead of configuring environment variables it may be easier to just copy the library as legacy. (e.g. legacy.dll) in both the libraries path and the path containing openssl executable.

Then try command:

openssl pkcs12 -info -in myDigitalID.p12 -noout -passin pass:mypassword -legacy -provider-path "C:\path\to\legacy_dir" -provider default

This time it should work and show something like this:

MAC: sha1, Iteration 2000
MAC length: 20, salt length: 8
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2000
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2000
Certificate bag


答:
I'm interpreting your pseudo-code as wanting to only update party "A" to the sum of both "A" and "B"'s votes.

base R

do.call(rbind, by(df, df$town,
  function(Z) {
    ind <- Z$party %in% c("A", "B")
    Z$votes[Z$party == "A"] <- sum(Z$votes[ind])
    Z
  }
))
#     town party votes
# a.1    a     A     3
# a.2    a     B     2
# a.3    a     C     3
# b.4    b     A     9
# b.5    b     B     5
# b.6    b     C     6
# c.7    c     A    15
# c.8    c     B     8
# c.9    c     C     9
```
<h2>dplyr</h2>
<pre class="lang-r prettyprint-override"><code>library(dplyr)
df %>%
  group_by(town) %>%
  mutate(
    votes = if_else(party == "A", sum(votes[party %in% c("A", "B")]), votes)
  ) %>%
  ungroup()
# # A tibble: 9 x 3
#   town  party votes
#   <chr> <chr> <int>
# 1 a     A         3
# 2 a     B         2
# 3 a     C         3
# 4 b     A         9
# 5 b     B         5
# 6 b     C         6
# 7 c     A        15
# 8 c     B         8
# 9 c     C         9
</code>```

data.table

library(data.table)
DT <- as.data.table(df) # normally setDT(df) is canonical
DT[, votes := fifelse(party == "A", sum(votes[party %in% c("A", "B")]), votes),
    by = .(town)]
#      town  party votes
#    <char> <char> <int>
# 1:      a      A     3
# 2:      a      B     2
# 3:      a      C     3
# 4:      b      A     9
# 5:      b      B     5
# 6:      b      C     6
# 7:      c      A    15
# 8:      c      B     8
# 9:      c      C     9
```

Body:
How can I add up row values in a dataframe based on conditions without having to aggregate the whole table?

I have this df:

  town party votes
1    a     A     1
2    a     B     2
3    a     C     3
4    b     A     4
5    b     B     5
6    b     C     6
7    c     A     7
8    c     B     8
9    c     C     9

I would like to add the votes of one party to those of another by town, without touching the values of the third one.

Basically to run df$votes[df$party == A] = df$votes[df$party == A] + df$votes[df$party == B] for each category of df$town

Body:
I'm interpreting your pseudo-code as wanting to only update party "A" to the sum of both "A" and "B"'s votes.

base R

do.call(rbind, by(df, df$town,
  function(Z) {
    ind <- Z$party %in% c("A", "B")
    Z$votes[Z$party == "A"] <- sum(Z$votes[ind])
    Z
  }
))
#     town party votes
# a.1    a     A     3
# a.2    a     B     2
# a.3    a     C     3
# b.4    b     A     9
# b.5    b     B     5
# b.6    b     C     6
# c.7    c     A    15
# c.8    c     B     8
# c.9    c     C     9

dplyr

library(dplyr)
df %>%
  group_by(town) %>%
  mutate(
    votes = if_else(party == "A", sum(votes[party %in% c("A", "B")]), votes)
  ) %>%
  ungroup()
# # A tibble: 9 x 3
#   town  party votes
#   <chr> <chr> <int>
# 1 a     A         3
# 2 a     B         2
# 3 a     C         3
# 4 b     A         9
# 5 b     B         5
# 6 b     C         6
# 7 c     A        15
# 8 c     B         8
# 9 c     C         9

data.table

library(data.table)
DT <- as.data.table(df) # normally setDT(df) is canonical
DT[, votes := fifelse(party == "A", sum(votes[party %in% c("A", "B")]), votes),
    by = .(town)]
#      town  party votes
#    <char> <char> <int>
# 1:      a      A     3
# 2:      a      B     2
# 3:      a      C     3
# 4:      b      A     9
# 5:      b      B     5
# 6:      b      C     6
# 7:      c      A    15
# 8:      c      B     8
# 9:      c      C     9


问:
Angular 13 package/library throws error "moment is not a function" when imported into a Angular 13 project
Im upgrading a private angular library/package (my-lib) so i can migrate all other projects, but when imported into a project one of the services uses moment and throws an error:
"ERROR TypeError: moment is not a function"

The library works in dev mode and the build and publish are ok and even when imported into a project all components and resources load fine and no errors are displayed, dependencies are download but seeams that some of the 3rd party dependencies are not known by "my-lib" after imported.

Even in the project i can import moment and use it but "my-lib" in node_modules dont see that package.

some of the files in "my-lib"

service.ts

```<code>import * as moment_ from 'moment';

const moment = moment_;
...

moment(value).format('YYYY-MM-DD')  ----> line that throws the error
</code>```

already tried

```<code>import moment from 'moment';
</code>```

and the "allowSyntheticDefaultImports" flag in tsconfig

package.json

```<code>"dependencies": {
    ...
    "moment": "~2.29.1",
    ...
},
"devDependencies": {
    "@angular-builders/custom-webpack": "~13.0.0",
    "@angular-devkit/build-angular": "~13.1.1",
    "@angular-eslint/builder": "~13.0.1",
    "@angular-eslint/eslint-plugin": "~13.0.1",
    "@angular-eslint/eslint-plugin-template": "~13.0.1",
    "@angular-eslint/schematics": "~13.0.1",
    "@angular-eslint/template-parser": "~13.0.1",
    "@angular/animations": "~13.1.0",
    "@angular/cli": "~13.1.1",
    "@angular/common": "~13.1.0",
    "@angular/compiler": "~13.1.0",
    "@angular/compiler-cli": "~13.1.0",
    "@angular/core": "~13.1.0",
    "@angular/forms": "~13.1.0",
    "@angular/language-service": "~13.1.0",
    "@angular/platform-browser": "~13.1.0",
    "@angular/platform-browser-dynamic": "~13.1.0",
    "@angular/router": "~13.1.0",
    "eslint": "^8.2.0",
    "ng-packagr": "~13.1.1",
    "rxjs": "~7.4.0",
    "ts-node": "~10.4.0",
    "tslib": "^2.3.0",
    "typescript": "~4.5.2",
    "zone.js": "~0.11.4"
  }
</code>```

tsconfig.ts

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitReturns": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2020",
    "module": "es2020",
    "typeRoots": [
      "node_modules/@types"
    ],
    "types": [
      "node",
      "cypress",
      "cypress-xpath",
      "cypress-wait-until"
    ],
    "lib": [
      "es2020",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "compilationMode": "partial",
    "enableResourceInlining": true,
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true,
    "types": [
      "node",
      "cypress",
      "cypress-xpath",
      "cypress-wait-until"
    ]
  }
}
</code>```

ng-package.json

```<code>{
  "$schema": "./node_modules/ng-packagr/package.schema.json",
  "lib": {
    "entryFile": "./src/my-lib/public_api.ts",
    "cssUrl": "inline"
  },
  "allowedNonPeerDependencies": ["."]
}
</code>```

this is a update from angular 9 to 13 and probably im missing something but cannot find examples or documentation that explains the change in behavior.

ps: The "require" function has the same behavior

```<code>const a = require('assets/test.png');   --> throws error require is not a function when my-lib is imported into a project and tries to run the this line
</code>```

If you need more details or have some suggestions i will apreciate.

Thanks in advance

答:
I had this issue trying to run moment in stackblitz. Setting "esModuleInterop":true in compilerOptions and using the import moment from 'moment' syntax fixed it for me. Let me know if that works.

Enabling esmoduleInterop also enables allowSyntheticDefaultImports.

More info: https://www.typescriptlang.org/tsconfig#esModuleInterop

Body:
Im upgrading a private angular library/package (my-lib) so i can migrate all other projects, but when imported into a project one of the services uses moment and throws an error:
"ERROR TypeError: moment is not a function"

The library works in dev mode and the build and publish are ok and even when imported into a project all components and resources load fine and no errors are displayed, dependencies are download but seeams that some of the 3rd party dependencies are not known by "my-lib" after imported.

Even in the project i can import moment and use it but "my-lib" in node_modules dont see that package.

some of the files in "my-lib"

service.ts

import * as moment_ from 'moment';

const moment = moment_;
...

moment(value).format('YYYY-MM-DD')  ----> line that throws the error

already tried

import moment from 'moment';

and the "allowSyntheticDefaultImports" flag in tsconfig

package.json

"dependencies": {
    ...
    "moment": "~2.29.1",
    ...
},
"devDependencies": {
    "@angular-builders/custom-webpack": "~13.0.0",
    "@angular-devkit/build-angular": "~13.1.1",
    "@angular-eslint/builder": "~13.0.1",
    "@angular-eslint/eslint-plugin": "~13.0.1",
    "@angular-eslint/eslint-plugin-template": "~13.0.1",
    "@angular-eslint/schematics": "~13.0.1",
    "@angular-eslint/template-parser": "~13.0.1",
    "@angular/animations": "~13.1.0",
    "@angular/cli": "~13.1.1",
    "@angular/common": "~13.1.0",
    "@angular/compiler": "~13.1.0",
    "@angular/compiler-cli": "~13.1.0",
    "@angular/core": "~13.1.0",
    "@angular/forms": "~13.1.0",
    "@angular/language-service": "~13.1.0",
    "@angular/platform-browser": "~13.1.0",
    "@angular/platform-browser-dynamic": "~13.1.0",
    "@angular/router": "~13.1.0",
    "eslint": "^8.2.0",
    "ng-packagr": "~13.1.1",
    "rxjs": "~7.4.0",
    "ts-node": "~10.4.0",
    "tslib": "^2.3.0",
    "typescript": "~4.5.2",
    "zone.js": "~0.11.4"
  }

tsconfig.ts

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitReturns": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2020",
    "module": "es2020",
    "typeRoots": [
      "node_modules/@types"
    ],
    "types": [
      "node",
      "cypress",
      "cypress-xpath",
      "cypress-wait-until"
    ],
    "lib": [
      "es2020",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "compilationMode": "partial",
    "enableResourceInlining": true,
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true,
    "types": [
      "node",
      "cypress",
      "cypress-xpath",
      "cypress-wait-until"
    ]
  }
}

ng-package.json

{
  "$schema": "./node_modules/ng-packagr/package.schema.json",
  "lib": {
    "entryFile": "./src/my-lib/public_api.ts",
    "cssUrl": "inline"
  },
  "allowedNonPeerDependencies": ["."]
}

this is a update from angular 9 to 13 and probably im missing something but cannot find examples or documentation that explains the change in behavior.

ps: The "require" function has the same behavior

const a = require('assets/test.png');   --> throws error require is not a function when my-lib is imported into a project and tries to run the this line

If you need more details or have some suggestions i will apreciate.

Thanks in advance


问:
Could managed code (specifically .NET) ever become 'unmanaged'?
Recently I was talking with a friend of mine who had started a C++ class a couple months ago (his first exposure to programming). We got onto the topic of C# and .NET generally, and he made the point to me that he felt it was 'doomed' for all of the commonly-cited issues (low speed, breakable bytecode, etc). I agreed with him on all those issues, but I held back in saying it was doomed, only because I felt that, in time, languages like C# could instead become native code (if Microsoft so chose to change the implementation of .NET from a bytecode, JIT runtime environemnent to one which compiles directly to native code like your C++ program does).

My question is, am I out to lunch here? I mean, it may take a lot of work (and may break too many things), but there isn't some type of magical barrier which prevents C# code from being compiled natively (if one wanted to do it), right? There was a time where C++ was considered a very high-level language (which it still is, but not as much as in the past) yet now it's the bedrock (along with C) for Microsoft's native APIs. The idea that .NET could one day be on the same level as C++ in that respect seems only to be a matter of time and effort to me, not some fundamental flaw in the design of the language.

EDIT: I should add that if native compilation of .NET is possible, why does Microsoft choose not to go that route? Why have they chosen the JIT bytecode path?

答:
dude, fyi, you can always compile your c# assemblies into native image using ngen.exe

and are you suggesting .net is flawed design? it was .net which brought back ms back into the game from their crappy vb 5, vb 6, com days. it was one of their biggest bets

java does the same stuff - so are you suggesting java too is a mistake?

reg. big vendors - please note .net has been hugely hugely successful across companies of all sizes (except for those open source guys - nothing wrong with that). all these companies have made significant amount of investments into the .net framework.

and to compare c# speed with c++ is a crazy idea according to me. does c++ give u managed environment along with a world class powerful framework?

and you can always obfuscate your assemblies if you are so paranoid about decompilation

its not about c++ v/s c#, managed v/s unmanaged. both are equally good and equally powerful in their own domains

OwnerDisplayName: GRB

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: Raj


问:
How to preview git-pull?
Is it even possible?

Basically, there's a remote repository from which I pull using just:

```<code>git pull
</code>```

Now, I'd like to preview what this pull would change (a diff) without touching anything on my side. The reason is that thing I'm pulling might not be "good" and I want someone else to fix it before making my repository "dirty".

答:
I created a custom git alias to do that for me:

```<code>alias.changes=!git log --name-status HEAD..
</code>```

with that you can do this:

```<code>$git fetch
$git changes origin
</code>```

This will get you a nice and easy way to preview changes before doing a merge.

OwnerDisplayName: Milan Babuskov

Title: How to preview git-pull?

Body:
Is it even possible?

Basically, there's a remote repository from which I pull using just:

git pull

Now, I'd like to preview what this pull would change (a diff) without touching anything on my side. The reason is that thing I'm pulling might not be "good" and I want someone else to fix it before making my repository "dirty".

LastEditorDisplayName: Milan Babuskov

Body:
I created a custom git alias to do that for me:

alias.changes=!git log --name-status HEAD..

with that you can do this:

$git fetch
$git changes origin

This will get you a nice and easy way to preview changes before doing a merge.


问:
Ransack Search Id and Strings Together
I am trying to search using Ransack but having issue when i am trying to search id and string together like

:id_or_title_or_user_username_cont

It produces the error

ActionView::Template::Error (PG::UndefinedFunction: ERROR:  operator does not exist: integer ~~* integer

I have also tried this

:id_eq_or_title_or_user_username_cont

it produces following error

undefined method `id_eq_or_title_or_user_username_cont' for Ransack::Search

What is the appropriate way of searching id and strings together using ransack other than custom predicates or with custom predicates ?

答:
Small update as the answers above correct, but I found they had the side effect of causing normal results (e.g full list, no search) to be Ordered by the string value of ID, so - 1,10,11,12...etc...2,20,21...3,30 etc instead of 1,2,3,4...

So combining both ideas above, can search by ID but still sort by Int ID

In the Model create a stringified version of ID for ransack

```<code>ransacker :id_as_str do
  Arel.sql("to_char(\"#{self.table_name}\".\"id\", '99999999')")
end
</code>```

And in the form

```<code><%= f.search_field :id_as_str_or_some_other_stuff_cont, placeholder: "Search..." %>
</code>```

Title: Ransack Search Id and Strings Together

Body:
Small update as the answers above correct, but I found they had the side effect of causing normal results (e.g full list, no search) to be Ordered by the string value of ID, so - 1,10,11,12...etc...2,20,21...3,30 etc instead of 1,2,3,4...

So combining both ideas above, can search by ID but still sort by Int ID

In the Model create a stringified version of ID for ransack

ransacker :id_as_str do
  Arel.sql("to_char(\"#{self.table_name}\".\"id\", '99999999')")
end

And in the form

<%= f.search_field :id_as_str_or_some_other_stuff_cont, placeholder: "Search..." %>


问:
FluXCD Helm deployment from Azure ACR - no chart name found error
I am attempting to deploy a Helm chart to AKS using FluxCD. The chart has been pushed to Azure ACR using the Helm cli - "helm push ...". The chart is declared in the ACR as helm/release-services:0.1.0

I am receiving the following error after a Flux reconcile:

'chart pull error: failed to get chart version for remote reference:
no chart name found'

with helm-controller logs as follows

{"level":"info","ts":"2022-02-07T12:40:18.121Z","logger":"controller.helmrelease","msg":"HelmChart 'flux-system/release-services-test-release-services' is not ready","reconciler group":"helm.toolkit.fluxcd.io","reconciler kind":"HelmRelease","name":"release-services","namespace":"release-services-test"}
{"level":"info","ts":"2022-02-07T12:40:18.135Z","logger":"controller.helmrelease","msg":"reconcilation finished in 15.458307ms, next run in 5m0s","reconciler group":"helm.toolkit.fluxcd.io","reconciler kind":"HelmRelease","name":"release-services","namespace":"release-services-test"}

Below is the HelmChart resource in AKS:

```<code>apiVersion: source.toolkit.fluxcd.io/v1beta1
kind: HelmChart
metadata:
  creationTimestamp: "2022-02-07T07:30:16Z"
  finalizers:
  - finalizers.fluxcd.io
  generation: 1
  name: release-services-test-release-services
  namespace: flux-system
  resourceVersion: "105266699"
  selfLink: /apis/source.toolkit.fluxcd.io/v1beta1/namespaces/flux-system/helmcharts/release-services-test-release-services
  uid: e4820a70-8885-44a1-8dfd-0e2bf7256915
spec:
  chart: release-services
  interval: 5m0s
  reconcileStrategy: ChartVersion
  sourceRef:
    kind: HelmRepository
    name: psbombb-helm-acr-dev
  version: '>=0.1.0'
status:
  conditions:
  - lastTransitionTime: "2022-02-07T11:02:49Z"
    message: 'chart pull error: failed to get chart version for remote reference:
      no chart name found'
    reason: ChartPullFailed
    status: "False"
    type: Ready
  observedGeneration: 1
</code>```

and the HelmRelease is as follows

```<code>apiVersion: helm.toolkit.fluxcd.io/v2beta1
kind: HelmRelease
metadata:
  creationTimestamp: "2022-02-07T04:34:14Z"
  finalizers:
  - finalizers.fluxcd.io
  generation: 9
  labels:
    kustomize.toolkit.fluxcd.io/name: apps
    kustomize.toolkit.fluxcd.io/namespace: flux-system
  name: release-services
  namespace: release-services-test
  resourceVersion: "105341484"
  selfLink: /apis/helm.toolkit.fluxcd.io/v2beta1/namespaces/release-services-test/helmreleases/release-services
  uid: 6a6e5f5c-951d-4655-9c15-fa9fe7421a04
spec:
  chart:
    spec:
      chart: release-services
      reconcileStrategy: ChartVersion
      sourceRef:
        kind: HelmRepository
        name: psbombb-helm-acr-dev
        namespace: flux-system
      version: '>=0.1.0'
  install:
    remediation:
      retries: 3
  interval: 5m
  releaseName: release-services
  timeout: 12m
  values:
    image:
      name: release-services
      pullPolicy: IfNotPresent
      registry: <repository>.azurecr.io
      repository: <repository>.azurecr.io/helm/release-services
      tag: 0.1.0
    postgres:
      secret:
        create: false
        existingName: release-services-secrets
status:
  conditions:
  - lastTransitionTime: "2022-02-07T08:27:13Z"
    message: HelmChart 'flux-system/release-services-test-release-services' is not
      ready
    reason: ArtifactFailed
    status: "False"
    type: Ready
  failures: 50
  helmChart: flux-system/release-services-test-release-services
  observedGeneration: 9

</code>```

Is there anything I am missing that anyone can spot for me please?

Thank you kindly

答:
I think your issue is that the Azure Container Registry stores Helm Charts as OCI Artifacts.

The Flux source controller will pull the index.yaml from a HTTP Helm Chart repo to look for tags and this is not working with an OCI registry.

Here is the GitHub issue for this were you can see that the Flux guys will work on this as of now the OCI Feature is stable with Helm 3.8.0.

Body:
I am attempting to deploy a Helm chart to AKS using FluxCD. The chart has been pushed to Azure ACR using the Helm cli - "helm push ...". The chart is declared in the ACR as helm/release-services:0.1.0

I am receiving the following error after a Flux reconcile:

'chart pull error: failed to get chart version for remote reference:
no chart name found'

with helm-controller logs as follows

{"level":"info","ts":"2022-02-07T12:40:18.121Z","logger":"controller.helmrelease","msg":"HelmChart 'flux-system/release-services-test-release-services' is not ready","reconciler group":"helm.toolkit.fluxcd.io","reconciler kind":"HelmRelease","name":"release-services","namespace":"release-services-test"}
{"level":"info","ts":"2022-02-07T12:40:18.135Z","logger":"controller.helmrelease","msg":"reconcilation finished in 15.458307ms, next run in 5m0s","reconciler group":"helm.toolkit.fluxcd.io","reconciler kind":"HelmRelease","name":"release-services","namespace":"release-services-test"}

Below is the HelmChart resource in AKS:

apiVersion: source.toolkit.fluxcd.io/v1beta1
kind: HelmChart
metadata:
  creationTimestamp: "2022-02-07T07:30:16Z"
  finalizers:
  - finalizers.fluxcd.io
  generation: 1
  name: release-services-test-release-services
  namespace: flux-system
  resourceVersion: "105266699"
  selfLink: /apis/source.toolkit.fluxcd.io/v1beta1/namespaces/flux-system/helmcharts/release-services-test-release-services
  uid: e4820a70-8885-44a1-8dfd-0e2bf7256915
spec:
  chart: release-services
  interval: 5m0s
  reconcileStrategy: ChartVersion
  sourceRef:
    kind: HelmRepository
    name: psbombb-helm-acr-dev
  version: '>=0.1.0'
status:
  conditions:
  - lastTransitionTime: "2022-02-07T11:02:49Z"
    message: 'chart pull error: failed to get chart version for remote reference:
      no chart name found'
    reason: ChartPullFailed
    status: "False"
    type: Ready
  observedGeneration: 1

and the HelmRelease is as follows

apiVersion: helm.toolkit.fluxcd.io/v2beta1
kind: HelmRelease
metadata:
  creationTimestamp: "2022-02-07T04:34:14Z"
  finalizers:
  - finalizers.fluxcd.io
  generation: 9
  labels:
    kustomize.toolkit.fluxcd.io/name: apps
    kustomize.toolkit.fluxcd.io/namespace: flux-system
  name: release-services
  namespace: release-services-test
  resourceVersion: "105341484"
  selfLink: /apis/helm.toolkit.fluxcd.io/v2beta1/namespaces/release-services-test/helmreleases/release-services
  uid: 6a6e5f5c-951d-4655-9c15-fa9fe7421a04
spec:
  chart:
    spec:
      chart: release-services
      reconcileStrategy: ChartVersion
      sourceRef:
        kind: HelmRepository
        name: psbombb-helm-acr-dev
        namespace: flux-system
      version: '>=0.1.0'
  install:
    remediation:
      retries: 3
  interval: 5m
  releaseName: release-services
  timeout: 12m
  values:
    image:
      name: release-services
      pullPolicy: IfNotPresent
      registry: <repository>.azurecr.io
      repository: <repository>.azurecr.io/helm/release-services
      tag: 0.1.0
    postgres:
      secret:
        create: false
        existingName: release-services-secrets
status:
  conditions:
  - lastTransitionTime: "2022-02-07T08:27:13Z"
    message: HelmChart 'flux-system/release-services-test-release-services' is not
      ready
    reason: ArtifactFailed
    status: "False"
    type: Ready
  failures: 50
  helmChart: flux-system/release-services-test-release-services
  observedGeneration: 9

Is there anything I am missing that anyone can spot for me please?

Thank you kindly