问:
Service worker with range requests plugin: cannot fetch mp3 files when offline
I am working on a single page PWA that needs to have all content available offline.

Initial setup and problem:
I used create-react-app to set up the basics, then used react-app-rewired to replace the GenerateSW plugin with the InjectManifest and do a simple precacheAndRoute of the webpack generated manifest in my service worker.

Worked like a charm, except for my mp3-files: in Safari I could not see the duration of a track and the progress bar was dead. In Chrome it was more or less okay, only problem was that it would cut off the last 1-2 seconds when playing an audio file.

Initial solution: In my SW configuration, I added a specific registerRoute for mp3-files that used the range request plugin as per https://developers.google.com/web/tools/workbox/guides/advanced-recipes#cached-av. It sort of worked, now everything works fine in both Chrome and Safari as long as I am online. When I go offline, everything except the mp3-files can be fetched from the cache.

You can see the error her: https://cgl-hunter-kids-test.firebaseapp.com/
Click on the title image to enter the site, select "Historien" in the top left menu, and then selected any of the 9 available stories. The audio player is in the top right corner.

In Chrome dev tools, I can see that it fetches the mp3 files from the Service Worker when online. I can also see that the mp3 files do exist in the precache. I have no idea why it cannot find them when offline - can anyone help?

Thank you,
Diana

My service worker configuration:

```<code>const COOKIE_CONSENT_ENDPOINT = '/hunterkidsCookieConsent';
const GAME_DATA_ENDPOINT      = '/hunterkidsGameData';

/* Use client claim to handle SW updates */
workbox.core.clientsClaim();

/* Activate new SW (user triggered) */
self.addEventListener('message', (event) => {
    if (event.data.action === 'skipWaiting') self.skipWaiting();
});

/* Cache files from _precacheManifest (generated by InjectManifest webpack plugin) */
self.__precacheManifest = [].concat(self.__precacheManifest || []);

self.addEventListener('activate', (event) => {event.waitUntil(clients.claim());});

/* Handle ranged quests of mp3 files */
// https://github.com/GoogleChrome/workbox/issues/1644
// https://developers.google.com/web/tools/workbox/guides/advanced-recipes#cached-av
workbox.routing.registerRoute(
  ({url}) => url.pathname.endsWith('.mp3'),
  new workbox.strategies.CacheFirst({
    cacheName: workbox.core.cacheNames.precache,
    plugins: [
        new workbox.cacheableResponse.Plugin({ statuses: [200] }),
        new workbox.rangeRequests.Plugin(),
      ],
  })
);

/* Special fetch requests */
self.addEventListener('fetch', function(event) {
    const {
        request,
        request: {url, method},
  } = event;
  /* Game progress */
  if (url.match(GAME_DATA_ENDPOINT)) {
    if (method === 'POST') {
      /* Write data to cache */
      request.json().then(body => {
        caches.open(GAME_DATA_ENDPOINT).then(function(cache) {
          cache.put(GAME_DATA_ENDPOINT, new Response(JSON.stringify(body)));
        });
      });
      return new Response('{}');
    } else {
      /* Read data from cache */
      event.respondWith(
        caches.open(GAME_DATA_ENDPOINT).then(function(cache) {
          return cache.match(GAME_DATA_ENDPOINT).then(function (response) {
            return response || new Response('{}');;
          }) || new Response('{}');
          })
      );
    }
  }

  /* Cookie consent */
  if (url.match(COOKIE_CONSENT_ENDPOINT)) {
    if (method === 'POST') {
      /* Write data to cookie */
      request.json().then(body => {
        caches.open(COOKIE_CONSENT_ENDPOINT).then(function(cache) {
          cache.put(COOKIE_CONSENT_ENDPOINT, new Response(JSON.stringify(body)));
        });
      });
      return new Response('{}');
    } else {
      /* Read data from cookie */
      event.respondWith(
        caches.open(COOKIE_CONSENT_ENDPOINT).then(function(cache) {
          return cache.match(COOKIE_CONSENT_ENDPOINT).then(function (response) {
            return response || new Response('{}');;
          }) || new Response('{}');
        })
      );
    }
  }
});

/* All other requests */
workbox.precaching.precacheAndRoute(self.__precacheManifest || []);
</code>```

答:
I figured it out!

I had to add the matchOptions to the CacheFirst strategy in my registerRoute:

```<code>workbox.routing.registerRoute(
  ({url}) => url.pathname.endsWith('.mp3'),
  new workbox.strategies.CacheFirst({
    cacheName: workbox.core.cacheNames.precache,
    plugins: [
        new workbox.cacheableResponse.Plugin({ statuses: [200] }),
        new workbox.rangeRequests.Plugin(),
      ],
    matchOptions: {
      ignoreSearch: true,
      ignoreVary: true
    }
  })
);
</code>```

It might have been related to using Firebase for hosting, but I am not sure.

Body:
I am working on a single page PWA that needs to have all content available offline.

Initial setup and problem:
I used create-react-app to set up the basics, then used react-app-rewired to replace the GenerateSW plugin with the InjectManifest and do a simple precacheAndRoute of the webpack generated manifest in my service worker.

Worked like a charm, except for my mp3-files: in Safari I could not see the duration of a track and the progress bar was dead. In Chrome it was more or less okay, only problem was that it would cut off the last 1-2 seconds when playing an audio file.

Initial solution: In my SW configuration, I added a specific registerRoute for mp3-files that used the range request plugin as per https://developers.google.com/web/tools/workbox/guides/advanced-recipes#cached-av. It sort of worked, now everything works fine in both Chrome and Safari as long as I am online. When I go offline, everything except the mp3-files can be fetched from the cache.

You can see the error her: https://cgl-hunter-kids-test.firebaseapp.com/
Click on the title image to enter the site, select "Historien" in the top left menu, and then selected any of the 9 available stories. The audio player is in the top right corner.

In Chrome dev tools, I can see that it fetches the mp3 files from the Service Worker when online. I can also see that the mp3 files do exist in the precache. I have no idea why it cannot find them when offline - can anyone help?

Thank you,
Diana

My service worker configuration:

const COOKIE_CONSENT_ENDPOINT = '/hunterkidsCookieConsent';
const GAME_DATA_ENDPOINT      = '/hunterkidsGameData';

/* Use client claim to handle SW updates */
workbox.core.clientsClaim();

/* Activate new SW (user triggered) */
self.addEventListener('message', (event) => {
    if (event.data.action === 'skipWaiting') self.skipWaiting();
});

/* Cache files from _precacheManifest (generated by InjectManifest webpack plugin) */
self.__precacheManifest = [].concat(self.__precacheManifest || []);

self.addEventListener('activate', (event) => {event.waitUntil(clients.claim());});

/* Handle ranged quests of mp3 files */
// https://github.com/GoogleChrome/workbox/issues/1644
// https://developers.google.com/web/tools/workbox/guides/advanced-recipes#cached-av
workbox.routing.registerRoute(
  ({url}) => url.pathname.endsWith('.mp3'),
  new workbox.strategies.CacheFirst({
    cacheName: workbox.core.cacheNames.precache,
    plugins: [
        new workbox.cacheableResponse.Plugin({ statuses: [200] }),
        new workbox.rangeRequests.Plugin(),
      ],
  })
);

/* Special fetch requests */
self.addEventListener('fetch', function(event) {
    const {
        request,
        request: {url, method},
  } = event;
  /* Game progress */
  if (url.match(GAME_DATA_ENDPOINT)) {
    if (method === 'POST') {
      /* Write data to cache */
      request.json().then(body => {
        caches.open(GAME_DATA_ENDPOINT).then(function(cache) {
          cache.put(GAME_DATA_ENDPOINT, new Response(JSON.stringify(body)));
        });
      });
      return new Response('{}');
    } else {
      /* Read data from cache */
      event.respondWith(
        caches.open(GAME_DATA_ENDPOINT).then(function(cache) {
          return cache.match(GAME_DATA_ENDPOINT).then(function (response) {
            return response || new Response('{}');;
          }) || new Response('{}');
          })
      );
    }
  }

  /* Cookie consent */
  if (url.match(COOKIE_CONSENT_ENDPOINT)) {
    if (method === 'POST') {
      /* Write data to cookie */
      request.json().then(body => {
        caches.open(COOKIE_CONSENT_ENDPOINT).then(function(cache) {
          cache.put(COOKIE_CONSENT_ENDPOINT, new Response(JSON.stringify(body)));
        });
      });
      return new Response('{}');
    } else {
      /* Read data from cookie */
      event.respondWith(
        caches.open(COOKIE_CONSENT_ENDPOINT).then(function(cache) {
          return cache.match(COOKIE_CONSENT_ENDPOINT).then(function (response) {
            return response || new Response('{}');;
          }) || new Response('{}');
        })
      );
    }
  }
});

/* All other requests */
workbox.precaching.precacheAndRoute(self.__precacheManifest || []);

Body:
I figured it out!

I had to add the matchOptions to the CacheFirst strategy in my registerRoute:

workbox.routing.registerRoute(
  ({url}) => url.pathname.endsWith('.mp3'),
  new workbox.strategies.CacheFirst({
    cacheName: workbox.core.cacheNames.precache,
    plugins: [
        new workbox.cacheableResponse.Plugin({ statuses: [200] }),
        new workbox.rangeRequests.Plugin(),
      ],
    matchOptions: {
      ignoreSearch: true,
      ignoreVary: true
    }
  })
);

It might have been related to using Firebase for hosting, but I am not sure.


来源: stackexchange

问:
Python: type inheritance without overloading method with the same name?
is it possible to achieve type inheritance without overwriting class methods? Take for example this code:

```<code>class Parent:
    def special_method(self, name):
        print("hello, {}!".format(name))

class Child:
    def __init__(self, injected_parent):
        self.parent = injected_parent

    def special_method(self):
        self.parent.special_method("Homer Simpson")

parent = Parent()
child = Child(parent)

child.special_method()
# hello, Homer Simpson!
</code>```

Works as expected, but I want the type of child to be Parent and not Child:

```<code>print(type(child))
<class '__main__.Child'>
</code>```

One way I've seen it done is to extend Child with:

```<code>class Child:
    def __init__(self, injected_parent):
        self.parent = injected_parent
        self.__class__ = Parent
...
</code>```

However, then child's special_method gets overwritten:

```<code>parent = Parent()
child = Child(parent)

child.special_method()
# TypeError: special_method() missing 1 required positional argument: 'name'
</code>```

Any way to make child have type Parent without side-effects?

答:
It seems like what you want to do is just regular inheritance, but as @juanpa.arrivillaga pointed out, you are using composition instead. What you are trying to do by changing the __class__ and overloading a method will not work. Here is an example using inheritance which will allow you to overload the method while still having access to the original method and to have child be an instance of parent which seems to meet your requirements:

```<code>class Parent:
    def special_method(self, name):
        print("hello, {}!".format(name))

class Child(Parent):
    def special_method(self):
        super().special_method("Homer Simpson")

child = Child()
</code>```

Now, child will still have a type of Child, but with classes what you want to be checking instead is whether it is an instance of the superclass using isinstance:

```<code>>>> child.special_method()
hello, Homer Simpson!

>>> type(child)
<class '__main__.Child'>

>>> isinstance(child, Parent)
True
</code>```

ContentLicense: CC BY-SA 4.0

Body:
is it possible to achieve type inheritance without overwriting class methods? Take for example this code:

class Parent:
    def special_method(self, name):
        print("hello, {}!".format(name))

class Child:
    def __init__(self, injected_parent):
        self.parent = injected_parent

    def special_method(self):
        self.parent.special_method("Homer Simpson")

parent = Parent()
child = Child(parent)

child.special_method()
# hello, Homer Simpson!

Works as expected, but I want the type of child to be Parent and not Child:

print(type(child))
<class '__main__.Child'>

One way I've seen it done is to extend Child with:

class Child:
    def __init__(self, injected_parent):
        self.parent = injected_parent
        self.__class__ = Parent
...

However, then child's special_method gets overwritten:

parent = Parent()
child = Child(parent)

child.special_method()
# TypeError: special_method() missing 1 required positional argument: 'name'

Any way to make child have type Parent without side-effects?

Body:
It seems like what you want to do is just regular inheritance, but as @juanpa.arrivillaga pointed out, you are using composition instead. What you are trying to do by changing the __class__ and overloading a method will not work. Here is an example using inheritance which will allow you to overload the method while still having access to the original method and to have child be an instance of parent which seems to meet your requirements:

class Parent:
    def special_method(self, name):
        print("hello, {}!".format(name))

class Child(Parent):
    def special_method(self):
        super().special_method("Homer Simpson")

child = Child()

Now, child will still have a type of Child, but with classes what you want to be checking instead is whether it is an instance of the superclass using isinstance:

>>> child.special_method()
hello, Homer Simpson!

>>> type(child)
<class '__main__.Child'>

>>> isinstance(child, Parent)
True


问:
Filter based on user input - LiveData, Recycler, RoomView
I have an SQLite Database for my Android App. Database has a table for properties , and another table for the repairs at each property.

Table repairs  :

```<code>@Entity(tableName = "repairs",
        indices = {@Index(value = "repairID", unique = true), @Index("repairPropID")})

public class MYRepairs
{
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "repid")
    public int id;

    @ColumnInfo(name = "repairID")
    @NonNull
    public String repairID;

    @ColumnInfo(name = "repairPropID")
    public int repairPropID;
}
</code>```

...

and then RepairsDao.java

```<code> @Dao
    public interface MyRepairsDao
    {
        @Query("SELECT * FROM repairs WHERE repid = :repid LIMIT 1")
        MYRepairs findRepairById(String repid);

        @Query("SELECT * FROM repairs WHERE repairPropID = :repairPropID")
        MYRepairs findRepairByPropID(int repairPropID);

        @Query("SELECT * FROM repairs ORDER BY repairPropID ASC")
        LiveData<List<MYRepairs>> getAllRepairs();

 @Query("SELECT * FROM repairs WHERE repairPropID = :repairPropID")
    LiveData<List<MYRepairs>> getPropertyRepairs(int repairPropID);

    }
</code>```

In the ViewModel:

```<code>   public class repairViewModel extends AndroidViewModel
    {
        private MyRepairsDao myRepairDao;
        private LiveData<List<MYRepairs>> repairLiveData;
        private LiveData<List<MYRepairs>> repairPropertyLiveData;
        private LiveData<String> filterLiveData = new MutableLiveData<String>();

        public repairViewModel(@NonNull Application application)
        {
            super(application);
            myRepairDao = DogwoodDatabase.getDatabase(application).repairDao();
            repairLiveData = myRepairDao.getAllRepairs();
            repairPropertyLiveData = myRepairDao.getPropertyRepairs(propertyID);
        }

        public LiveData<List<MYRepairs>> getAllRepairs()
        {
            return repairLiveData;
        }

        public LiveData<List<MYRepairs>> getPropertyRepairs(int propertyID)
        {
            return repairPropertyLiveData;
        }
</code>```

And in the RecyclerView.Adapter:

```<code>public class repairListAdapter extends RecyclerView.Adapter<repairListAdapter.RepairViewHolder>
{
@NonNull
        @Override
        public repairListAdapter.RepairViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
        {
            final View itemView = layoutInflater.inflate(R.layout.repaircontent, parent, false);
            return new repairListAdapter.RepairViewHolder(itemView);
        }
</code>```

In the repairFragment - we only want to view the repairs for a user selected property. Property Code propertyID  is received by the repairFragement. It is known to the initData()

```<code>   public class repairFragment extends Fragment
    {

        private repairListAdapter repairListAdapter;
        private repairViewModel repairViewModel;

        public void onCreate(@Nullable Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            propertyID = getArguments().getString("ARG_PROPNUM_ID");
            propNumID = Integer.parseInt(propertyID);
            initData();
        }

     private void initData()
        {
            Log.e ("INIT", "ID is " + propertyID);

            repairViewModel = new
                   ViewModelProvider(this).get(repairViewModel.class);

repairViewModel.getPropertyRepairs(propertyID).observe(this, new Observer<List<MYRepairs>>()
            {
                @Override
                public void onChanged(@Nullable List<MYRepairs> MYRepairs)
                {
                    repairListAdapter.setMYRepairList(MYRepairs);
                }
            });

        }
</code>```

This returns NO RECORDS.
In an ideal world, my properties would have no repairs, but I do not live in that world!

I have scoured this board for help on filtering .

Can you help me with how to filter for only the repairs for a user selected property (propertyID).

Thanks, Rachael

答:
What you wanted to do is the following:

```<code>public LiveData<List<MYRepairs>> getPropertyRepairs() {
    return repairPropertyLiveData;
}
</code>```

And

```<code>private MutableLiveData<String> selectedPropertyId = new MutableLiveData<>();

private final repairPropertyLiveData = Transformations.switchMap(selectedPropertyId, (id) -> {
    return myRepairDao.getPropertyRepairs(id);
});

public void updateSelectedProperty(String propertyId) {
    selectedPropertyId.setValue(propertyId);
}
</code>```

This way, you don't end up with new subscriptions that were not properly invalidated in case you were to select a different property id later.

Body:
I have an SQLite Database for my Android App. Database has a table for properties , and another table for the repairs at each property.

Table repairs  :

@Entity(tableName = "repairs",
        indices = {@Index(value = "repairID", unique = true), @Index("repairPropID")})

public class MYRepairs
{
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "repid")
    public int id;

    @ColumnInfo(name = "repairID")
    @NonNull
    public String repairID;

    @ColumnInfo(name = "repairPropID")
    public int repairPropID;
}

...

and then RepairsDao.java

 @Dao
    public interface MyRepairsDao
    {
        @Query("SELECT * FROM repairs WHERE repid = :repid LIMIT 1")
        MYRepairs findRepairById(String repid);

        @Query("SELECT * FROM repairs WHERE repairPropID = :repairPropID")
        MYRepairs findRepairByPropID(int repairPropID);

        @Query("SELECT * FROM repairs ORDER BY repairPropID ASC")
        LiveData<List<MYRepairs>> getAllRepairs();

 @Query("SELECT * FROM repairs WHERE repairPropID = :repairPropID")
    LiveData<List<MYRepairs>> getPropertyRepairs(int repairPropID);

    }

In the ViewModel:

   public class repairViewModel extends AndroidViewModel
    {
        private MyRepairsDao myRepairDao;
        private LiveData<List<MYRepairs>> repairLiveData;
        private LiveData<List<MYRepairs>> repairPropertyLiveData;
        private LiveData<String> filterLiveData = new MutableLiveData<String>();

        public repairViewModel(@NonNull Application application)
        {
            super(application);
            myRepairDao = DogwoodDatabase.getDatabase(application).repairDao();
            repairLiveData = myRepairDao.getAllRepairs();
            repairPropertyLiveData = myRepairDao.getPropertyRepairs(propertyID);
        }

        public LiveData<List<MYRepairs>> getAllRepairs()
        {
            return repairLiveData;
        }

        public LiveData<List<MYRepairs>> getPropertyRepairs(int propertyID)
        {
            return repairPropertyLiveData;
        }

And in the RecyclerView.Adapter:

public class repairListAdapter extends RecyclerView.Adapter<repairListAdapter.RepairViewHolder>
{
@NonNull
        @Override
        public repairListAdapter.RepairViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
        {
            final View itemView = layoutInflater.inflate(R.layout.repaircontent, parent, false);
            return new repairListAdapter.RepairViewHolder(itemView);
        }

In the repairFragment - we only want to view the repairs for a user selected property. Property Code propertyID  is received by the repairFragement. It is known to the initData()

   public class repairFragment extends Fragment
    {

        private repairListAdapter repairListAdapter;
        private repairViewModel repairViewModel;

        public void onCreate(@Nullable Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            propertyID = getArguments().getString("ARG_PROPNUM_ID");
            propNumID = Integer.parseInt(propertyID);
            initData();
        }

     private void initData()
        {
            Log.e ("INIT", "ID is " + propertyID);

            repairViewModel = new
                   ViewModelProvider(this).get(repairViewModel.class);

repairViewModel.getPropertyRepairs(propertyID).observe(this, new Observer<List<MYRepairs>>()
            {
                @Override
                public void onChanged(@Nullable List<MYRepairs> MYRepairs)
                {
                    repairListAdapter.setMYRepairList(MYRepairs);
                }
            });

        }

This returns NO RECORDS.
In an ideal world, my properties would have no repairs, but I do not live in that world!

I have scoured this board for help on filtering .

Can you help me with how to filter for only the repairs for a user selected property (propertyID).

Thanks, Rachael

Body:
What you wanted to do is the following:

public LiveData<List<MYRepairs>> getPropertyRepairs() {
    return repairPropertyLiveData;
}

And

private MutableLiveData<String> selectedPropertyId = new MutableLiveData<>();

private final repairPropertyLiveData = Transformations.switchMap(selectedPropertyId, (id) -> {
    return myRepairDao.getPropertyRepairs(id);
});

public void updateSelectedProperty(String propertyId) {
    selectedPropertyId.setValue(propertyId);
}

This way, you don't end up with new subscriptions that were not properly invalidated in case you were to select a different property id later.


问:
Flexbox won't align horizontally
Based on everyhting I've googled, flexbox should be displaying in a horizontal row by default, but I feel like I've tried everything and can't get this to work. I will post the code below. If you remove the "display: flex;" from the css it looks similar to how I want it to look, but I want the heights of the 3 divs to all be even, which is why I want to use flexbox. Any help would be appreciated.

/*PARENT*/
form fieldset{
    display: flex;
    flex-direction: row;
    padding: 5px 0px;
    border: 0;
}

/*CHILDREN*/
form fieldset > div{
    display: inline-block;
    width: 25%;
    text-align: center;
    border: solid thin black;
}

/*STYLES*/
form fieldset:first-of-type > div > p{
    text-decoration: underline;
    font-size: 1.2em;
}

form fieldset:first-of-type > div > div{
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
    font-size: 0.9em;
}

form fieldset:first-of-type div p{
    text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
    <link rel="stylesheet" href="temp_css.css">
</head>
<body>
    <form action="temp.html">
        <fieldset id="fieldset">
            <div id="movie">
                <p>Movie or TV Show?</p>
                <div>
                    <label for="movie">Movie</label>
                    <input type="radio" name="tv_or_movie" id="movie">
                    <label for="tv">TV Show</label>
                    <input type="radio" name="tv_or_movie" id="tv">
                </div>
            </div>
            <div id="animated">
                <p>Is It Animated?</p>
                <div>
                    <label for="animated_yes">Yes</label>
                    <input type="radio" name="animated" id="animated_yes">
                    <label for="animated_no">No</label>
                    <input type="radio" name="animated" id="animated_no">
                </div>
            </div>
            <div id="favorites">
                <p>Would You Consider it One of Your Favorites?</p>
                <div>
                    <label for="favorites_yes">Yes</label>
                    <input type="radio" name="favorite" id="favorites_yes">
                    <label for="favorites_no">No</label>
                    <input type="radio" name="favorite" id="favorites_no">
                </div>
            </div>
        </fieldset>
    </form>
</body>
</html></code>```

答:
flex with fieldset will not go very well. I just used a wrapper and all other things will be taken care by flex(I hope that is not an issue here).

Remove unnecessary elements, justify-content will take care the things in your case.

make things simpler than making it complicated.

.MainDiv {
  display: flex;
  width: 100%;
  justify-content: space-around;
}

.MainDiv>div {
  width: 25%;
  text-align: center;
  border: 1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>test</title>
  <link rel="stylesheet" href="temp_css.css">
</head>

<body>
  <form action="temp.html">
    <fieldset id="fieldset">
      <div class="MainDiv">
        <div id="movie">
          <p>Movie or TV Show?</p>
          <div>
            <label for="movie">Movie</label>
            <input type="radio" name="tv_or_movie" id="movie">
            <label for="tv">TV Show</label>
            <input type="radio" name="tv_or_movie" id="tv">
          </div>
        </div>

        <div id="animated">
          <p>Is It Animated?</p>
          <div>
            <label for="animated_yes">Yes</label>
            <input type="radio" name="animated" id="animated_yes">
            <label for="animated_no">No</label>
            <input type="radio" name="animated" id="animated_no">
          </div>
        </div>

        <div id="favorites">
          <p>Would You Consider it One of Your Favorites?</p>
          <div>
            <label for="favorites_yes">Yes</label>
            <input type="radio" name="favorite" id="favorites_yes">
            <label for="favorites_no">No</label>
            <input type="radio" name="favorite" id="favorites_no">
          </div>
        </div>
      </div>

    </fieldset>
  </form>
</body>

</html></code>```

Title: Flexbox won't align horizontally

Body:
Based on everyhting I've googled, flexbox should be displaying in a horizontal row by default, but I feel like I've tried everything and can't get this to work. I will post the code below. If you remove the "display: flex;" from the css it looks similar to how I want it to look, but I want the heights of the 3 divs to all be even, which is why I want to use flexbox. Any help would be appreciated.

/*PARENT*/
form fieldset{
    display: flex;
    flex-direction: row;
    padding: 5px 0px;
    border: 0;
}

/*CHILDREN*/
form fieldset > div{
    display: inline-block;
    width: 25%;
    text-align: center;
    border: solid thin black;
}

/*STYLES*/
form fieldset:first-of-type > div > p{
    text-decoration: underline;
    font-size: 1.2em;
}

form fieldset:first-of-type > div > div{
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
    font-size: 0.9em;
}

form fieldset:first-of-type div p{
    text-align: center;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
    <link rel="stylesheet" href="temp_css.css">

    <form action="temp.html">
        <fieldset id="fieldset">

Movie or TV Show?

                    Movie
                    <input type="radio" name="tv_or_movie" id="movie">
                    TV Show
                    <input type="radio" name="tv_or_movie" id="tv">

Is It Animated?

                    Yes
                    <input type="radio" name="animated" id="animated_yes">
                    No
                    <input type="radio" name="animated" id="animated_no">

Would You Consider it One of Your Favorites?

                    Yes
                    <input type="radio" name="favorite" id="favorites_yes">
                    No
                    <input type="radio" name="favorite" id="favorites_no">

        </fieldset>
    </form>

Body:
flex with fieldset will not go very well. I just used a wrapper and all other things will be taken care by flex(I hope that is not an issue here).

Remove unnecessary elements, justify-content will take care the things in your case.

make things simpler than making it complicated.

.MainDiv {
  display: flex;
  width: 100%;
  justify-content: space-around;
}

.MainDiv>div {
  width: 25%;
  text-align: center;
  border: 1px solid black;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>test</title>
  <link rel="stylesheet" href="temp_css.css">
</head>

<body>
  <form action="temp.html">
    <fieldset id="fieldset">
      <div class="MainDiv">
        <div id="movie">
          <p>Movie or TV Show?</p>
          <div>
            <label for="movie">Movie</label>
            <input type="radio" name="tv_or_movie" id="movie">
            <label for="tv">TV Show</label>
            <input type="radio" name="tv_or_movie" id="tv">
          </div>
        </div>

        <div id="animated">
          <p>Is It Animated?</p>
          <div>
            <label for="animated_yes">Yes</label>
            <input type="radio" name="animated" id="animated_yes">
            <label for="animated_no">No</label>
            <input type="radio" name="animated" id="animated_no">
          </div>
        </div>

        <div id="favorites">
          <p>Would You Consider it One of Your Favorites?</p>
          <div>
            <label for="favorites_yes">Yes</label>
            <input type="radio" name="favorite" id="favorites_yes">
            <label for="favorites_no">No</label>
            <input type="radio" name="favorite" id="favorites_no">
          </div>
        </div>
      </div>

    </fieldset>
  </form>
</body>

</html>


问:
Making a graph with different colours
I have a dataset of corona virus which looks something like this

```<code>day month cases deaths country
3     5     10    1     USA
4     5     12    2     USA
</code>```

it has multiple entries for each country for different days, I made it filter out so it only gets the data from 28th of May now I want to make a graph for every country with how many cases they have use pandas and matploitlib

However it's not working properly

when I use

```<code>import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_excel("covid.xlsx")
print(df.columns.tolist())
df.loc[(df.day == 28) & (df.month==5), :].plot.line(x='countriesAndTerritories', y='deaths')
plt.show()
</code>```

The code executes but only shows 5 countries and the countriesAndTerritories is on the x axis, when I switch around x='countriesAndTerritories', y='deaths' I get TypeError: no numeric data to plot

This is  a reference of what I want: https://qap.ecdc.europa.eu/public/single/?appid=f818d019-18c5-41e0-99e6-bd2b7f6f17b5&obj=3d471628-9a6e-4938-95da-0cba933925ca&opt=nointeraction&select=clearall (europe's data visualization)

答:
You can reproduce the plot with seaborn:

```<code>import seaborn as sns
plt.figure(figsize=(10,6))
sns.lineplot(data=df.iloc[0:600,:], x='dateRep', y='deaths', hue='countriesAndTerritories')
</code>```

Output:

Here I selected a subset of the whole dataframe (since there are 200 countries it would be too messy to show the legend).
If you want to select another range, change the 0 and 600 (df.iloc[0:600,:]). Or if you have a list of countries you want to plot you can do this:

```<code>countries_to_plot = ["Zimbabwe", "Italy","France","Netherlands"]
sns.lineplot(data=df[df.countriesAndTerritories.isin(countries_to_plot)], x='dateRep', y='deaths', hue='countriesAndTerritories')
</code>```

Title: Making a graph with different colours

Body:
I have a dataset of corona virus which looks something like this

day month cases deaths country
3     5     10    1     USA
4     5     12    2     USA

it has multiple entries for each country for different days, I made it filter out so it only gets the data from 28th of May now I want to make a graph for every country with how many cases they have use pandas and matploitlib

However it's not working properly

when I use

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_excel("covid.xlsx")
print(df.columns.tolist())
df.loc[(df.day == 28) & (df.month==5), :].plot.line(x='countriesAndTerritories', y='deaths')
plt.show()

The code executes but only shows 5 countries and the countriesAndTerritories is on the x axis, when I switch around x='countriesAndTerritories', y='deaths' I get TypeError: no numeric data to plot

This is  a reference of what I want: https://qap.ecdc.europa.eu/public/single/?appid=f818d019-18c5-41e0-99e6-bd2b7f6f17b5&obj=3d471628-9a6e-4938-95da-0cba933925ca&opt=nointeraction&select=clearall (europe's data visualization)

Body:
You can reproduce the plot with seaborn:

import seaborn as sns
plt.figure(figsize=(10,6))
sns.lineplot(data=df.iloc[0:600,:], x='dateRep', y='deaths', hue='countriesAndTerritories')

Output:

Here I selected a subset of the whole dataframe (since there are 200 countries it would be too messy to show the legend).
If you want to select another range, change the 0 and 600 (df.iloc[0:600,:]). Or if you have a list of countries you want to plot you can do this:

countries_to_plot = ["Zimbabwe", "Italy","France","Netherlands"]
sns.lineplot(data=df[df.countriesAndTerritories.isin(countries_to_plot)], x='dateRep', y='deaths', hue='countriesAndTerritories')


问:
jquery $.each() for objects
```<code><script>
    $(document).ready(function() {
        var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };
        $.each(data.programs[0], function(key,val) {
            alert(key+val);
        });
    });
</script>
</code>```

This code retrieves the first data. name:zonealarm and price:500.

How can I retrieve all the data in the object?

I tried $.each(data.programs, function(key,val) but it didn't work.

Should I put it in a loop?

答:
$.each() works for objects and arrays both:

```<code>var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };

$.each(data.programs, function (i) {
    $.each(data.programs[i], function (key, val) {
        alert(key + val);
    });
});
</code>```

...and since you will get the current array element as second argument:

```<code>$.each(data.programs, function (i, currProgram) {
    $.each(currProgram, function (key, val) {
        alert(key + val);
    });
});
</code>```

Title: jquery $.each() for objects

Body:
$.each() works for objects and arrays both:

var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };

$.each(data.programs, function (i) {
    $.each(data.programs[i], function (key, val) {
        alert(key + val);
    });
});

...and since you will get the current array element as second argument:

$.each(data.programs, function (i, currProgram) {
    $.each(currProgram, function (key, val) {
        alert(key + val);
    });
});

ContentLicense: CC BY-SA 3.0


问:
Links are broken in production build in create-react-app
I am doing the most simple thing possible using create-react-app. I want to get the test application running on my website.

I create my create-react-app using this command.

```<code>npx create-react-app myTest
</code>```

Then I test that it works when running the 'test' script.

Yes. It works fine on the dev-server. I get the spinny react logo.

Next, I run the 'build' script.

This creates a supposedly production ready collection of files :

I create a subdirectoy on my webserver to host this project.

www.mywebsite.com/myReactTest/

I copy over all the files using Filezilla.

I then navigate over to www.mywebsite.com/myReactTest/ and all I get is a white screen.

Looking at the console, I can see that the paths are not quite correct.

What puzzles me is that this is supposed to be a production ready build? How is this possible?

答:
To run a static server using Create-React-App you need to serve it using Node.

```<code>npm install -g serve

# serve the build folder
serve -s build
</code>```

See possible other solutions in related docs.

Body:
I am doing the most simple thing possible using create-react-app. I want to get the test application running on my website.

I create my create-react-app using this command.

npx create-react-app myTest

Then I test that it works when running the 'test' script.

Yes. It works fine on the dev-server. I get the spinny react logo.

Next, I run the 'build' script.

This creates a supposedly production ready collection of files :

I create a subdirectoy on my webserver to host this project.

www.mywebsite.com/myReactTest/

I copy over all the files using Filezilla.

I then navigate over to www.mywebsite.com/myReactTest/ and all I get is a white screen.

Looking at the console, I can see that the paths are not quite correct.

What puzzles me is that this is supposed to be a production ready build? How is this possible?

Body:
To run a static server using Create-React-App you need to serve it using Node.

npm install -g serve

# serve the build folder
serve -s build

See possible other solutions in related docs.


问:
How to get a new pandas data frame column with cluster groups using scikit-learn
I am new to scikit-learn. I have a pandas DataFrame with 1 column containing text that I want to cluster.
As an end result I would like to have my dataframe showing an extra column with the cluster group it belongs to, for each row.
My DF looks like this:

```<code>event_date,event_desc,event_url
2020-05-28 07:03:00,Roche’s OCREVUS (ocrelizumab) shorter 2-hour infusion time approved in Europe,https://www.roche.com/investors/updates/inv-update-2020-05-28b.htm
2020-05-28 07:00:00,Roche initiates phase III clinical trial of Actemra/RoActemra plus remdesivir in hospitalised patients with severe COVID-19 pneumonia,https://www.roche.com/investors/updates/inv-update-2020-05-28.htm
2020-05-27 07:00:00,Roche’s Port Delivery System with ranibizumab shows positive phase III results in neovascular age-related macular degeneration,https://www.roche.com/investors/updates/inv-update-2020-05-27.htm
2020-05-25 15:00:00,Reminder: Invitation to Roche’s virtual event on key oncology data presented at ASCO 2020,https://www.roche.com/investors/updates/inv-update-2020-05-25.htm
2020-05-22 07:03:00,Roche acquires Stratos Genomics to further develop DNA based sequencing for diagnostic use,https://www.roche.com/investors/updates/inv-update-2020-05-22b.htm
2020-05-22 07:00:00,New longer-term data reinforce safety of Roche’s satralizumab in adults and adolescents with neuromyelitis optica spectrum disorder,https://www.roche.com/investors/updates/inv-update-2020-05-22.htm
2020-05-19 07:00:00,FDA approves Roche’s Tecentriq as a first-line monotherapy for certain people with metastatic non-small cell lung cancer,https://www.roche.com/investors/updates/inv-update-2020-05-19.htm
2020-05-15 07:00:00,Roche launches new blood gas digital solution designed to improve patient care,https://www.roche.com/investors/updates/inv-update-2020-05-15.htm
2020-05-14 07:00:00,Roche to present first clinical data on novel anti-TIGIT cancer immunotherapy tiragolumab at ASCO,https://www.roche.com/investors/updates/inv-update-2020-05-14.htm
2020-05-11 14:15:00,A formative figure in the company's history: Roche Honorary Chairman Fritz Gerber dies at the age of 91,https://www.roche.com/investors/updates/inv-update-2020-05-11c.htm
2020-05-11 07:00:00,Changes to the Roche Enlarged Corporate Executive Committee,https://www.roche.com/investors/updates/inv-update-2020-05-11.htm
2020-05-07 07:00:00,New data at the ASCO20 Virtual Scientific Program reflects Roche’s commitment to accelerating progress in cancer care,https://www.roche.com/investors/updates/inv-update-2020-05-07.htm
2020-05-06 15:00:00,Invitation to Roche’s virtual event on key oncology data presented at ASCO 2020,https://www.roche.com/investors/updates/inv-update-2020-05-06.htm
2020-05-03 04:15:00,Roche’s COVID-19 antibody test receives FDA Emergency Use Authorization and is available in markets accepting the CE mark,https://www.roche.com/investors/updates/inv-update-2020-05-03.htm
2020-04-30 14:00:00,Reminder: Invitation to Roche’s Virtual Event “Digital technology and advanced analytics in Roche”,https://www.roche.com/investors/updates/inv-update-2020-04-30.htm
2020-04-28 07:03:00,New 6-year data for Roche’s OCREVUS (ocrelizumab) show earlier treatment initiation nearly halves risk of needing walking aid in relapsing multiple sclerosis,https://www.roche.com/investors/updates/inv-update-2020-04-28b.htm
2020-04-28 07:00:00,Roche’s risdiplam shows significant improvement in survival and motor milestones in infants with Type 1 spinal muscular atrophy (SMA),https://www.roche.com/investors/updates/inv-update-2020-04-28.htm
2020-04-24 17:35:00,Positive Results from the Phase III SAkuraStar Study for Satralizumab in NMOSD Published in The Lancet Neurology,https://www.roche.com/investors/updates/inv-update-2020-04-24.htm
2020-04-22 07:00:00,"First quarter with 2% growth in Swiss francs, 7% at constant exchange rates",https://www.roche.com/investors/updates/inv-update-2020-04-22.htm
2020-04-21 14:00:00,Reminder: Invitation to Roche’s live audio webcast on new AAN 2020 data ,https://www.roche.com/investors/updates/inv-update-2020-04-21b.htm
2020-04-21 07:00:00,Roche receives FDA approval for cobas HPV test for use on the cobas 6800/8800 Systems to identify women at risk for cervical cancer,https://www.roche.com/investors/updates/inv-update-2020-04-21.htm
2020-04-20 07:00:00,US FDA and EMA accept applications for Roche’s OCREVUS (ocrelizumab) shorter 2-hour infusion time,https://www.roche.com/investors/updates/inv-update-2020-04-20.htm
2020-04-17 07:00:00,Roche develops new serology test to detect COVID-19 antibodies,https://www.roche.com/investors/updates/inv-update-2020-04-17.htm
2020-04-15 10:00:00,Reminder: Invitation to Roche’s First Quarter Sales 2020 Audio Webcast and Conference Call,https://www.roche.com/investors/updates/inv-update-2020-04-15b.htm
</code>```

I run the clustering with column event_desc

So far I use the following code from useful link:

```<code>    import pandas as pd

    from sklearn.feature_extraction.text import TfidfVectorizer
    from sklearn.cluster import KMeans
    my_csv_file_name = 'temp.csv'
    result_df = pd.read_csv(csv_file_name, sep=',', parse_dates=['event_date'],
                            dtype={'event_desc': pd.StringDtype(), 'event_url': pd.StringDtype()})

    vectorizer = TfidfVectorizer(stop_words='english')
    X = vectorizer.fit_transform(result_df['event_desc'])
    true_k = 10
    model = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1)
    model.fit(X)

    print("Top terms per cluster:")
    order_centroids = model.cluster_centers_.argsort()[:, ::-1]
    terms = vectorizer.get_feature_names()
    for i in range(true_k):
        print("Cluster %d:" % i),
        for ind in order_centroids[i, :10]:
            print(' %s' % terms[ind]),

    print("Prediction")

    Y = vectorizer.transform(["chrome browser to open."])
    prediction = model.predict(Y)
    print(prediction)

</code>```

It prints "grouped" keywords by cluster, but I would like to associate each cluster with its own row: meaning that the initial dataframe would have an extra column cluster_group with numbers between 0 to 9  corresponding to the cluster group it belongs to (I choose 10 groups-the actual csv is more than 3000 rows). Any idea of how to do that?
Thanks a lot. best

答:
The cluster groups are stored in the labels_ attribute of your model object, i.e. model.labels_ returns an array where each element contains the cluster group of each row in your data frame.

```<code>import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans

my_csv_file_name = 'temp.csv'
result_df = pd.read_csv(my_csv_file_name, sep=',', parse_dates=['event_date'],
dtype={'event_desc': pd.StringDtype(), 'event_url': pd.StringDtype()})

vectorizer = TfidfVectorizer(stop_words='english')
X = vectorizer.fit_transform(result_df['event_desc'])

true_k = 10
model = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1)
model.fit(X)

# extract the cluster groups
result_df['cluster_group'] = model.labels_

print(result_df['cluster_group'].sort_values().unique())
[0 1 2 3 4 5 6 7 8 9]
</code>```

Body:
I am new to scikit-learn. I have a pandas DataFrame with 1 column containing text that I want to cluster.
As an end result I would like to have my dataframe showing an extra column with the cluster group it belongs to, for each row.
My DF looks like this:

event_date,event_desc,event_url
2020-05-28 07:03:00,Roche’s OCREVUS (ocrelizumab) shorter 2-hour infusion time approved in Europe,https://www.roche.com/investors/updates/inv-update-2020-05-28b.htm
2020-05-28 07:00:00,Roche initiates phase III clinical trial of Actemra/RoActemra plus remdesivir in hospitalised patients with severe COVID-19 pneumonia,https://www.roche.com/investors/updates/inv-update-2020-05-28.htm
2020-05-27 07:00:00,Roche’s Port Delivery System with ranibizumab shows positive phase III results in neovascular age-related macular degeneration,https://www.roche.com/investors/updates/inv-update-2020-05-27.htm
2020-05-25 15:00:00,Reminder: Invitation to Roche’s virtual event on key oncology data presented at ASCO 2020,https://www.roche.com/investors/updates/inv-update-2020-05-25.htm
2020-05-22 07:03:00,Roche acquires Stratos Genomics to further develop DNA based sequencing for diagnostic use,https://www.roche.com/investors/updates/inv-update-2020-05-22b.htm
2020-05-22 07:00:00,New longer-term data reinforce safety of Roche’s satralizumab in adults and adolescents with neuromyelitis optica spectrum disorder,https://www.roche.com/investors/updates/inv-update-2020-05-22.htm
2020-05-19 07:00:00,FDA approves Roche’s Tecentriq as a first-line monotherapy for certain people with metastatic non-small cell lung cancer,https://www.roche.com/investors/updates/inv-update-2020-05-19.htm
2020-05-15 07:00:00,Roche launches new blood gas digital solution designed to improve patient care,https://www.roche.com/investors/updates/inv-update-2020-05-15.htm
2020-05-14 07:00:00,Roche to present first clinical data on novel anti-TIGIT cancer immunotherapy tiragolumab at ASCO,https://www.roche.com/investors/updates/inv-update-2020-05-14.htm
2020-05-11 14:15:00,A formative figure in the company's history: Roche Honorary Chairman Fritz Gerber dies at the age of 91,https://www.roche.com/investors/updates/inv-update-2020-05-11c.htm
2020-05-11 07:00:00,Changes to the Roche Enlarged Corporate Executive Committee,https://www.roche.com/investors/updates/inv-update-2020-05-11.htm
2020-05-07 07:00:00,New data at the ASCO20 Virtual Scientific Program reflects Roche’s commitment to accelerating progress in cancer care,https://www.roche.com/investors/updates/inv-update-2020-05-07.htm
2020-05-06 15:00:00,Invitation to Roche’s virtual event on key oncology data presented at ASCO 2020,https://www.roche.com/investors/updates/inv-update-2020-05-06.htm
2020-05-03 04:15:00,Roche’s COVID-19 antibody test receives FDA Emergency Use Authorization and is available in markets accepting the CE mark,https://www.roche.com/investors/updates/inv-update-2020-05-03.htm
2020-04-30 14:00:00,Reminder: Invitation to Roche’s Virtual Event “Digital technology and advanced analytics in Roche”,https://www.roche.com/investors/updates/inv-update-2020-04-30.htm
2020-04-28 07:03:00,New 6-year data for Roche’s OCREVUS (ocrelizumab) show earlier treatment initiation nearly halves risk of needing walking aid in relapsing multiple sclerosis,https://www.roche.com/investors/updates/inv-update-2020-04-28b.htm
2020-04-28 07:00:00,Roche’s risdiplam shows significant improvement in survival and motor milestones in infants with Type 1 spinal muscular atrophy (SMA),https://www.roche.com/investors/updates/inv-update-2020-04-28.htm
2020-04-24 17:35:00,Positive Results from the Phase III SAkuraStar Study for Satralizumab in NMOSD Published in The Lancet Neurology,https://www.roche.com/investors/updates/inv-update-2020-04-24.htm
2020-04-22 07:00:00,"First quarter with 2% growth in Swiss francs, 7% at constant exchange rates",https://www.roche.com/investors/updates/inv-update-2020-04-22.htm
2020-04-21 14:00:00,Reminder: Invitation to Roche’s live audio webcast on new AAN 2020 data ,https://www.roche.com/investors/updates/inv-update-2020-04-21b.htm
2020-04-21 07:00:00,Roche receives FDA approval for cobas HPV test for use on the cobas 6800/8800 Systems to identify women at risk for cervical cancer,https://www.roche.com/investors/updates/inv-update-2020-04-21.htm
2020-04-20 07:00:00,US FDA and EMA accept applications for Roche’s OCREVUS (ocrelizumab) shorter 2-hour infusion time,https://www.roche.com/investors/updates/inv-update-2020-04-20.htm
2020-04-17 07:00:00,Roche develops new serology test to detect COVID-19 antibodies,https://www.roche.com/investors/updates/inv-update-2020-04-17.htm
2020-04-15 10:00:00,Reminder: Invitation to Roche’s First Quarter Sales 2020 Audio Webcast and Conference Call,https://www.roche.com/investors/updates/inv-update-2020-04-15b.htm

I run the clustering with column event_desc

So far I use the following code from useful link:

    import pandas as pd

    from sklearn.feature_extraction.text import TfidfVectorizer
    from sklearn.cluster import KMeans
    my_csv_file_name = 'temp.csv'
    result_df = pd.read_csv(csv_file_name, sep=',', parse_dates=['event_date'],
                            dtype={'event_desc': pd.StringDtype(), 'event_url': pd.StringDtype()})

    vectorizer = TfidfVectorizer(stop_words='english')
    X = vectorizer.fit_transform(result_df['event_desc'])
    true_k = 10
    model = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1)
    model.fit(X)

    print("Top terms per cluster:")
    order_centroids = model.cluster_centers_.argsort()[:, ::-1]
    terms = vectorizer.get_feature_names()
    for i in range(true_k):
        print("Cluster %d:" % i),
        for ind in order_centroids[i, :10]:
            print(' %s' % terms[ind]),

    print("Prediction")

    Y = vectorizer.transform(["chrome browser to open."])
    prediction = model.predict(Y)
    print(prediction)

It prints "grouped" keywords by cluster, but I would like to associate each cluster with its own row: meaning that the initial dataframe would have an extra column cluster_group with numbers between 0 to 9  corresponding to the cluster group it belongs to (I choose 10 groups-the actual csv is more than 3000 rows). Any idea of how to do that?
Thanks a lot. best

Body:
The cluster groups are stored in the labels_ attribute of your model object, i.e. model.labels_ returns an array where each element contains the cluster group of each row in your data frame.

import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans

my_csv_file_name = 'temp.csv'
result_df = pd.read_csv(my_csv_file_name, sep=',', parse_dates=['event_date'],
dtype={'event_desc': pd.StringDtype(), 'event_url': pd.StringDtype()})

vectorizer = TfidfVectorizer(stop_words='english')
X = vectorizer.fit_transform(result_df['event_desc'])

true_k = 10
model = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1)
model.fit(X)

# extract the cluster groups
result_df['cluster_group'] = model.labels_

print(result_df['cluster_group'].sort_values().unique())
[0 1 2 3 4 5 6 7 8 9]


问:
Weird Issue - DataSource is changing after injection to service
This one is really puzzling me. I have a Spring Boot (2.1.2) app where I am managing two data sources via MyBatis and Spring. I have multiple MyBatis mappers and each one is configured to use a particular data source. The code for that configuration is below:

```<code>import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
public class MyBatisConfig {

    private static final String POSTGRES_SESSION_FACTORY = "postgresSessionFactory";
    private static final String MYSQL_SESSION_FACTORY = "mySqlDbSessionFactory";

    @Bean(name = POSTGRES_SESSION_FACTORY, destroyMethod = "")
    @Primary
    public SqlSessionFactoryBean postgresSessionFactory(
            @Qualifier(DataSourceConfig.PRIMARY_DATA_SOURCE) final DataSource oneDataSource,
            ApplicationContext applicationContext) throws Exception {
        final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setConfigLocation(applicationContext.getResource("classpath:mybatis-config.xml"));
        sqlSessionFactoryBean.setDataSource(oneDataSource);
        SqlSessionFactory sqlSessionFactory;
        sqlSessionFactory = sqlSessionFactoryBean.getObject();
        sqlSessionFactory.getConfiguration().addMapper(Mapper1.class);
        sqlSessionFactory.getConfiguration().addMapper(Mapper2.class);

        return sqlSessionFactoryBean;
    }

    @Bean(name = MYSQL_SESSION_FACTORY, destroyMethod = "")
    public SqlSessionFactoryBean mySqlSessionFactory(
            @Qualifier(DataSourceConfig.SECONDARY_DATA_SOURCE) final DataSource anotherDataSource,
            ApplicationContext applicationContext) throws Exception {
        final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setConfigLocation(applicationContext.getResource("classpath:mybatis-config-sql.xml"));
        sqlSessionFactoryBean.setDataSource(anotherDataSource);
        final SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
        sqlSessionFactory.getConfiguration().addMapper(Mapper3.class);
        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperFactoryBean<Mapper1> accountMapperFactory(@Qualifier(POSTGRES_SESSION_FACTORY) final SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {
        MapperFactoryBean<Mapper1> factoryBean = new MapperFactoryBean<>(Mapper1.class);
        factoryBean.setSqlSessionFactory(sqlSessionFactoryBean.getObject());
        return factoryBean;
    }

    @Bean
    public MapperFactoryBean<Mapper2> domainMapperFactory(@Qualifier(POSTGRES_SESSION_FACTORY) final SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {
        MapperFactoryBean<Mapper2> factoryBean = new MapperFactoryBean<>(Mapper2.class);
        factoryBean.setSqlSessionFactory(sqlSessionFactoryBean.getObject());
        return factoryBean;
    }

    @Bean
    public MapperFactoryBean<Mapper3> usageMapperFactory(@Qualifier(MYSQL_SESSION_FACTORY) final SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {
        MapperFactoryBean<Mapper3> factoryBean = new MapperFactoryBean<>(Mapper3.class);
        factoryBean.setSqlSessionFactory(sqlSessionFactoryBean.getObject());
        return factoryBean;
    }
}
</code>```

If I use my debugger, I can very that at the time these beans are being initialized, all of them are pointing to the correct data source. (Mapper1 and Mapper2's SqlSessionFactorys connect to the postgres datasource, Mapper3's SqlSessionFactory connects to the mysql datasource.

But strangely, when they are injected into a service, all three Mappers are connected to the postgres datasource. I am beyond confused at this point.

The service and injection are quite simple:

```<code>@Autowired private Mapper1 mapper1;
@Autowired private Mapper2 mapper2;
@Autowired private Mapper3 mapper3;
</code>```

However when I call the service and stop it with the debugger, I can see that mapper3 is connected to the wrong datasource (postgres).

Any ideas? Any more information needed?

答:
I had the same effects, when configuring multiple datasources with MyBatis. At runtime, all mappers were using the last defined datasource connection credentials, although during startup everything looked fine.

I could narrow the problem down to the factoryBean definition and setting the configuration. As it seems, the configuration object is shared among all datasources (as I set them here), because I set the same instance from the MyBatisProperties. During runtime the configuration is also the place where MyBatis gets the datasource from the Environment property.

The "magic" happens on factoryBean.getObject() and factoryBean.buildSqlSessionFactory(). Here, the datasource is set into the configuration. When the configuration was not explicitly set, then a new default one is created. Otherwise, the configuration object is reused. Thus when initializing several factory beans with the same configuration object, then the configuration object gets every datasource injected and the last datasource remains.

This might be a bug, because as a Mybatis user I expect Mybatis to use the datasource I provide with factoryBean.setDataSource(aDatasource) So, when I commented out factoryBean.setConfiguration, then everything works as intended, but of course my configuration is not applied.

```<code>@Bean("sqlSessionFactoryA")
public SqlSessionFactory sqlSessionFactory(@Qualifier("datasourceA") DataSource aDataSource) throws Exception {
  SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
  factoryBean.setDataSource(aDataSource);
  factoryBean.setConfigurationProperties(properties.getConfigurationProperties());
//    factoryBean.setConfiguration(properties.getConfiguration());
  return factoryBean.getObject();
}
</code>```

As a solution I set the MyBatisProperties to prototype scope, so that a new properties object with a new configuration object is created on each injection. This is necessary, beause I dont want to write a copy method and org.apache.ibatis.session.Configuration does not provide a copy constructor.

```<code>@Bean
@Primary
@Scope("prototype")
public MybatisProperties myBatisProperties() {
  return new MybatisProperties();
}
</code>```

Now I could also apply the configuration and everything worked fine.

```<code>org.apache.ibatis.session.Configuration tmpConfiguration = properties.getConfiguration();
factoryBean.setConfiguration(tmpConfiguration);
</code>```

Body:
This one is really puzzling me. I have a Spring Boot (2.1.2) app where I am managing two data sources via MyBatis and Spring. I have multiple MyBatis mappers and each one is configured to use a particular data source. The code for that configuration is below:

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
public class MyBatisConfig {

    private static final String POSTGRES_SESSION_FACTORY = "postgresSessionFactory";
    private static final String MYSQL_SESSION_FACTORY = "mySqlDbSessionFactory";

    @Bean(name = POSTGRES_SESSION_FACTORY, destroyMethod = "")
    @Primary
    public SqlSessionFactoryBean postgresSessionFactory(
            @Qualifier(DataSourceConfig.PRIMARY_DATA_SOURCE) final DataSource oneDataSource,
            ApplicationContext applicationContext) throws Exception {
        final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setConfigLocation(applicationContext.getResource("classpath:mybatis-config.xml"));
        sqlSessionFactoryBean.setDataSource(oneDataSource);
        SqlSessionFactory sqlSessionFactory;
        sqlSessionFactory = sqlSessionFactoryBean.getObject();
        sqlSessionFactory.getConfiguration().addMapper(Mapper1.class);
        sqlSessionFactory.getConfiguration().addMapper(Mapper2.class);

        return sqlSessionFactoryBean;
    }

    @Bean(name = MYSQL_SESSION_FACTORY, destroyMethod = "")
    public SqlSessionFactoryBean mySqlSessionFactory(
            @Qualifier(DataSourceConfig.SECONDARY_DATA_SOURCE) final DataSource anotherDataSource,
            ApplicationContext applicationContext) throws Exception {
        final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setConfigLocation(applicationContext.getResource("classpath:mybatis-config-sql.xml"));
        sqlSessionFactoryBean.setDataSource(anotherDataSource);
        final SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
        sqlSessionFactory.getConfiguration().addMapper(Mapper3.class);
        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperFactoryBean<Mapper1> accountMapperFactory(@Qualifier(POSTGRES_SESSION_FACTORY) final SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {
        MapperFactoryBean<Mapper1> factoryBean = new MapperFactoryBean<>(Mapper1.class);
        factoryBean.setSqlSessionFactory(sqlSessionFactoryBean.getObject());
        return factoryBean;
    }

    @Bean
    public MapperFactoryBean<Mapper2> domainMapperFactory(@Qualifier(POSTGRES_SESSION_FACTORY) final SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {
        MapperFactoryBean<Mapper2> factoryBean = new MapperFactoryBean<>(Mapper2.class);
        factoryBean.setSqlSessionFactory(sqlSessionFactoryBean.getObject());
        return factoryBean;
    }

    @Bean
    public MapperFactoryBean<Mapper3> usageMapperFactory(@Qualifier(MYSQL_SESSION_FACTORY) final SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {
        MapperFactoryBean<Mapper3> factoryBean = new MapperFactoryBean<>(Mapper3.class);
        factoryBean.setSqlSessionFactory(sqlSessionFactoryBean.getObject());
        return factoryBean;
    }
}

If I use my debugger, I can very that at the time these beans are being initialized, all of them are pointing to the correct data source. (Mapper1 and Mapper2's SqlSessionFactorys connect to the postgres datasource, Mapper3's SqlSessionFactory connects to the mysql datasource.

But strangely, when they are injected into a service, all three Mappers are connected to the postgres datasource. I am beyond confused at this point.

The service and injection are quite simple:

@Autowired private Mapper1 mapper1;
@Autowired private Mapper2 mapper2;
@Autowired private Mapper3 mapper3;

However when I call the service and stop it with the debugger, I can see that mapper3 is connected to the wrong datasource (postgres).

Any ideas? Any more information needed?

Body:
I had the same effects, when configuring multiple datasources with MyBatis. At runtime, all mappers were using the last defined datasource connection credentials, although during startup everything looked fine.

I could narrow the problem down to the factoryBean definition and setting the configuration. As it seems, the configuration object is shared among all datasources (as I set them here), because I set the same instance from the MyBatisProperties. During runtime the configuration is also the place where MyBatis gets the datasource from the Environment property.

The "magic" happens on factoryBean.getObject() and factoryBean.buildSqlSessionFactory(). Here, the datasource is set into the configuration. When the configuration was not explicitly set, then a new default one is created. Otherwise, the configuration object is reused. Thus when initializing several factory beans with the same configuration object, then the configuration object gets every datasource injected and the last datasource remains.

This might be a bug, because as a Mybatis user I expect Mybatis to use the datasource I provide with factoryBean.setDataSource(aDatasource) So, when I commented out factoryBean.setConfiguration, then everything works as intended, but of course my configuration is not applied.

@Bean("sqlSessionFactoryA")
public SqlSessionFactory sqlSessionFactory(@Qualifier("datasourceA") DataSource aDataSource) throws Exception {
  SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
  factoryBean.setDataSource(aDataSource);
  factoryBean.setConfigurationProperties(properties.getConfigurationProperties());
//    factoryBean.setConfiguration(properties.getConfiguration());
  return factoryBean.getObject();
}

As a solution I set the MyBatisProperties to prototype scope, so that a new properties object with a new configuration object is created on each injection. This is necessary, beause I dont want to write a copy method and org.apache.ibatis.session.Configuration does not provide a copy constructor.

@Bean
@Primary
@Scope("prototype")
public MybatisProperties myBatisProperties() {
  return new MybatisProperties();
}

Now I could also apply the configuration and everything worked fine.

org.apache.ibatis.session.Configuration tmpConfiguration = properties.getConfiguration();
factoryBean.setConfiguration(tmpConfiguration);


问:
Smooth scroll of the menu
I have a menu with 2 levels. When i want to scroll down i want to change the position of Logo to the bottom menu. I want a smooth scroll, but now when i scroll down i can see a shake of the menu in process of scrolling, basically is not smooth.

window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
    document.querySelector(".nav1").style.fontSize = "25px";
    document.querySelector("h4").style.position = "relative";
    document.querySelector("h4").style.top = "55px";
    document.querySelector(".menu").style.position = "fixed";

  } else {
     document.querySelector(".nav1").style.fontSize = "20px";
    document.querySelector("h4").style.position = "relative";
    document.querySelector("h4").style.top = "0px";
    document.querySelector(".menu").style.position = "relative";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.menu {
  background:gray;
}
.menu, .nav1 {
  width:100%;
  transition: all 0.6s ease;

}
.nav1 >h4 {
  border:2px solid blue;
  width:50px;
    transition: all 0.6s ease;

}
.nav2>ul {
  display:flex;
  justify-content:space-evenly;
  border:2px solid red;
}</code>```

Logo

list

list

list

list

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

```

What could be the issue and how to solve it?

答:
You can use position: sticky on .menu.

Note here: sticky doesnt work in IE

window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
    document.querySelector(".nav1").style.fontSize = "25px";
    document.querySelector("h4").style.position = "relative";
    document.querySelector("h4").style.top = "55px";

  } else {
     document.querySelector(".nav1").style.fontSize = "20px";
    document.querySelector("h4").style.position = "relative";
    document.querySelector("h4").style.top = "0px";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.menu {
  background:gray;
  position: sticky;
  top: 0;
}
.menu, .nav1 {
  width:100%;
  transition: all 0.6s ease;

}
.nav1 >h4 {
  border:2px solid blue;
  width:50px;
    transition: all 0.6s ease;

}
.nav2>ul {
  display:flex;
  justify-content:space-evenly;
  border:2px solid red;
}</code>```

Logo

list

list

list

list

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

```

Title: Smooth scroll of the menu

Body:
I have a menu with 2 levels. When i want to scroll down i want to change the position of Logo to the bottom menu. I want a smooth scroll, but now when i scroll down i can see a shake of the menu in process of scrolling, basically is not smooth.

window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
    document.querySelector(".nav1").style.fontSize = "25px";
    document.querySelector("h4").style.position = "relative";
    document.querySelector("h4").style.top = "55px";
    document.querySelector(".menu").style.position = "fixed";

  } else {
     document.querySelector(".nav1").style.fontSize = "20px";
    document.querySelector("h4").style.position = "relative";
    document.querySelector("h4").style.top = "0px";
    document.querySelector(".menu").style.position = "relative";
  }
}

.menu {
  background:gray;
}
.menu, .nav1 {
  width:100%;
  transition: all 0.6s ease;

}
.nav1 >h4 {
  border:2px solid blue;
  width:50px;
    transition: all 0.6s ease;

}
.nav2>ul {
  display:flex;
  justify-content:space-evenly;
  border:2px solid red;
}

Logo

list

list

list

list

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

content

What could be the issue and how to solve it?

Body:
You can use position: sticky on .menu.

Note here: sticky doesnt work in IE

window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
    document.querySelector(".nav1").style.fontSize = "25px";
    document.querySelector("h4").style.position = "relative";
    document.querySelector("h4").style.top = "55px";

  } else {
     document.querySelector(".nav1").style.fontSize = "20px";
    document.querySelector("h4").style.position = "relative";
    document.querySelector("h4").style.top = "0px";
  }
}

.menu {
  background:gray;
  position: sticky;
  top: 0;
}
.menu, .nav1 {
  width:100%;
  transition: all 0.6s ease;

}
.nav1 >h4 {
  border:2px solid blue;
  width:50px;
    transition: all 0.6s ease;

}
.nav2>ul {
  display:flex;
  justify-content:space-evenly;
  border:2px solid red;
}

<div class="menu">
  <div class="nav1">
    <h4>Logo</h4>
  </div>
  <div class="nav2">
    <ul>
    <li>list</li>
    <li>list</li>
    <li>list</li>
    <li>list</li></ul>
  </div>
</div>
<div class="content">
  <ul>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
  </ul>
</div>


问:
Copying a file to another Project's Debug folder in the Post Build Event
This is driving me insane. With Prism's Modularity Quickstart, building a Module moves it to the main application's bin\Debug folder. When I try to do the same, the file goes to the application's bin\Release folder. What am I doing wrong??

Post-Build Event

```<code>xcopy "$(TargetDir)MyModule.dll"
      "$(SolutionDir)MainApplication\bin\$(ConfigurationName)\Modules\" /Y
</code>```

答:
The $(ConfigurationName) tag will contain the name of the current Solution Configuration.

You can change the solution configuration you are building under by going to Build -> Configuration Manager and change the Active Solution Configuration to "Debug". Alternatively there is a dropdown at the top of Visual Studio with this as well.

Body:
This is driving me insane. With Prism's Modularity Quickstart, building a Module moves it to the main application's bin\Debug folder. When I try to do the same, the file goes to the application's bin\Release folder. What am I doing wrong??

Post-Build Event

xcopy "$(TargetDir)MyModule.dll"
      "$(SolutionDir)MainApplication\bin\$(ConfigurationName)\Modules\" /Y


问:
Jooq text array generated as object array
given the following sql

create table something(
  id BIGSERIAL,
  something TEXT[] NOT NULL DEFAULT '{}',
  PRIMARY KEY (id)
);
```

<p>and instructing the code generator to use DDLDatabase
the generated item is in the form of </p>

<pre class="lang-java prettyprint-override"><code>    public final TableField<JSomethingRecord, Object[]> SOMETHING_
</code>```

Looking around in the documentation I cannot find how can this be mapped in a String[].
same applies for varchar and varchar(255).
I shouldn't have to use an enforced type here as at least on of the three should be a valid datatype
and not fallback to OTHER as it happens with the UUID (for which I saw there is an example for enforced types)

Am I doing / understanding something wrong or this is an expected behaviour?

The database I am using is PostGres and the generator configuration is the following

<generator>
    <database>
        <name>org.jooq.meta.extensions.ddl.DDLDatabase</name>
        <inputCatalog/>
        <inputSchema>PUBLIC</inputSchema>
        <properties>
            <property>
                <key>use-attribute-converters</key>
                <value>true</value>
            </property>
            <property>
                <key>scripts</key>
                <value>src/main/resources/db/migration/*</value>
            </property>
        </properties>
    </database>
    <target>
        <clean>true</clean>
        <packageName>my.other.package</packageName>
        <directory>target/generated-sources/jooq</directory>
    </target>
</generator>
```

Thank you in advance

答:
As of jOOQ 3.13, PostgreSQL's typed arrays are not yet supported by the DDLDatabase, because the current implementation of the DDLDatabase translates your DDL to H2 behind the scenes, and H2 1.4.200's ARRAY type does not support any other type of array than Object[].

This will change in the future, as:

H2 1.4.201 will support typed arrays like PostgreSQL: https://github.com/h2database/h2database/issues/1390

jOOQ will support running your DDL on an actual PostgreSQL database in test containers: https://github.com/jOOQ/jOOQ/issues/6551

jOOQ will support interpreting the DDL instead of running it on a third party database product: https://github.com/jOOQ/jOOQ/issues/7034

Until then, in order to use such PostgreSQL-specific features, I recommend using the classic approach of connecting to an actual PostgreSQL database instance.

Body:
given the following sql

create table something(
  id BIGSERIAL,
  something TEXT[] NOT NULL DEFAULT '{}',
  PRIMARY KEY (id)
);

and instructing the code generator to use DDLDatabase
the generated item is in the form of

    public final TableField<JSomethingRecord, Object[]> SOMETHING_

Looking around in the documentation I cannot find how can this be mapped in a String[].
same applies for varchar and varchar(255).
I shouldn't have to use an enforced type here as at least on of the three should be a valid datatype
and not fallback to OTHER as it happens with the UUID (for which I saw there is an example for enforced types)

Am I doing / understanding something wrong or this is an expected behaviour?

The database I am using is PostGres and the generator configuration is the following

<generator>
    <database>
        <name>org.jooq.meta.extensions.ddl.DDLDatabase</name>
        <inputCatalog/>
        <inputSchema>PUBLIC</inputSchema>
        <properties>
            <property>
                <key>use-attribute-converters</key>
                <value>true</value>
            </property>
            <property>
                <key>scripts</key>
                <value>src/main/resources/db/migration/*</value>
            </property>
        </properties>
    </database>
    <target>
        <clean>true</clean>
        <packageName>my.other.package</packageName>
        <directory>target/generated-sources/jooq</directory>
    </target>
</generator>

Thank you in advance


问:
why google Admob ads not showing up
I just create an android app and wants to integrate ads from my google AdMob account. but Ads do not show up.

But when I test my app from the developer's guidance as they provide sample id's for banner and interstitial ads and also for app id the app work fine but as soon as I put banner id, interstitial ads id and app id from my Admob account then the problem occurred. I did not publish my app till now to play store and I just created my AdMob account does it take time to verify or any suggestion why ads not showing up.

答:
some common issues are :

Make sure you have updated AdMob with your payment details.

Make sure that the ads you created in AdMob are banner ads.

Check your AdMob dashboard to see the status of your ads, are they active?

Verify you used the correct Ad Unit Id.

Give it 24 hours, it can take time for an ad to become active in your
region

if you do not have traffic on your app Admob will not show ads on your app and if you Will publish your app on play store then AdMob will show ads on your app without traffic read New (privacy policy) if you link your app (published on play store) with Admob then your account will not be suspended directly AdMob will always give you a warning

Title: why google Admob ads not showing up


问:
sed replace 1 line in file with all lines in file
Lets say I have a line #SYM

I need to replace it with all lines from file1.txt

Is it possible to do that with sed?

I have tried sed 's/#SYM/file1.txt/' updater

But that doesn't work, because I need to load file1.txt as string, and I do not know how to do that.

EDIT: I believe that there could be a way to do it in a shell script somehow.

EDIT2: I also just tried this:

#!/bin/bash
value=$(<tools/symlink)
sed -i 's/#SYM/$value/' META-INF/com/google/android/updater-script

答:
Use r command:

```<code>sed -e '/#SYM/ {r tools/symlink' -e 'd}' META-INF/com/google/android/updater-script
</code>```

/#SYM/ {r tools/symlink if a line contains #SYM, append the contents of tools/symlink

d} then delete the matching line

the two commands are separated using -e option because everything after r is considered as part of filename

Add the -i option once you are satisifed that it is working

Body:
Use r command:

sed -e '/#SYM/ {r tools/symlink' -e 'd}' META-INF/com/google/android/updater-script

/#SYM/ {r tools/symlink if a line contains #SYM, append the contents of tools/symlink

d} then delete the matching line

the two commands are separated using -e option because everything after r is considered as part of filename

Add the -i option once you are satisifed that it is working


问:
Java: How do you enforce a class type parameter to be the same as generic type specified in a generic method?
I created a NotificationManager class, which let's you register a generic listener to some generic notification service. In the NotificationManager class I have a generic method for registering a listener with a service:

```<code>public static <E> void registerNotify(Class<E> type, INotificationListener<E> listener) {
    @SuppressWarnings("unchecked")
    INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
    service.registerNotificationListener(listener);
}
</code>```

So, for some INotificationListener of a particular type I'd like to force the user, when calling this method, to specify the same type as the listener. The type maps to all the INotificationListeners of the same type, however this method doesn't enforce what I'm trying to enforce. For example, I could call:

```<code>INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(String.class, locationListener);
</code>```

and the code compiles fine. What I thought this would enforce is the following:

```<code>INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(Location.class, locationListener);
</code>```

Any ideas on how to accomplish this?

Update:

Sorry for the mixup, the above does in fact work. The method in the same class which does not work is actually the following:

```<code>public static <E> void broadcastNotify(Class<E> type, E data)
    {
        @SuppressWarnings("unchecked")
        INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
        service.notifyListeners(data);
    }
</code>```

And calling:

```<code>Location location = new Location();
NotificationManager.broadcastNotify(Object.class, location);
</code>```

Does not cause a compilation error, which is what I would like it to do.

答:
Location is an Object - I believe it becomes:

```<code>public static <Object> void broadcastNotify(Class<Object> type, Object data)
</code>```

Remember in java all objects inherit from Object.

Body:
I created a NotificationManager class, which let's you register a generic listener to some generic notification service. In the NotificationManager class I have a generic method for registering a listener with a service:

public static <E> void registerNotify(Class<E> type, INotificationListener<E> listener) {
    @SuppressWarnings("unchecked")
    INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
    service.registerNotificationListener(listener);
}

So, for some INotificationListener of a particular type I'd like to force the user, when calling this method, to specify the same type as the listener. The type maps to all the INotificationListeners of the same type, however this method doesn't enforce what I'm trying to enforce. For example, I could call:

INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(String.class, locationListener);

and the code compiles fine. What I thought this would enforce is the following:

INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(Location.class, locationListener);

Any ideas on how to accomplish this?

Update:

Sorry for the mixup, the above does in fact work. The method in the same class which does not work is actually the following:

public static <E> void broadcastNotify(Class<E> type, E data)
    {
        @SuppressWarnings("unchecked")
        INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
        service.notifyListeners(data);
    }

And calling:

Location location = new Location();
NotificationManager.broadcastNotify(Object.class, location);

Does not cause a compilation error, which is what I would like it to do.

Body:
Location is an Object - I believe it becomes:

public static <Object> void broadcastNotify(Class<Object> type, Object data)

Remember in java all objects inherit from Object.


问:
not able to understand scope of variable in this code
In this code vid is initialized inside the function, so how can it be used outside the function
( i.e how could vid.play() know that vid is initialised using vid = document.querySelector("#myPlayer")).

```<code>window.onload = init;

let vid;
function init() {
  console.log('page loaded, DOM is ready');
  vid = document.querySelector('#myPlayer');
  vid.ontimeupdate = displayTimeWhileVideoIsPlaying();
}

function playVideo() {
  vid.play();
}
</code>```

答:
It can't, it will simply look at the let vid; variable. You have 2 possible scenario's here.

init() is called before playVideo():

At the time vid.play() is called, your vid variable holds your video
as init initialized it.

playVideo() is called before init():

At the time vid.play() is called, your vid variable will be undefined and thus throw an error.

Body:
In this code vid is initialized inside the function, so how can it be used outside the function
( i.e how could vid.play() know that vid is initialised using vid = document.querySelector("#myPlayer")).

window.onload = init;

let vid;
function init() {
  console.log('page loaded, DOM is ready');
  vid = document.querySelector('#myPlayer');
  vid.ontimeupdate = displayTimeWhileVideoIsPlaying();
}

function playVideo() {
  vid.play();
}


问:
How I can call a post function with a link
I have a navbar, and I want to have also a tag where I can call my post function. The problem is that I don't know how to call it with a link. If you see to my navbar code, you see that I am working with links.

Here is my post function

```<code>app.post('/logout', (req, res) => {
    if (req.session) {
        try{
            console.log(`${req.session.userdata.name} logged out at ${getTime()} at the devide ${req.ip.slice(7)} ${req.ips}`)
        } catch(error){
            console.log(`"Err" logged out at ${getTime()} at the devide ${req.ip.slice(7)} ${req.ips}`);
        }
        req.session.destroy(function(err) {
            if(err) {
                return next(err);
            } else {
                return res.redirect('/');
            };
        });
    };
});
</code>```

And here is my navbar code

```<code><div class="navbar">
    <a class="active" href="/user/:id/home">Home</a>
    <a href="/">Login</a>
    <a href="/info">Info</a>
</div>
</code>```

I also tried this

```<code><form action="/logout" method="post">
  <a href="#" id = "logout" title="save logout"><i class="fa fa-fw fa-power-off"> </i>Logout</a>
</form>
</code>```

答:
You should listen to the click event of the link, And submit the form using javascript.

Here I am using JQuery,

$('#logout').click(function(e){

  e.preventDefault();
  $('#logout_form').submit();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form action="/logout" method="post" id='logout_form'>

     <i class="fa fa-fw fa-power-off"> </i>Logout

</form></code>```

Body:
I have a navbar, and I want to have also a tag where I can call my post function. The problem is that I don't know how to call it with a link. If you see to my navbar code, you see that I am working with links.

Here is my post function

app.post('/logout', (req, res) => {
    if (req.session) {
        try{
            console.log(`${req.session.userdata.name} logged out at ${getTime()} at the devide ${req.ip.slice(7)} ${req.ips}`)
        } catch(error){
            console.log(`"Err" logged out at ${getTime()} at the devide ${req.ip.slice(7)} ${req.ips}`);
        }
        req.session.destroy(function(err) {
            if(err) {
                return next(err);
            } else {
                return res.redirect('/');
            };
        });
    };
});

And here is my navbar code

    Home
    Login
    Info

I also tried this

<form action="/logout" method="post">
   Logout
</form>

Body:
You should listen to the click event of the link, And submit the form using javascript.

Here I am using JQuery,

$('#logout').click(function(e){

  e.preventDefault();
  $('#logout_form').submit();

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form action="/logout" method="post" id='logout_form'>
  <a href="#" id="logout" title="save logout">
     <i class="fa fa-fw fa-power-off"> </i>Logout
  </a>
</form>


问:
Laravel display SEO tag automatically through Route name
I have question about Laravel.

I want display SEO tag automatically from Database but I do not know how to do.

I have route like this

```<code>Route::get('/', [
    'uses' => 'SeoController@index',
    'as' => 'homepage'
]);
Route::get('/about', [
    'uses' => 'SeoController@index',
    'as' => 'about'
]);
</code>```

From SeoController I want to display view base on Route url;

```<code>public function index()
    {
        switch ($route) {
            case '/':
                $title = "Homepage";
                return view('welcome', ['title'=> $title]);
                break;
            case '/about':
                $title = "About page";
                return view('about', ['title'=> $title]);
                break;
            default:
                break;
        }
    }
</code>```

How can I check $route to know which route come?

Thank you so much

答:
I would love to suggest a better way of doing this in Laravel.

In Laravel, you would want to define different controller methods for each pages and return a view like so:

```<code>class SeoController extends Controller
{
    public function home()
    {
        return view('home');
    }

     public function about()
    {
        return view('about');
    }

    public function contact()
    {
        return view('contact');
    }
}
</code>```

Ensure you have the routes registered in web.php as:

```<code>Route::get('/', [
    'uses' => 'SeoController@home',
    'as' => 'homepage'
]);

Route::get('/about', [
    'uses' => 'SeoController@about',
    'as' => 'about'
]);

Route::get('/contact', [
    'uses' => 'SeoController@contact',
    'as' => 'contact'
]);
</code>```

And also ensure you have the corresponding blade file for each of these views in the view folder.

Body:
I have question about Laravel.

I want display SEO tag automatically from Database but I do not know how to do.

I have route like this

Route::get('/', [
    'uses' => 'SeoController@index',
    'as' => 'homepage'
]);
Route::get('/about', [
    'uses' => 'SeoController@index',
    'as' => 'about'
]);

From SeoController I want to display view base on Route url;

public function index()
    {
        switch ($route) {
            case '/':
                $title = "Homepage";
                return view('welcome', ['title'=> $title]);
                break;
            case '/about':
                $title = "About page";
                return view('about', ['title'=> $title]);
                break;
            default:
                break;
        }
    }

How can I check $route to know which route come?

Thank you so much

Body:
I would love to suggest a better way of doing this in Laravel.

In Laravel, you would want to define different controller methods for each pages and return a view like so:

class SeoController extends Controller
{
    public function home()
    {
        return view('home');
    }

     public function about()
    {
        return view('about');
    }

    public function contact()
    {
        return view('contact');
    }
}

Ensure you have the routes registered in web.php as:

Route::get('/', [
    'uses' => 'SeoController@home',
    'as' => 'homepage'
]);

Route::get('/about', [
    'uses' => 'SeoController@about',
    'as' => 'about'
]);

Route::get('/contact', [
    'uses' => 'SeoController@contact',
    'as' => 'contact'
]);

And also ensure you have the corresponding blade file for each of these views in the view folder.


答:
Check the value of vid like this

```<code>if (vid) {
 vid.play();
} else {
  alert('Video not initialized')
}
</code>```

Title: not able to understand scope of variable in this code

Body:
Check the value of vid like this

if (vid) {
 vid.play();
} else {
  alert('Video not initialized')
}


问:
Unit testing a RecyclerView Adapter throws NullPointerException when accessing mObservables
My view model holds a very simple recyclerview adapter

When I try to send it messages (which in turn calls notifyDatasetChanged) it throws an exception like so

```<code>java.lang.NullPointerException
at androidx.recyclerview.widget.RecyclerView$AdapterDataObservable.notifyChanged(RecyclerView.java:11996)
at
</code>```

the problem is that the mObservers variable from AdapterDataObservable is null

the thing is that this extends Observable<AdapterDataObserver> which in turn defines mObservers as

```<code>protected final ArrayList<T> mObservers = new ArrayList<T>();
</code>```

so basically the moment my adapter is instantiated , it will call

```<code>private final AdapterDataObservable mObservable = new AdapterDataObservable();
</code>```

(which is called by the way, mObservable is not null)

which in turn should call mObservers = new ArrayList<T>();

can someone explain why this is never called? or if there is a way to get past this problem?

as a side note the adapter is not mocked it is a solid object.

Edit:

Here is the code of the tests I'm using:

```<code>class LoginViewModelTest {

     private lateinit var vm: LoginViewModel

        @get:Rule
        val rule = InstantTaskExecutorRule()

        @Before
        fun setUp() {

            whenever(settings.hasShownWelcome).thenReturn(false)
            whenever(settings.serverIp).thenReturn("http://127.0.0.1")

            //this is where the crash happens
            vm = LoginViewModel(settings, service, app, TestLog, TestDispatchers) { p -> permissionGranted }
        }
</code>```

And below is the code that is tested:

```<code>class LoginViewModel(private val settings: ISettings, private val service: AppService, application: Application, l: ILog, dispatchers: IDispatchers, val permissionChecker: (String) -> Boolean) :  BaseViewModel(application, l, dispatchers)

    val stepAdapter :StepAdapter

    init {
        val maxSteps = calculateSteps()
        //after this assignment, during the normal run, the stepAdapter.mObservable.mObservers is an empty array
        //during unit tests, after this assignment it is null
        stepAdapter = StepAdapter(maxSteps)
    }
</code>```

答:
i don't know if you have already found a solution or not, but this is for other people like me who ran into a similar problem:

make the test an android test (aka instrumented test) and not a unit test.

while i cannot fully explain why, it seems that when notifying an adapter about a change (notifyItemChanged(), notifyDataSetChanged() etc.) something about the inner logic of android requires an actual RecyclerView/adapter to receive the message.

once i moved my test from the Test folder to the AndroidTest folder, the problem was fixed.

P.S.

make sure to remove your old build configuration! android studio keeps referring to the old one (in the Test folder) and if you don't remove it you will receive a classNotFound error

Body:
My view model holds a very simple recyclerview adapter

When I try to send it messages (which in turn calls notifyDatasetChanged) it throws an exception like so

java.lang.NullPointerException
at androidx.recyclerview.widget.RecyclerView$AdapterDataObservable.notifyChanged(RecyclerView.java:11996)
at

the problem is that the mObservers variable from AdapterDataObservable is null

the thing is that this extends Observable<AdapterDataObserver> which in turn defines mObservers as

protected final ArrayList<T> mObservers = new ArrayList<T>();

so basically the moment my adapter is instantiated , it will call

private final AdapterDataObservable mObservable = new AdapterDataObservable();

(which is called by the way, mObservable is not null)

which in turn should call mObservers = new ArrayList<T>();

can someone explain why this is never called? or if there is a way to get past this problem?

as a side note the adapter is not mocked it is a solid object.

Edit:

Here is the code of the tests I'm using:

class LoginViewModelTest {

     private lateinit var vm: LoginViewModel

        @get:Rule
        val rule = InstantTaskExecutorRule()

        @Before
        fun setUp() {

            whenever(settings.hasShownWelcome).thenReturn(false)
            whenever(settings.serverIp).thenReturn("http://127.0.0.1")

            //this is where the crash happens
            vm = LoginViewModel(settings, service, app, TestLog, TestDispatchers) { p -> permissionGranted }
        }

And below is the code that is tested:

class LoginViewModel(private val settings: ISettings, private val service: AppService, application: Application, l: ILog, dispatchers: IDispatchers, val permissionChecker: (String) -> Boolean) :  BaseViewModel(application, l, dispatchers)

    val stepAdapter :StepAdapter

    init {
        val maxSteps = calculateSteps()
        //after this assignment, during the normal run, the stepAdapter.mObservable.mObservers is an empty array
        //during unit tests, after this assignment it is null
        stepAdapter = StepAdapter(maxSteps)
    }