问:
IllegalArgumentException: Invalid column DISTINCT bucket_display_name
I'm retrieving list of distinct folders list having video files with number of videos in each folder, and this is working fine in devices having Android P and below, but when I run on devices having Android Q the app crashes.
How can I make it work for devices running Android Q

java.lang.IllegalArgumentException: Invalid column DISTINCT
  bucket_display_name

Logcat:

```<code>java.lang.IllegalArgumentException: Invalid column DISTINCT bucket_display_name
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:170)
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
        at android.content.ContentProviderProxy.query(ContentProviderNative.java:423)
        at android.content.ContentResolver.query(ContentResolver.java:944)
        at android.content.ContentResolver.query(ContentResolver.java:880)
        at android.content.ContentResolver.query(ContentResolver.java:836)
        at com.aisar.mediaplayer.fragments.VideoFolderFragment$MediaQuery.getAllVideo(VideoFolderFragment.java:364)
        at com.aisar.mediaplayer.fragments.VideoFolderFragment$VideosLoader.loadVideos(VideoFolderFragment.java:434)
        at com.aisar.mediaplayer.fragments.VideoFolderFragment$VideosLoader.access$1100(VideoFolderFragment.java:413)
        at com.aisar.mediaplayer.fragments.VideoFolderFragment$5.run(VideoFolderFragment.java:189)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
</code>```

My Code:

```<code>public class MediaQuery {
        private Context context;
        private int count = 0;
        private Cursor cursor;
        List<ModelVideoFolder> videoItems;

        public MediaQuery(Context context) {
            this.context = context;
        }

        public List<ModelVideoFolder> getAllVideo(String query) {
            String selection = null;
            String[] projection = {
                    "DISTINCT " + MediaStore.Video.Media.BUCKET_DISPLAY_NAME,
                    MediaStore.Video.Media.BUCKET_ID
            };
            cursor = context.getContentResolver().query(
                    MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                    projection,
                    selection,
                    null,
                    query);
            videoItems = new ArrayList<>();
            ModelVideoFolder videoItem;
            while (cursor.moveToNext()) {
                videoItem = new ModelVideoFolder(
                        "" + cursor.getString(1),
                        "" + cursor.getString(0),
                        "",
                        "",
                        "" + getVideosCount(cursor.getString(1))
                );
                videoItems.add(videoItem);
            }
            return videoItems;
        }

        public int getVideosCount(String BUCKET_ID) {
            int count = 0;
            String selection = null;
            String[] projection = {
                    MediaStore.Video.Media.BUCKET_ID,
            };
            Cursor cursor = getActivity().getContentResolver().query(
                    MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                    projection,
                    selection,
                    null,
                    null);
            while (cursor.moveToNext()) {
                if (BUCKET_ID.equals(cursor.getString(0))) {
                    //add only those videos that are in selected/chosen folder
                    count++;
                }
            }
            return count;
        }
    }
</code>```

答: I was facing the same problem. DISTINCT keyword doesn't work in Android 10, use hashset for distinct.

Body:
I'm retrieving list of distinct folders list having video files with number of videos in each folder, and this is working fine in devices having Android P and below, but when I run on devices having Android Q the app crashes.
How can I make it work for devices running Android Q

java.lang.IllegalArgumentException: Invalid column DISTINCT
  bucket_display_name

Logcat:

java.lang.IllegalArgumentException: Invalid column DISTINCT bucket_display_name
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:170)
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
        at android.content.ContentProviderProxy.query(ContentProviderNative.java:423)
        at android.content.ContentResolver.query(ContentResolver.java:944)
        at android.content.ContentResolver.query(ContentResolver.java:880)
        at android.content.ContentResolver.query(ContentResolver.java:836)
        at com.aisar.mediaplayer.fragments.VideoFolderFragment$MediaQuery.getAllVideo(VideoFolderFragment.java:364)
        at com.aisar.mediaplayer.fragments.VideoFolderFragment$VideosLoader.loadVideos(VideoFolderFragment.java:434)
        at com.aisar.mediaplayer.fragments.VideoFolderFragment$VideosLoader.access$1100(VideoFolderFragment.java:413)
        at com.aisar.mediaplayer.fragments.VideoFolderFragment$5.run(VideoFolderFragment.java:189)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)

My Code:

public class MediaQuery {
        private Context context;
        private int count = 0;
        private Cursor cursor;
        List<ModelVideoFolder> videoItems;

        public MediaQuery(Context context) {
            this.context = context;
        }

        public List<ModelVideoFolder> getAllVideo(String query) {
            String selection = null;
            String[] projection = {
                    "DISTINCT " + MediaStore.Video.Media.BUCKET_DISPLAY_NAME,
                    MediaStore.Video.Media.BUCKET_ID
            };
            cursor = context.getContentResolver().query(
                    MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                    projection,
                    selection,
                    null,
                    query);
            videoItems = new ArrayList<>();
            ModelVideoFolder videoItem;
            while (cursor.moveToNext()) {
                videoItem = new ModelVideoFolder(
                        "" + cursor.getString(1),
                        "" + cursor.getString(0),
                        "",
                        "",
                        "" + getVideosCount(cursor.getString(1))
                );
                videoItems.add(videoItem);
            }
            return videoItems;
        }

        public int getVideosCount(String BUCKET_ID) {
            int count = 0;
            String selection = null;
            String[] projection = {
                    MediaStore.Video.Media.BUCKET_ID,
            };
            Cursor cursor = getActivity().getContentResolver().query(
                    MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                    projection,
                    selection,
                    null,
                    null);
            while (cursor.moveToNext()) {
                if (BUCKET_ID.equals(cursor.getString(0))) {
                    //add only those videos that are in selected/chosen folder
                    count++;
                }
            }
            return count;
        }
    }


来源: stackexchange

问:
if window.location.href has 'sometext' inside - do this
Currently working on something which uses ajax for some pagination. What I'm looking to do is add something like referal=3 to the end of some links then when they go to that link I'll insert a back button with the window location for example:

User uses the ajax pagination, goes to page 3 I'll add ?ref=3 to the end of the link or something so it would like this this:

http://foo.com/somepage/?ref=3

(not sure if that's a corrent way of doing it)

Then the user clicks that link and I'll append a back button on that page with that link.

So when they go back to the homepage using the generated button the window.location.href will be:

http://foo.com?ref=3

The idea is that when they click that back button, the ajax pagination will load to page 3.

I'm not sure how else to explain this, but does anyone know how I would go about doing a conditional statement dependant on the window.location.href?

答:
You can use this function to get parts of the query string:

```<code>function getQueryString(variable){
    // Grab the query string part of the URL (everything after the ?)
    var query = window.location.search.substring(1);

    // If you don't specify which value you want, return the whole thing
    if(!variable) return query;

    // Split the query string to key=value pairs into an array
    var vars = query.split('&');

    // Loop through them to find the one we're looking for
    for (var i = 0; i < vars.length; i++){
        // Split key and value
        var pair = vars[i].split('=');

        // If the key matches our parameter, return the value
        if (pair[0] == variable){
            return pair[1];
        }
    }
    // If not found, return empty string
    return '';
}
</code>```

Then you can get the value as a string by:

```<code>var value = getQueryString('ref');

// Conditional code if it is a certain value, do something
if(value === '3'){
    // Do something
}
</code>```

You can also get it as a number by using parseInt():

```<code>var value = parseInt(getQueryString('ref'), 10);

if(value === 3){
    // Do something
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use this function to get parts of the query string:

function getQueryString(variable){
    // Grab the query string part of the URL (everything after the ?)
    var query = window.location.search.substring(1);

    // If you don't specify which value you want, return the whole thing
    if(!variable) return query;

    // Split the query string to key=value pairs into an array
    var vars = query.split('&');

    // Loop through them to find the one we're looking for
    for (var i = 0; i < vars.length; i++){
        // Split key and value
        var pair = vars[i].split('=');

        // If the key matches our parameter, return the value
        if (pair[0] == variable){
            return pair[1];
        }
    }
    // If not found, return empty string
    return '';
}

Then you can get the value as a string by:

var value = getQueryString('ref');

// Conditional code if it is a certain value, do something
if(value === '3'){
    // Do something
}

You can also get it as a number by using parseInt():

var value = parseInt(getQueryString('ref'), 10);

if(value === 3){
    // Do something
}


问:
Set HTML <select> option value based on Node.js data
From my Node app I am trying to send a JSON array of MongoDB collection to client side HTML/AJAX. I want the Node.js data to reflect on a <select> or on a dropdown. The Node.js response object is sending 2 arrays hostArr and portArr I wish to concatenate the adjacent values and display it on select options. I have included my progress below, this for obvious reason doesn't work. Looking for a solution here..

app.js

```<code>MongoClient.connect(url,{ useUnifiedTopology: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mongoDetails");
    dbo.collection("mongoDetails").find({}).toArray(function(err, result) {
      if (err) throw err;
      var hostArr =[];
      var portArr =[];
      for(i=0;i<result.length;i++){
        hostArr.push(result[i].hostname);
      }
      for(i=0;i<result.length;i++){
        portArr.push(result[i].port);
      }
      console.log(hostArr);
      console.log(portArr);
      res.json({mongoDet1:hostArr, mongoDet2:portArr});
      db.close();
    });
  });
</code>```

Index.html

```<code><div >
    <select id="mongoDetails">
        <option value="1"></option>
        <option value="2"></option>
        <option value="3"></option>
    </select>
</div>

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url: "http://localhost:8070/api/route1",
            type: 'POST',
            dataType:'json',
            success: function(res) {
                console.log(res);
                $.each(res, function(key, value) {
                console.log(key);
                console.log(value);
                $("#mongoDetails").value(res.mongoDet1[value]+res.mongoDet2[value]);
            });
            }
        });
    });
</script>
</code>```

答:
To do this, you can use the following method:

```<code>MongoClient.connect(url,{ useUnifiedTopology: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mongoDetails");
    dbo.collection("mongoDetails").find({}).toArray(function(err, result) {
      if (err) throw err;

      var resultArr =[];

      for(i=0;i<result.length;i++){
        resultArr.push({
          hostname: result[i].hostname,
          port: result[i].port
        });
      }
      console.log(hostArr);
      res.json({content:resultArr});
      db.close();
    });
  });

<div>
    <select id="mongoDetails"></select>
</div>

<script type="text/javascript">
    $(document).ready(function(){
        var selectElement = document.getElementById('mongoDetails');
        $.ajax({
            url: "http://localhost:8070/api/route1",
            type: 'POST',
            dataType:'json',
            success: function(res) {
                console.log(res);
               res.content.forEach(item => {
                 console.log(item);
                   selectElement.options[selectElement.options.length] = new Option(item.hostname, item.port);
              });
            }
        });
    });
</script>
</code>```

This tutorial shows exactly what you need to do

also you can get <select> value with this code:

```<code>var value = document.getElementById("mongoDetails").value;
console.log(value);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
From my Node app I am trying to send a JSON array of MongoDB collection to client side HTML/AJAX. I want the Node.js data to reflect on a <select> or on a dropdown. The Node.js response object is sending 2 arrays hostArr and portArr I wish to concatenate the adjacent values and display it on select options. I have included my progress below, this for obvious reason doesn't work. Looking for a solution here..

app.js

MongoClient.connect(url,{ useUnifiedTopology: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mongoDetails");
    dbo.collection("mongoDetails").find({}).toArray(function(err, result) {
      if (err) throw err;
      var hostArr =[];
      var portArr =[];
      for(i=0;i<result.length;i++){
        hostArr.push(result[i].hostname);
      }
      for(i=0;i<result.length;i++){
        portArr.push(result[i].port);
      }
      console.log(hostArr);
      console.log(portArr);
      res.json({mongoDet1:hostArr, mongoDet2:portArr});
      db.close();
    });
  });

Index.html

    <select id="mongoDetails">
        <option value="1"></option>
        <option value="2"></option>
        <option value="3"></option>
    </select>

Body:
To do this, you can use the following method:

MongoClient.connect(url,{ useUnifiedTopology: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mongoDetails");
    dbo.collection("mongoDetails").find({}).toArray(function(err, result) {
      if (err) throw err;

      var resultArr =[];

      for(i=0;i<result.length;i++){
        resultArr.push({
          hostname: result[i].hostname,
          port: result[i].port
        });
      }
      console.log(hostArr);
      res.json({content:resultArr});
      db.close();
    });
  });

<div>
    <select id="mongoDetails"></select>
</div>

<script type="text/javascript">
    $(document).ready(function(){
        var selectElement = document.getElementById('mongoDetails');
        $.ajax({
            url: "http://localhost:8070/api/route1",
            type: 'POST',
            dataType:'json',
            success: function(res) {
                console.log(res);
               res.content.forEach(item => {
                 console.log(item);
                   selectElement.options[selectElement.options.length] = new Option(item.hostname, item.port);
              });
            }
        });
    });
</script>

This tutorial shows exactly what you need to do

also you can get <select> value with this code:

var value = document.getElementById("mongoDetails").value;
console.log(value);


问:
Azure DevOps & copying code base from one project to another or finding a better way of doing this
I'm seeking advice on the following:

In my development shop we support a SASS solution to our customers. We currently have 10 sites that we develop and provide technical support. We're a small team, just 2 of us. We're using Azure DevOps services to host and manage our code, right now we're just using it for a code repo. Within our organization, we multiple projects that represent site. Each site uses the same code base, except the web.config. The web.config is used to change the UI\theme for each customer. When we get a request to create a new site, we first create a new project site and then we copy our code base from the "golden copy" project.

We use a "golden copy" code base to make feature changes and bug fixes. Once we develop a new feature (or fix an issue) to the golden copy, and then we push it to test, QA beings testing. If testing is successful, then the development team copies the entire "golden copy" code files and copies the code to each site project, build and deploy to test for QA to ensure that site works with the new changes . This can be time consuming and prone to errors.

I would like to know the following:
 - Is there way in dev ops azure where we merge\copy from our golden
   copy to our other site project's repos?
 - Can you offer a better way for reorganizing our Organization\Projects
   setup based on our current setup\workflow.

Thank you,

答:
As Shayki mentioned, you can consider adopting Git branching strategy. Distributed version control systems like Git give you flexibility in how you use version control to share and manage code.

Keep your branch strategy simple. Build your strategy from these three concepts:

Use feature branches for all new features and bug fixes.

Merge feature branches into the master branch using pull requests.

Keep a high quality, up-to-date master branch.

A strategy that extends these concepts and avoids contradictions will result in a version control workflow for your team that is consistent and easy to follow. For details ,please refer to this official document.

Is there way in dev ops azure where we merge\copy from our golden copy
  to our other site project's repos?

For this issue , do you refer to synchronize the changes on the golden copy to other projects' repos? If so, I think it can only be done manually(copy the entire "golden copy" code files to each site project) or clone the entire repo into other projects through the following steps.

In other projects, select the Import repository option:


问:
Error 400 Bad request when getting Open Weather API (geolocation)
I want to get the weather API to display the current location but it gives back an 400 error. I don't know how to fix it.
(I open my api on browser and its works fine. But when I put it in the code bellow, it's gave error)</p>

```<code>state: {
        weather:{},
        api_key: 'c9f562aaffcdefaf40f2ed808d202c9b',
        url_base: 'https://api.openweathermap.org/data/2.5/',
        query: '',
        icons: {
            'Rain': require('../assets/regnerisch.png'),
            'Clear': require('../assets/sonne.png'),
            'Clouds': require('../assets/wolkig.png'),
            'Snow': require('../assets/schnee.png'),
            'Drizzle':require('../assets/regnerisch.png'),
            'Thunderstorm':require('../assets/regnerisch.png')
        },
    },

 actions:{
         currentCity({commit}) {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(position => {
                axios
                .get(`${this.url_base}weather?&lat=${position.coords.latitude}&lon=${position.coords.longitude}&units=metric&APPID=${this.api_key}`)
                .then(res=>res.data)
                .then(weather=>{
                    commit('currentCity',weather)
                })
            })
        }
    }
},
     mutations:{
         currentCity (state, weather){
             state.weather = weather
         }
     }
</code>```

答:
You are using undefined variables inside axios call that is why its giving 400 bad request because of wrong url.
Working code in GitHub repo after cleaning up home and temperature components.  https://github.com/manojkmishra/weather_app_vuex_test

demo- https://weather-app-vuex-test.netlify.app/

Modify store.js as below

```<code>import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);
export default new Vuex.Store({
state: { weather:{},    },
 actions:{
    async currentCity ({commit}, position)
    {   let url_base= 'https://api.openweathermap.org/data/2.5/';
        let api_key= 'c9f562aaffcdefaf40f2ed808d202c9b';
        console.log('store-pos',position,url_base,api_key)
        let res=await axios.get(`${url_base}weather?&lat=${position.coords.latitude}&
        lon=${position.coords.longitude}&units=metric&APPID=${api_key}`)
            commit('CUR_CITY',res.data)
        return res;
    },

 },
 mutations:{
     CUR_CITY (state, weather)
     {   console.log('store-muta-state=',state)
         state.weather = weather

     }
 },
  getters:{}
})
</code>```

modify home.js as below, cleanup your home.vue to test for only one component for eg-temperature and remove all others to check if everything is working.

```<code>import 'chartjs-plugin-datalabels';
import Temperature from '../temperature/Temperature.vue';
import { mapState} from 'vuex';
import '../../custom.scss';

export default {
computed:
{  ...mapState({ weather: state => state.weather,
                }),
},
components: {Temperature},
mounted() {
    navigator.geolocation.getCurrentPosition((position) =>
    {
        this.$store.dispatch('currentCity', position)
    });
},
};
</code>```

Body:
I want to get the weather API to display the current location but it gives back an 400 error. I don't know how to fix it.
(I open my api on browser and its works fine. But when I put it in the code bellow, it's gave error)

state: {
        weather:{},
        api_key: 'c9f562aaffcdefaf40f2ed808d202c9b',
        url_base: 'https://api.openweathermap.org/data/2.5/',
        query: '',
        icons: {
            'Rain': require('../assets/regnerisch.png'),
            'Clear': require('../assets/sonne.png'),
            'Clouds': require('../assets/wolkig.png'),
            'Snow': require('../assets/schnee.png'),
            'Drizzle':require('../assets/regnerisch.png'),
            'Thunderstorm':require('../assets/regnerisch.png')
        },
    },

 actions:{
         currentCity({commit}) {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(position => {
                axios
                .get(`${this.url_base}weather?&lat=${position.coords.latitude}&lon=${position.coords.longitude}&units=metric&APPID=${this.api_key}`)
                .then(res=>res.data)
                .then(weather=>{
                    commit('currentCity',weather)
                })
            })
        }
    }
},
     mutations:{
         currentCity (state, weather){
             state.weather = weather
         }
     }

Body:
You are using undefined variables inside axios call that is why its giving 400 bad request because of wrong url.
Working code in GitHub repo after cleaning up home and temperature components.  https://github.com/manojkmishra/weather_app_vuex_test

demo- https://weather-app-vuex-test.netlify.app/

Modify store.js as below

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);
export default new Vuex.Store({
state: { weather:{},    },
 actions:{
    async currentCity ({commit}, position)
    {   let url_base= 'https://api.openweathermap.org/data/2.5/';
        let api_key= 'c9f562aaffcdefaf40f2ed808d202c9b';
        console.log('store-pos',position,url_base,api_key)
        let res=await axios.get(`${url_base}weather?&lat=${position.coords.latitude}&
        lon=${position.coords.longitude}&units=metric&APPID=${api_key}`)
            commit('CUR_CITY',res.data)
        return res;
    },

 },
 mutations:{
     CUR_CITY (state, weather)
     {   console.log('store-muta-state=',state)
         state.weather = weather

     }
 },
  getters:{}
})

modify home.js as below, cleanup your home.vue to test for only one component for eg-temperature and remove all others to check if everything is working.

import 'chartjs-plugin-datalabels';
import Temperature from '../temperature/Temperature.vue';
import { mapState} from 'vuex';
import '../../custom.scss';

export default {
computed:
{  ...mapState({ weather: state => state.weather,
                }),
},
components: {Temperature},
mounted() {
    navigator.geolocation.getCurrentPosition((position) =>
    {
        this.$store.dispatch('currentCity', position)
    });
},
};


问:
How to make iframe redirect with cookies
we are trying to integrate some service (MSDS), we use login URL + client guid, something like this "https://login.ehs.com/pl/[guid]"
this request's response has code 302 to redirect to another URL and returns with some cookies, the browser sets these cookies in the redirection request then it redirects again to the client's profile (successfully login),

What we want is to show this page in an iframe on our website, but we noticed that the redirection request is sent without the cookies returned from the first request, hence it renders back an error html page (error in logging in).

so how to allow this request and the redirection with setting header cookies when using the iframe?

here are the redirection request cookies when setting the URL in a chrome tab
image

And those when using iframe
image

Note that our website domain is totally different than the integrated service domain.

答:
As far as I know, you can't access cross-origin cookies from a foreign domain. This thread is related: https://security.stackexchange.com/questions/113187/accesssing-cookies-of-another-domain-using-iframes-and-javascript

I recommend you do the login request on your application itself instead of doing it from an iFrame, or at least modify the iFrame to send you back the cookies using postMessage and you can set them yourself in your page.


问:
If I have a favicon, do I need to link to it?
I have a Favicon and in my page I have something like:

```<code><link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
</code>```

This works fine. But inspired by the book "Ultra Fast asp" I am trying to remove all the small bits that are not necessary. I read a lot about browsers looking for favicon.ico anyway. (People complaining about 404 errors if they do not have a favicon).

So I was wondering: what is the use of the link if the browser looks for it anyway. It is "dead wood" -> so can I just remove this link completely or am I missing something.

thanks for your ideas,
Pleun

答:
Using the explicit link syntax allows you to use different icons on different pages, and to have icon support on the browsers that do not automatically download the favicon.ico that is in the root of the site.

If you only ever use one icon on a website and don't care about browsers that do not automatically download the root icon, the links are not needed.

Body:
I have a Favicon and in my page I have something like:

<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

This works fine. But inspired by the book "Ultra Fast asp" I am trying to remove all the small bits that are not necessary. I read a lot about browsers looking for favicon.ico anyway. (People complaining about 404 errors if they do not have a favicon).

So I was wondering: what is the use of the link if the browser looks for it anyway. It is "dead wood" -> so can I just remove this link completely or am I missing something.

thanks for your ideas,
Pleun


问:
can't import keras from tensorflow
I am trying to use keras but am unable to because when I run from tensorflow import keras I get this error:

```<code>➜  kerasTutorial python3
Python 3.7.7 (default, Mar 10 2020, 15:43:33)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from tensorflow import keras
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/tensorflow/__init__.py", line 41, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/__init__.py", line 64, in <module>
    from tensorflow.python.framework.framework_lib import *  # pylint: disable=redefined-builtin
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/framework_lib.py", line 25, in <module>
    from tensorflow.python.framework.ops import Graph
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 64, in <module>
    from tensorflow.python.platform import app
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/platform/app.py", line 23, in <module>
    from absl.app import run as _run
  File "/usr/local/lib/python3.7/site-packages/absl/app.py", line 35, in <module>
    import pdb
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/pdb.py", line 76, in <module>
    import code
  File "/Users/mathewlewis/Documents/Y4S3/Crypto/kerasTutorial/code.py", line 4, in <module>
    from tensorflow.keras.models import Sequential
  File "/usr/local/lib/python3.7/site-packages/tensorflow/keras/__init__.py", line 14, in <module>
    from . import activations
  File "/usr/local/lib/python3.7/site-packages/tensorflow/keras/activations/__init__.py", line 10, in <module>
    from tensorflow.python.keras.activations import deserialize
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/__init__.py", line 27, in <module>
    from tensorflow.python.keras import models
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/models.py", line 23, in <module>
    from tensorflow.python.keras import backend as K
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/backend.py", line 36, in <module>
    from tensorflow.python.client import session as session_module
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/client/session.py", line 38, in <module>
    from tensorflow.python.framework import sparse_tensor
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/sparse_tensor.py", line 29, in <module>
    from tensorflow.python.framework import constant_op
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py", line 324, in <module>
    ops.register_tensor_conversion_function(
AttributeError: module 'tensorflow.python.framework.ops' has no attribute 'register_tensor_conversion_function'
>>>
</code>```

I am using python3 on mac. I have installed both keras and tensorflow using pip3 install keras and pip3 install tensorflow

I am under the impression that importing keras from tensorflow should be possible given that here on keras.io they provide the following sample code:

```<code>import numpy as np
import tensorflow as tf
from tensorflow import keras
</code>```

Because of this, I suspect I have improperly installed either tensorflow or keras. For this reason, I have included below the results I get when I run pip3 install tensorflow and pip3 install keras:

```<code>➜  kerasTutorial pip3 install tensorflow
Requirement already satisfied: tensorflow in /usr/local/lib/python3.7/site-packages (2.2.0)
Requirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.14.0)
Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.29.0)
Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.6.3)
Requirement already satisfied: wheel>=0.26; python_version >= "3" in /usr/local/lib/python3.7/site-packages (from tensorflow) (0.34.2)
Requirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.7/site-packages (from tensorflow) (0.2.0)
Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (2.10.0)
Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.7/site-packages (from tensorflow) (0.3.3)
Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.7/site-packages (from tensorflow) (3.2.1)
Requirement already satisfied: protobuf>=3.8.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (3.12.0)
Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.12.1)
Requirement already satisfied: scipy==1.4.1; python_version >= "3" in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.4.1)
Requirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (0.9.0)
Requirement already satisfied: tensorflow-estimator<2.3.0,>=2.2.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (2.2.0)
Requirement already satisfied: tensorboard<2.3.0,>=2.2.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (2.2.1)
Requirement already satisfied: keras-preprocessing>=1.1.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.1.2)
Requirement already satisfied: numpy<2.0,>=1.16.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.18.4)
Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.1.0)
Requirement already satisfied: setuptools in /Users/mathewlewis/Library/Python/3.7/lib/python/site-packages (from protobuf>=3.8.0->tensorflow) (46.4.0)
Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (2.23.0)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (3.2.2)
Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.15.0)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (0.4.1)
Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.0.1)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.6.0.post3)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (2020.4.5.1)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (2.9)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (1.25.9)
Requirement already satisfied: importlib-metadata; python_version < "3.8" in /usr/local/lib/python3.7/site-packages (from markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow) (1.6.0)
Requirement already satisfied: rsa<4.1,>=3.1.4 in /usr/local/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (4.0)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (4.1.0)
Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (0.2.8)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow) (1.3.0)
Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/site-packages (from importlib-metadata; python_version < "3.8"->markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.1.0)
Requirement already satisfied: pyasn1>=0.1.3 in /usr/local/lib/python3.7/site-packages (from rsa<4.1,>=3.1.4->google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (0.4.8)
Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.1.0)

➜  kerasTutorial pip3 install keras
Requirement already satisfied: keras in /usr/local/lib/python3.7/site-packages (2.3.1)
Requirement already satisfied: keras-applications>=1.0.6 in /usr/local/lib/python3.7/site-packages (from keras) (1.0.8)
Requirement already satisfied: h5py in /usr/local/lib/python3.7/site-packages (from keras) (2.10.0)
Requirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.7/site-packages (from keras) (1.1.2)
Requirement already satisfied: numpy>=1.9.1 in /usr/local/lib/python3.7/site-packages (from keras) (1.18.4)
Requirement already satisfied: six>=1.9.0 in /usr/local/lib/python3.7/site-packages (from keras) (1.14.0)
Requirement already satisfied: scipy>=0.14 in /usr/local/lib/python3.7/site-packages (from keras) (1.4.1)
Requirement already satisfied: pyyaml in /usr/local/lib/python3.7/site-packages (from keras) (5.3.1)
</code>```

In case this is relavent, I am on a mid 2015 macbook pro, running macos catalina version 10.15.4

This was my best attempt at including all relavent information. If you'd like to know something else please let me know and I'll try and find that out for you. Thanks very much for taking the time to read this long question.

I have also tried using keras directly rather than importing from tensorflow. To do so I ran from keras.models import Sequential and got this error:

```<code>➜  kerasTutorial python3
Python 3.7.7 (default, Mar 10 2020, 15:43:33)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from keras.models import Sequential
Using TensorFlow backend.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/keras/__init__.py", line 3, in <module>
    from . import utils
  File "/usr/local/lib/python3.7/site-packages/keras/utils/__init__.py", line 6, in <module>
    from . import conv_utils
  File "/usr/local/lib/python3.7/site-packages/keras/utils/conv_utils.py", line 9, in <module>
    from .. import backend as K
  File "/usr/local/lib/python3.7/site-packages/keras/backend/__init__.py", line 1, in <module>
    from .load_backend import epsilon
  File "/usr/local/lib/python3.7/site-packages/keras/backend/load_backend.py", line 90, in <module>
    from .tensorflow_backend import *
  File "/usr/local/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py", line 5, in <module>
    import tensorflow as tf
  File "/usr/local/lib/python3.7/site-packages/tensorflow/__init__.py", line 41, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/__init__.py", line 64, in <module>
    from tensorflow.python.framework.framework_lib import *  # pylint: disable=redefined-builtin
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/framework_lib.py", line 25, in <module>
    from tensorflow.python.framework.ops import Graph
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 64, in <module>
    from tensorflow.python.platform import app
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/platform/app.py", line 23, in <module>
    from absl.app import run as _run
  File "/usr/local/lib/python3.7/site-packages/absl/app.py", line 35, in <module>
    import pdb
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/pdb.py", line 76, in <module>
    import code
  File "/Users/mathewlewis/Documents/Y4S3/Crypto/kerasTutorial/code.py", line 4, in <module>
    from tensorflow.keras.models import Sequential
  File "/usr/local/lib/python3.7/site-packages/tensorflow/keras/__init__.py", line 14, in <module>
    from . import activations
  File "/usr/local/lib/python3.7/site-packages/tensorflow/keras/activations/__init__.py", line 10, in <module>
    from tensorflow.python.keras.activations import deserialize
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/__init__.py", line 27, in <module>
    from tensorflow.python.keras import models
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/models.py", line 23, in <module>
    from tensorflow.python.keras import backend as K
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/backend.py", line 36, in <module>
    from tensorflow.python.client import session as session_module
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/client/session.py", line 38, in <module>
    from tensorflow.python.framework import sparse_tensor
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/sparse_tensor.py", line 29, in <module>
    from tensorflow.python.framework import constant_op
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py", line 324, in <module>
    ops.register_tensor_conversion_function(
AttributeError: module 'tensorflow.python.framework.ops' has no attribute 'register_tensor_conversion_function'
>>>
</code>```

Also, I am not using conda. I'd like to have a solution which uses python3 and packages which can be installed using pip3.

答:
I looked into the error. Some people had it because of an older version of Keras. You have a version which shouldn't be causing any issues.

I would suggest to uninstall keras and tensorflow:

```<code>pip3 uninstall tensorflow
pip3 uninstall keras
</code>```

upgrade pip3:

```<code>pip3 install --upgrade pip
</code>```

and then install tensorflow again:

```<code>pip3 install tensorflow
</code>```

and try to run the project. If this doesn't work try reinstalling python as well.

Title: can't import keras from tensorflow

Body:
I am trying to use keras but am unable to because when I run from tensorflow import keras I get this error:

➜  kerasTutorial python3
Python 3.7.7 (default, Mar 10 2020, 15:43:33)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from tensorflow import keras
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/tensorflow/__init__.py", line 41, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/__init__.py", line 64, in <module>
    from tensorflow.python.framework.framework_lib import *  # pylint: disable=redefined-builtin
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/framework_lib.py", line 25, in <module>
    from tensorflow.python.framework.ops import Graph
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 64, in <module>
    from tensorflow.python.platform import app
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/platform/app.py", line 23, in <module>
    from absl.app import run as _run
  File "/usr/local/lib/python3.7/site-packages/absl/app.py", line 35, in <module>
    import pdb
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/pdb.py", line 76, in <module>
    import code
  File "/Users/mathewlewis/Documents/Y4S3/Crypto/kerasTutorial/code.py", line 4, in <module>
    from tensorflow.keras.models import Sequential
  File "/usr/local/lib/python3.7/site-packages/tensorflow/keras/__init__.py", line 14, in <module>
    from . import activations
  File "/usr/local/lib/python3.7/site-packages/tensorflow/keras/activations/__init__.py", line 10, in <module>
    from tensorflow.python.keras.activations import deserialize
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/__init__.py", line 27, in <module>
    from tensorflow.python.keras import models
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/models.py", line 23, in <module>
    from tensorflow.python.keras import backend as K
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/backend.py", line 36, in <module>
    from tensorflow.python.client import session as session_module
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/client/session.py", line 38, in <module>
    from tensorflow.python.framework import sparse_tensor
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/sparse_tensor.py", line 29, in <module>
    from tensorflow.python.framework import constant_op
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py", line 324, in <module>
    ops.register_tensor_conversion_function(
AttributeError: module 'tensorflow.python.framework.ops' has no attribute 'register_tensor_conversion_function'
>>>

I am using python3 on mac. I have installed both keras and tensorflow using pip3 install keras and pip3 install tensorflow

I am under the impression that importing keras from tensorflow should be possible given that here on keras.io they provide the following sample code:

import numpy as np
import tensorflow as tf
from tensorflow import keras

Because of this, I suspect I have improperly installed either tensorflow or keras. For this reason, I have included below the results I get when I run pip3 install tensorflow and pip3 install keras:

➜  kerasTutorial pip3 install tensorflow
Requirement already satisfied: tensorflow in /usr/local/lib/python3.7/site-packages (2.2.0)
Requirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.14.0)
Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.29.0)
Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.6.3)
Requirement already satisfied: wheel>=0.26; python_version >= "3" in /usr/local/lib/python3.7/site-packages (from tensorflow) (0.34.2)
Requirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.7/site-packages (from tensorflow) (0.2.0)
Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (2.10.0)
Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.7/site-packages (from tensorflow) (0.3.3)
Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.7/site-packages (from tensorflow) (3.2.1)
Requirement already satisfied: protobuf>=3.8.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (3.12.0)
Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.12.1)
Requirement already satisfied: scipy==1.4.1; python_version >= "3" in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.4.1)
Requirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (0.9.0)
Requirement already satisfied: tensorflow-estimator<2.3.0,>=2.2.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (2.2.0)
Requirement already satisfied: tensorboard<2.3.0,>=2.2.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (2.2.1)
Requirement already satisfied: keras-preprocessing>=1.1.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.1.2)
Requirement already satisfied: numpy<2.0,>=1.16.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.18.4)
Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.7/site-packages (from tensorflow) (1.1.0)
Requirement already satisfied: setuptools in /Users/mathewlewis/Library/Python/3.7/lib/python/site-packages (from protobuf>=3.8.0->tensorflow) (46.4.0)
Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (2.23.0)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (3.2.2)
Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.15.0)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (0.4.1)
Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.0.1)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.6.0.post3)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (2020.4.5.1)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (2.9)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (1.25.9)
Requirement already satisfied: importlib-metadata; python_version < "3.8" in /usr/local/lib/python3.7/site-packages (from markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow) (1.6.0)
Requirement already satisfied: rsa<4.1,>=3.1.4 in /usr/local/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (4.0)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (4.1.0)
Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (0.2.8)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow) (1.3.0)
Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/site-packages (from importlib-metadata; python_version < "3.8"->markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.1.0)
Requirement already satisfied: pyasn1>=0.1.3 in /usr/local/lib/python3.7/site-packages (from rsa<4.1,>=3.1.4->google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (0.4.8)
Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.1.0)

➜  kerasTutorial pip3 install keras
Requirement already satisfied: keras in /usr/local/lib/python3.7/site-packages (2.3.1)
Requirement already satisfied: keras-applications>=1.0.6 in /usr/local/lib/python3.7/site-packages (from keras) (1.0.8)
Requirement already satisfied: h5py in /usr/local/lib/python3.7/site-packages (from keras) (2.10.0)
Requirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.7/site-packages (from keras) (1.1.2)
Requirement already satisfied: numpy>=1.9.1 in /usr/local/lib/python3.7/site-packages (from keras) (1.18.4)
Requirement already satisfied: six>=1.9.0 in /usr/local/lib/python3.7/site-packages (from keras) (1.14.0)
Requirement already satisfied: scipy>=0.14 in /usr/local/lib/python3.7/site-packages (from keras) (1.4.1)
Requirement already satisfied: pyyaml in /usr/local/lib/python3.7/site-packages (from keras) (5.3.1)

In case this is relavent, I am on a mid 2015 macbook pro, running macos catalina version 10.15.4

This was my best attempt at including all relavent information. If you'd like to know something else please let me know and I'll try and find that out for you. Thanks very much for taking the time to read this long question.

I have also tried using keras directly rather than importing from tensorflow. To do so I ran from keras.models import Sequential and got this error:

➜  kerasTutorial python3
Python 3.7.7 (default, Mar 10 2020, 15:43:33)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from keras.models import Sequential
Using TensorFlow backend.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/keras/__init__.py", line 3, in <module>
    from . import utils
  File "/usr/local/lib/python3.7/site-packages/keras/utils/__init__.py", line 6, in <module>
    from . import conv_utils
  File "/usr/local/lib/python3.7/site-packages/keras/utils/conv_utils.py", line 9, in <module>
    from .. import backend as K
  File "/usr/local/lib/python3.7/site-packages/keras/backend/__init__.py", line 1, in <module>
    from .load_backend import epsilon
  File "/usr/local/lib/python3.7/site-packages/keras/backend/load_backend.py", line 90, in <module>
    from .tensorflow_backend import *
  File "/usr/local/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py", line 5, in <module>
    import tensorflow as tf
  File "/usr/local/lib/python3.7/site-packages/tensorflow/__init__.py", line 41, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/__init__.py", line 64, in <module>
    from tensorflow.python.framework.framework_lib import *  # pylint: disable=redefined-builtin
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/framework_lib.py", line 25, in <module>
    from tensorflow.python.framework.ops import Graph
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 64, in <module>
    from tensorflow.python.platform import app
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/platform/app.py", line 23, in <module>
    from absl.app import run as _run
  File "/usr/local/lib/python3.7/site-packages/absl/app.py", line 35, in <module>
    import pdb
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/pdb.py", line 76, in <module>
    import code
  File "/Users/mathewlewis/Documents/Y4S3/Crypto/kerasTutorial/code.py", line 4, in <module>
    from tensorflow.keras.models import Sequential
  File "/usr/local/lib/python3.7/site-packages/tensorflow/keras/__init__.py", line 14, in <module>
    from . import activations
  File "/usr/local/lib/python3.7/site-packages/tensorflow/keras/activations/__init__.py", line 10, in <module>
    from tensorflow.python.keras.activations import deserialize
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/__init__.py", line 27, in <module>
    from tensorflow.python.keras import models
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/models.py", line 23, in <module>
    from tensorflow.python.keras import backend as K
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/backend.py", line 36, in <module>
    from tensorflow.python.client import session as session_module
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/client/session.py", line 38, in <module>
    from tensorflow.python.framework import sparse_tensor
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/sparse_tensor.py", line 29, in <module>
    from tensorflow.python.framework import constant_op
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py", line 324, in <module>
    ops.register_tensor_conversion_function(
AttributeError: module 'tensorflow.python.framework.ops' has no attribute 'register_tensor_conversion_function'
>>>

Also, I am not using conda. I'd like to have a solution which uses python3 and packages which can be installed using pip3.

Body:
I looked into the error. Some people had it because of an older version of Keras. You have a version which shouldn't be causing any issues.

I would suggest to uninstall keras and tensorflow:

pip3 uninstall tensorflow
pip3 uninstall keras

upgrade pip3:

pip3 install --upgrade pip

and then install tensorflow again:

pip3 install tensorflow

and try to run the project. If this doesn't work try reinstalling python as well.


问:
Airflow: Only allow one instance of task

Is there a way specify that a task can only run once concurrently? So in the tree above where DAG concurrency is 4, Airflow will start task 4 instead of a second instance of task 2?

This DAG is a little special because there is no order between the tasks. These tasks are independent but related in purpose and therefore kept in one DAG so as to new create an excessive number of single task DAGs.

max_active_runs is 2 and dag_concurrency is 4. I would like it start all 4 tasks and only start a task in next if same task in previous run is done.

答: Airflow operator documentation describes argument task_concurrency. Just set it to one.


问:
How do i center everything?
I have made a really simple calculator, but it being on the top right of the screen makes it look weird. Vertical-align does not work and text-align only works for the text box. How do i make all the buttons centered in the screen???

I put all of the buttons and stuff inside a div called main. How do i center that div vertically and horizontally?

I could manually position it by giving some px values to the left and top but it would not work different screens. I want to make it in a way that it remains centered in a huge variety of screens.

答:
U can do it by flex

```<code>display:flex;
align-items:center;
Justify-content:center;
</code>```

Or

```<code>display:inline-block;
margin: auto;
</code>```

It will do.

Title: How do i center everything?

Body:
U can do it by flex

display:flex;
align-items:center;
Justify-content:center;

Or

display:inline-block;
margin: auto;

It will do.


问:
Failed to pass a string from Activity to Fragment
I want to pass a Serializable object from activity to fragment. But at fragment, getArguments() always retuns null. Then I try to pass a simple string value from activity to fragment, it still shows NullPointerExection.

Here is my Activity Class

```<code>public class FullProfile extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private Customer customer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_full_profile);

    tabLayout = findViewById(R.id.tabLayout);
    viewPager = findViewById(R.id.myViewPager);
    setupViewPager(viewPager);

    ProfileBasicFragment basic = new ProfileBasicFragment();
    Bundle bundle = new Bundle();
    bundle.putString("profile", "Hello Hello");

    basic.setArguments(bundle);
    getSupportFragmentManager().beginTransaction().add(R.id.myViewPager, basic).commit();

    tabLayout.setupWithViewPager(viewPager);

}

private void setupViewPager(ViewPager viewPager) {
    FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), 4);
    fragmentAdapter.addFragment(new ProfileBasicFragment(), "Profile");
    fragmentAdapter.addFragment(new ProductFragment(), "Product");
    fragmentAdapter.addFragment(new WatchListFragment(), "Choices");

    viewPager.setAdapter(fragmentAdapter);

}
</code>```

}

Here is my Fragment..

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

TextView t;
String s;

public ProfileBasicFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_profile_basic, container, false);
    t = view.findViewById(R.id.nameTV);

    String s = getArguments().getString("profile");
    t.setText(s);

    return view;
}
</code>```

}

And Here is the error

```<code> java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
</code>```

I can't understand what's is my fault. Can you help me? Thank you

答:
the actual problem is when you initializing the viewPager.

```<code>private void setupViewPager(ViewPager viewPager) {
...
fragmentAdapter.addFragment(new ProfileBasicFragment(), "Profile");
 //Problem is here
...
}
</code>```

So send the data from here also or in your fragment do this

```<code> if(getArguments()!=null){
 String s = getArguments().getString("profile");
 t.setText(s);
 }
</code>```

Body:
I want to pass a Serializable object from activity to fragment. But at fragment, getArguments() always retuns null. Then I try to pass a simple string value from activity to fragment, it still shows NullPointerExection.

Here is my Activity Class

public class FullProfile extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private Customer customer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_full_profile);

    tabLayout = findViewById(R.id.tabLayout);
    viewPager = findViewById(R.id.myViewPager);
    setupViewPager(viewPager);

    ProfileBasicFragment basic = new ProfileBasicFragment();
    Bundle bundle = new Bundle();
    bundle.putString("profile", "Hello Hello");

    basic.setArguments(bundle);
    getSupportFragmentManager().beginTransaction().add(R.id.myViewPager, basic).commit();

    tabLayout.setupWithViewPager(viewPager);

}

private void setupViewPager(ViewPager viewPager) {
    FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), 4);
    fragmentAdapter.addFragment(new ProfileBasicFragment(), "Profile");
    fragmentAdapter.addFragment(new ProductFragment(), "Product");
    fragmentAdapter.addFragment(new WatchListFragment(), "Choices");

    viewPager.setAdapter(fragmentAdapter);

}

}

Here is my Fragment..

public class ProfileBasicFragment extends Fragment {

TextView t;
String s;

public ProfileBasicFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_profile_basic, container, false);
    t = view.findViewById(R.id.nameTV);

    String s = getArguments().getString("profile");
    t.setText(s);

    return view;
}

}

And Here is the error

 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference

I can't understand what's is my fault. Can you help me? Thank you

Body:
the actual problem is when you initializing the viewPager.

private void setupViewPager(ViewPager viewPager) {
...
fragmentAdapter.addFragment(new ProfileBasicFragment(), "Profile");
 //Problem is here
...
}

So send the data from here also or in your fragment do this

 if(getArguments()!=null){
 String s = getArguments().getString("profile");
 t.setText(s);
 }


问:
How do I disable pylint unused import error messages in vs code
How do I disable these error messages from popping up in the problems box in vs code

答:
For the simple test.py, I did not modify setting but only apply to that file I used
    # pylint: disable=W0614
Put this line on top of the file then pylint automatically recognized it.

This eliminated 100 unused import warnings

You can keep disabling like this

```<code># pylint: disable=missing-module-docstring
# pylint: disable=missing-class-docstring
# pylint: disable=missing-function-docstring
# pylint: disable=wildcard-import
# pylint: disable=W0614
</code>```

Body:
For the simple test.py, I did not modify setting but only apply to that file I used
    # pylint: disable=W0614
Put this line on top of the file then pylint automatically recognized it.

This eliminated 100 unused import warnings

You can keep disabling like this

# pylint: disable=missing-module-docstring
# pylint: disable=missing-class-docstring
# pylint: disable=missing-function-docstring
# pylint: disable=wildcard-import
# pylint: disable=W0614


问:
stdout and need to flush it C++
I have some C++ code that uses cout statements for debug purposes and for some reason I can't get all the data to print unless I do a std::cout.flush(); at the end.

I don't quite understand why this flush operation is needed.

Anyone have any insight?

答: In C++ you can use endl formatter with cout operator rather then flush.

Title: stdout and need to flush it C++


问:
create and update field to other model backpack laravel
I am trying to create a dashboard to display a specific table and create/update the lines for this table via backpack laravel.

For example I want to display a table of area and this table has a relationship with the cities table.

my problem is when I want to add a specific area and the city associated with it is not added !!.

That I do not want to go to add the city then back to add the area.

This is a very small example of what I'm really dealing with ,
since I want to add a line in a table and this line contains relationships with other tables I want to create on the same page.

I searched and did not find a direct answer. Does it make sense that a new view should be created?
Does the Backpack Laravel not provide a solution to this problem?

If the answer is no and this is what I saw, what is the best solution to this problem ?

Image to summarizes the problem as I want to create the city on the same page as creating the area

答:
I think what you’re looking for is what we call the InlineCreate Operation in Backpack. It adds a “+ Add” button next to the relationship field, so that the admin can add a related item right there, in a modal.

Check out its docs here.


问:
Chrome form reset don't change display select element
When I reset the form the select element value reset but still display the old value

I'm using this to reset the form

```<code>$('#testForm')[0].reset();
</code>```

In this example the 'Two' option is selected by default.
If I change the selection and press 'reset form' the select value change back but still shows the old value

in Edge its working

https://jsfiddle.net/z6vk91sL/

Google Chrome   83.0.4103.61 (Official Build) (64-bit) (cohort: Stable)

$('#testFormReset').on("click", () => {
  $('#testForm')[0].reset();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}</code>```

<form id='testForm'>
  <select>
    <option value='1'>One</option>
    <option selected value='2'>Two</option>
    <option value='3'>Three</option>
  </select>

  <button id='testFormReset' type='reset'>
    reset form
  </button>
</form>```

答:
You're running into issue #1087031, which was reported five days ago and has been fixed. The fix will make its way out into release before too long, probably v84 (it's targeted at M-84).

I found the issue by searching for select reset component:Blink>Forms at https://bugs.chromium.org/p/chromium/issues.

Body:
When I reset the form the select element value reset but still display the old value

I'm using this to reset the form

$('#testForm')[0].reset();

In this example the 'Two' option is selected by default.
If I change the selection and press 'reset form' the select value change back but still shows the old value

in Edge its working

https://jsfiddle.net/z6vk91sL/

Google Chrome   83.0.4103.61 (Official Build) (64-bit) (cohort: Stable)

$('#testFormReset').on("click", () => {
  $('#testForm')[0].reset();
})

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

<form id='testForm'>
  <select>
    <option value='1'>One</option>
    <option selected value='2'>Two</option>
    <option value='3'>Three</option>
  </select>

  <button id='testFormReset' type='reset'>
    reset form
  </button>
</form>


问:
Vertical align of A elements inside LI
I have a problem with implementing a new design. While the anchor elements are aligned correctly in the old design, for some reason the anchor elements are aligned to the bottom in the new design with html/css regading the UL, LI and A part being exatly the same.</p>

```<code>#treeview ul {
    padding-top: 3px;
}
#treeview ul li {
    background: none repeat scroll 0 0 transparent;
    line-height: 24px;
    padding-bottom: 3px;
    padding-left: 0;
}
#treeview ul li.active {
    background: none repeat scroll 0 0 #DDDDDD;
}
#treeview ul li ul li {
    padding-left: 30px;
}
#treeview ul li a {
    color: #444444;
    padding-left: 5px;
    text-decoration: none;
}

<div id="treeview">
    <ul>
        <li>
            <img src="assets/js/no-expand.png">
            <img class="icon" width="24" height="" src="assets/images/icons/icon_dance24x24.png">
            <a title="Essential" href="/index/night-clubs/essential/">Essential</a>
        </li>
    </ul>
</div>
</code>```

答:
Try this...</p>

```<code>#treeview ul li * {
    vertical-align: middle;
}
</code>```

Title: Vertical align of A elements inside LI

Body:
I have a problem with implementing a new design. While the anchor elements are aligned correctly in the old design, for some reason the anchor elements are aligned to the bottom in the new design with html/css regading the UL, LI and A part being exatly the same.

#treeview ul {
    padding-top: 3px;
}
#treeview ul li {
    background: none repeat scroll 0 0 transparent;
    line-height: 24px;
    padding-bottom: 3px;
    padding-left: 0;
}
#treeview ul li.active {
    background: none repeat scroll 0 0 #DDDDDD;
}
#treeview ul li ul li {
    padding-left: 30px;
}
#treeview ul li a {
    color: #444444;
    padding-left: 5px;
    text-decoration: none;
}

            Essential

Body:
Try this...

#treeview ul li * {
    vertical-align: middle;
}


问:
Python Seaborn - Create boxplot for each numeric variable
I am trying to build a boxplot for each numeric variable in my data set.

There is already a description here:

```<code>import seaborn as sns
import pandas as pd

iris_xtab = sns.load_dataset("iris")
iris_long = pd.melt(iris, id_vars='species')
sns.boxplot(x='variable', y='value', hue='species', data=iris_long)
</code>```

Unfortunately, the values of my data set vary very much so that I cannot fit the entire data in one graph.
Is there are way to produce one boxplot per column?

答:
As for seaborn, it is still unfamiliar, but I think it is possible by the following measures.

```<code>g = sns.FacetGrid(iris_long, col='variable', height=9, aspect=1.5)
g.map(sns.boxplot, 'variable', 'value', hue='species', data=iris_long)
</code>```

Body:
I am trying to build a boxplot for each numeric variable in my data set.

There is already a description here:

import seaborn as sns
import pandas as pd

iris_xtab = sns.load_dataset("iris")
iris_long = pd.melt(iris, id_vars='species')
sns.boxplot(x='variable', y='value', hue='species', data=iris_long)

Unfortunately, the values of my data set vary very much so that I cannot fit the entire data in one graph.
Is there are way to produce one boxplot per column?

Body:
As for seaborn, it is still unfamiliar, but I think it is possible by the following measures.

g = sns.FacetGrid(iris_long, col='variable', height=9, aspect=1.5)
g.map(sns.boxplot, 'variable', 'value', hue='species', data=iris_long)


问:
ServiceWorker Push Notification options not passing to notification
The notification options that I am passing to my notifications are not passing to the notification and I am getting a default notification. (Title is the website, body is "The site has been updated in the background").

Service worker is an adapted create-react-app service worker.

Also, the console.log statements in the push event handler are not passing to the browser. Why is this?

The push event listener is directly after the load event listener in the CRA Service Worker

Web-Push API Call to create a web-push notification:

```<code>router.post('/:userid', auth, async (req, res) => {
  try {
    const user = await User.findById(req.params.userid);

    user.pushSubscriptions.forEach((sub) => {
      if (sub === null) {
        return;
      }

      webpush.setVapidDetails(
        'mailto:contact@email.com',
        config.get('vapidPublic'),
        config.get('vapidSecret')
      );

      const options = {
        endpoint: sub.endpoint,
        expirationTime: sub.expirationTime,
        keys: {
          p256dh: sub.keys.p256dh,
          auth: sub.keys.auth,
        },
      };

      console.log(options.endpoint);

      webpush
        .sendNotification(
          options,
          JSON.stringify({
            title: 'NotifTitle',
            body: 'Body',
          })
        )
        .catch((error) => console.log(error));
    });

    return res.status(200).json({ msg: 'Notification Sent' });
  } catch (error) {
    console.log(error);
    return res.status(500);
  }
});
</code>```

Push listener in sw.js:

```<code>window.addEventListener('push', (event) => {
      console.log('Notification Recieved', event);

      //Fallback data
      let data = {
        title: 'TestABC',
        body: '123456',
      };

      if (event.data) {
        data = JSON.parse(event.data.text());
      }

      //Notification options
      var options = {
        body: data.body,
        icon: '../public/logo192.png',
        image: '../public/logo192.png',
      };

      event.waitUntil(
        console.log(options),
        navigator.serviceWorker.registration.showNotification(
          data.title,
          options
        )
      );
    });
</code>```

Thanks

答:
try to convert data like this </p>

```<code>data = event.data.json();
</code>```

<p>you can read more here </p>

Body:
The notification options that I am passing to my notifications are not passing to the notification and I am getting a default notification. (Title is the website, body is "The site has been updated in the background").

Service worker is an adapted create-react-app service worker.

Also, the console.log statements in the push event handler are not passing to the browser. Why is this?

The push event listener is directly after the load event listener in the CRA Service Worker

Web-Push API Call to create a web-push notification:

router.post('/:userid', auth, async (req, res) => {
  try {
    const user = await User.findById(req.params.userid);

    user.pushSubscriptions.forEach((sub) => {
      if (sub === null) {
        return;
      }

      webpush.setVapidDetails(
        'mailto:contact@email.com',
        config.get('vapidPublic'),
        config.get('vapidSecret')
      );

      const options = {
        endpoint: sub.endpoint,
        expirationTime: sub.expirationTime,
        keys: {
          p256dh: sub.keys.p256dh,
          auth: sub.keys.auth,
        },
      };

      console.log(options.endpoint);

      webpush
        .sendNotification(
          options,
          JSON.stringify({
            title: 'NotifTitle',
            body: 'Body',
          })
        )
        .catch((error) => console.log(error));
    });

    return res.status(200).json({ msg: 'Notification Sent' });
  } catch (error) {
    console.log(error);
    return res.status(500);
  }
});

Push listener in sw.js:

window.addEventListener('push', (event) => {
      console.log('Notification Recieved', event);

      //Fallback data
      let data = {
        title: 'TestABC',
        body: '123456',
      };

      if (event.data) {
        data = JSON.parse(event.data.text());
      }

      //Notification options
      var options = {
        body: data.body,
        icon: '../public/logo192.png',
        image: '../public/logo192.png',
      };

      event.waitUntil(
        console.log(options),
        navigator.serviceWorker.registration.showNotification(
          data.title,
          options
        )
      );
    });

Thanks

Body:
try to convert data like this

data = event.data.json();

you can read more here


问:
Hide TextView when SearchView is open
I am using TextView on top of SearchView as a heading. The other option is customising the search query hint by changing the font, color, text size and centering. This seems like a simpler method.

```<code><androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <SearchView
            android:id="@+id/searchview"
            android:layout_width="match_parent"
            android:layout_height="43dp"
            android:layout_marginStart="12dp"
            android:layout_marginTop="40dp"
            android:layout_marginEnd="12dp"
            android:background="@drawable/searchbackground"
            android:closeIcon="@drawable/search_x_button"
            android:iconifiedByDefault="false"
            android:paddingStart="2dp"
            android:paddingTop="11dp"
            android:paddingEnd="15dp"
            android:paddingBottom="11dp"
            android:queryBackground="@android:color/transparent"
            android:gravity="center"
            android:searchIcon="@drawable/ic_ssearch"
            android:textSize="15sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <TextView
            android:id="@+id/textView13"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="24dp"
            android:layout_marginTop="49dp"
            android:layout_marginEnd="24dp"
            android:fontFamily="@font/manrope_semibold"
            android:text="@string/search"
            android:textColor="@color/font_title"
            android:textSize="19sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
</code>```

How can I set the textview to hide once the searchview is in focus, aka user taps on it and the blinking cursor appears?

Edit: fixed by doing this

```<code>searchHint = view.findViewById(R.id.textView13);
</code>```

and then

```<code>public boolean onQueryTextChange(String query) {
            if (query.equals("")) {
                searchHint.setVisibility(View.VISIBLE);
            } else {
                searchHint.setVisibility(View.GONE);
            }
            return true;
        }
</code>```

答:
You can try it like this:

Whenever you click on the TextView, change its visibility to GONE, and add the focus to the SearchView.

```<code>SearchView mSearchView = findViewById(R.id.searchview);
TextView textView = findViewById(R.id.textView13)

textView.setOnClickListener(v -> {
     textView.setVisibility(View.GONE);
     mSearchView.setSearchFocused(true);
  });
</code>```

Hope it helps!

Title: Hide TextView when SearchView is open

Body:
I am using TextView on top of SearchView as a heading. The other option is customising the search query hint by changing the font, color, text size and centering. This seems like a simpler method.

<androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <SearchView
            android:id="@+id/searchview"
            android:layout_width="match_parent"
            android:layout_height="43dp"
            android:layout_marginStart="12dp"
            android:layout_marginTop="40dp"
            android:layout_marginEnd="12dp"
            android:background="@drawable/searchbackground"
            android:closeIcon="@drawable/search_x_button"
            android:iconifiedByDefault="false"
            android:paddingStart="2dp"
            android:paddingTop="11dp"
            android:paddingEnd="15dp"
            android:paddingBottom="11dp"
            android:queryBackground="@android:color/transparent"
            android:gravity="center"
            android:searchIcon="@drawable/ic_ssearch"
            android:textSize="15sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <TextView
            android:id="@+id/textView13"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="24dp"
            android:layout_marginTop="49dp"
            android:layout_marginEnd="24dp"
            android:fontFamily="@font/manrope_semibold"
            android:text="@string/search"
            android:textColor="@color/font_title"
            android:textSize="19sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

How can I set the textview to hide once the searchview is in focus, aka user taps on it and the blinking cursor appears?

Edit: fixed by doing this

searchHint = view.findViewById(R.id.textView13);

and then

public boolean onQueryTextChange(String query) {
            if (query.equals("")) {
                searchHint.setVisibility(View.VISIBLE);
            } else {
                searchHint.setVisibility(View.GONE);
            }
            return true;
        }

Body:
You can try it like this:

Whenever you click on the TextView, change its visibility to GONE, and add the focus to the SearchView.

SearchView mSearchView = findViewById(R.id.searchview);
TextView textView = findViewById(R.id.textView13)

textView.setOnClickListener(v -> {
     textView.setVisibility(View.GONE);
     mSearchView.setSearchFocused(true);
  });

Hope it helps!


问:
Django-Filter Package: How To Filter Objects To Create Stats And Not Lists
I'm using Django-Filter package which is working well for the one example they have in their documentation. However, I am not trying to generate a list of objects rather filter the calculations I have done on the object fields.

Example template: https://django-filter.readthedocs.io/en/stable/guide/usage.html#the-template

```<code>{% for obj in filter.qs %}
    {{ obj.name }} - ${{ obj.price }}<br />
{% endfor %}
</code>```

The problem here is that a list is created.. I'm looking for my trade "stats" to be updated based on the new filter selections.

I believe I need to set up my views differently and possibly call the template objects in another way as well but not totally sure.

filters.py

```<code>class StatsFilter(django_filters.FilterSet):
    class Meta:
        model = Trade
        fields = ['type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios']
</code>```

views.py

```<code>class StatsView(LoginRequiredMixin, FilterView):
    model = Trade
    template_name = 'dashboard/stats.html'
    filterset_class = StatsFilter

    def get_form(self, *args, **kwargs):
        form = StatsFilter()
        user = self.request.user
        form.fields['associated_portfolios'].queryset = Portfolio.objects.filter(user=user)
        return form

    def get_context_data(self, *args, **kwargs):
        trade = Trade.objects.filter(user=self.request.user, status='cl').order_by('created')
        all_trades = Trade.objects.filter(user=self.request.user, status='cl').count()
        context = super(StatsView, self).get_context_data(*args, **kwargs)
        data = [t.profit_loss_value_fees for t in trade]

        context['all_trades'] = all_trades
        context['gross_profit'] = sum([t.profit_loss_value for t in trade])
        context['net_profit'] = sum([t.profit_loss_value_fees for t in trade])
        ...
        return context
</code>```

stats.html

```<code>            <form method="get" class="row">
                {{ filter.form.as_p }}
                {{ form.media }}

                <div class="col-xl-12">
                    <button class="btn btn-success float-right" type="submit">Apply</button>
                </div>
            </form>

            <table class="table table-striped">
                <tr>
                    <th scope="row">Net Profit <small>(Fees Included)</small></th>
                    <td>
                        {% if net_profit >= 0 %}
                        <font color="green">{{ net_profit|floatformat:2 }}</font>
                        {% else %}
                        <font color="red">{{ net_profit|floatformat:2 }}</font>
                        {% endif %}
                    </td>
                </tr>

                <tr>
                    <th scope="row">Gross Profit</th>
                    <td>{{ gross_profit|floatformat:2 }}</td>
                </tr>
</code>```

答:
The secret sauce that took me weeks to find out is so obvious. Run the calcs over the filter. Example below. Also you do not need to use aggregate. Works just as well with the original way I wrote above.

```<code>context['gross_profit'] = sum([t.profit_loss_value for t in trade])
</code>```

This is the key part:

```<code>trades = filter.qs.filter(status='cl')
</code>```

view.py

```<code>def get_context_data(self, *args, **kwargs):
    filter = StatsFilter(self.request.GET, queryset=self.get_queryset(), request=self.request)
    trades_count = filter.qs.filter(status='cl').count()
    trades = filter.qs.filter(status='cl')
    ...
    context['gross_profit'] = trades.aggregate(value=Sum('profit_loss_value'))['value']
</code>```

Body:
I'm using Django-Filter package which is working well for the one example they have in their documentation. However, I am not trying to generate a list of objects rather filter the calculations I have done on the object fields.

Example template: https://django-filter.readthedocs.io/en/stable/guide/usage.html#the-template

{% for obj in filter.qs %}
    {{ obj.name }} - ${{ obj.price }}

{% endfor %}

The problem here is that a list is created.. I'm looking for my trade "stats" to be updated based on the new filter selections.

I believe I need to set up my views differently and possibly call the template objects in another way as well but not totally sure.

filters.py

class StatsFilter(django_filters.FilterSet):
    class Meta:
        model = Trade
        fields = ['type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios']

views.py

class StatsView(LoginRequiredMixin, FilterView):
    model = Trade
    template_name = 'dashboard/stats.html'
    filterset_class = StatsFilter

    def get_form(self, *args, **kwargs):
        form = StatsFilter()
        user = self.request.user
        form.fields['associated_portfolios'].queryset = Portfolio.objects.filter(user=user)
        return form

    def get_context_data(self, *args, **kwargs):
        trade = Trade.objects.filter(user=self.request.user, status='cl').order_by('created')
        all_trades = Trade.objects.filter(user=self.request.user, status='cl').count()
        context = super(StatsView, self).get_context_data(*args, **kwargs)
        data = [t.profit_loss_value_fees for t in trade]

        context['all_trades'] = all_trades
        context['gross_profit'] = sum([t.profit_loss_value for t in trade])
        context['net_profit'] = sum([t.profit_loss_value_fees for t in trade])
        ...
        return context

stats.html

            <form method="get" class="row">
                {{ filter.form.as_p }}
                {{ form.media }}

                    <button class="btn btn-success float-right" type="submit">Apply</button>

            </form>

                    Net Profit (Fees Included)

                        {% if net_profit >= 0 %}
                        {{ net_profit|floatformat:2 }}
                        {% else %}
                        {{ net_profit|floatformat:2 }}
                        {% endif %}

                    Gross Profit
                    {{ gross_profit|floatformat:2 }}

Body:
The secret sauce that took me weeks to find out is so obvious. Run the calcs over the filter. Example below. Also you do not need to use aggregate. Works just as well with the original way I wrote above.

context['gross_profit'] = sum([t.profit_loss_value for t in trade])

This is the key part:

trades = filter.qs.filter(status='cl')

view.py

def get_context_data(self, *args, **kwargs):
    filter = StatsFilter(self.request.GET, queryset=self.get_queryset(), request=self.request)
    trades_count = filter.qs.filter(status='cl').count()
    trades = filter.qs.filter(status='cl')
    ...
    context['gross_profit'] = trades.aggregate(value=Sum('profit_loss_value'))['value']


问:
Error call javascript variable from php json_encode() because there is json label number
I get problem to call javascript variable from php json_encode().
At javascript, i can't get array.length because there are labels 1:.
I want [res_tmp] array get format like [sample] array (no label number array, example: 1:, 2:).
Thanks for your help.

Echo(false):

```<code>res_tmp: {
0: null,
1: {
name: "AAA",
sort: 1
},
2: {
name: "DDD",
sort: 2
},
...

</code>```

Echo(i wish):

```<code>res_tmp: {
 null,
{
name: "AAA",
sort: 1
},
{
name: "DDD",
sort: 2
},
...
</code>```

this is my code:

```<code>    $tmp = [

        [
         "name"  => "1.AAA",
         "sort"  => 1,
      ],[
         "name"  => "10.CCC",
         "sort"  => 10,
      ],[
         "name"  => "11.BBB",
         "sort"  => 11,
      ],[
         "name"  => "2.DDD",
         "sort"  => 2,
      ],[
         "name"  => "3.EEE",
         "sort"  => 3,
      ],
    ];

for ($i=0; $i < count($tmp); $i++) {
    $res_tmp[ $tmp[$i]['sort'] ] = $tmp[$i];
}

$nul = [0,4,5,6,7,8,9,12];
for ($j=0; $j < count($nul); $j++) {
  $res_tmp[ $nul[$j] ] = null;
}

$val = [
    "sample" => $tmp,
    "res_tmp" => $res_tmp,
];
echo json_encode($val);
// echo "```",print_r($val),"```";
</code>```

答:
welcome to SO. Here is a javascript approach.

What you have here is not an array but a JSON dict, which is an object. You can get the length of it in JavaScript using Object.keys:

```<code>let keys = Object.keys(res_tmp);
</code>```

This will get you the array of keys. You can iterate that and access the values. Like so:

```<code>let res_tmp = {
  0: null,
  1: {
    name: "AAA",
    sort: 1
  },
  2: {
    name: "DDD",
    sort: 2
  }
}
let keys = Object.keys(res_tmp);
let arr = [];
for (let j=0;j<keys.length;++j)
{
  let item = res_tmp[keys[j]];
  arr.push(item);
}
</code>```

Now arr holds the echo you wish.

Body:
I get problem to call javascript variable from php json_encode().
At javascript, i can't get array.length because there are labels 1:.
I want [res_tmp] array get format like [sample] array (no label number array, example: 1:, 2:).
Thanks for your help.

Echo(false):

res_tmp: {
0: null,
1: {
name: "AAA",
sort: 1
},
2: {
name: "DDD",
sort: 2
},
...

Echo(i wish):

res_tmp: {
 null,
{
name: "AAA",
sort: 1
},
{
name: "DDD",
sort: 2
},
...

this is my code:

    $tmp = [

        [
         "name"  => "1.AAA",
         "sort"  => 1,
      ],[
         "name"  => "10.CCC",
         "sort"  => 10,
      ],[
         "name"  => "11.BBB",
         "sort"  => 11,
      ],[
         "name"  => "2.DDD",
         "sort"  => 2,
      ],[
         "name"  => "3.EEE",
         "sort"  => 3,
      ],
    ];

for ($i=0; $i < count($tmp); $i++) {
    $res_tmp[ $tmp[$i]['sort'] ] = $tmp[$i];
}

$nul = [0,4,5,6,7,8,9,12];
for ($j=0; $j < count($nul); $j++) {
  $res_tmp[ $nul[$j] ] = null;
}

$val = [
    "sample" => $tmp,
    "res_tmp" => $res_tmp,
];
echo json_encode($val);
// echo "
",print_r($val),"
";

Body:
welcome to SO. Here is a javascript approach.

What you have here is not an array but a JSON dict, which is an object. You can get the length of it in JavaScript using Object.keys:

let keys = Object.keys(res_tmp);

This will get you the array of keys. You can iterate that and access the values. Like so:

let res_tmp = {
  0: null,
  1: {
    name: "AAA",
    sort: 1
  },
  2: {
    name: "DDD",
    sort: 2
  }
}
let keys = Object.keys(res_tmp);
let arr = [];
for (let j=0;j<keys.length;++j)
{
  let item = res_tmp[keys[j]];
  arr.push(item);
}

Now arr holds the echo you wish.


问:
How do I search through associations in metawhere in Rails 3?
When I was using searchlogic, I couuld use the following:

```<code>27 #      @todos = Todo.contact_user_id_is(current_user).
 28 #                    contact_campaign_id_is(@campaign).
 29 #                    current_date_lte(Date.today).
 30 #                    done_date_null.
 31 #                    ascend_by_contact_id.
 32 #                    ascend_by_current_date
</code>```

For example, it would allow me to search for the campaign belong to a contact that belonged to the Todo record.

This is what I've tried (not sure how to do the sorting:

```<code> 22       @todos = Todo.joins(:contacts).where(:user_id.eq => current_user,
 23                           :contacts => { :campaign_id.eq => @campaign.id},
 24                           :current_date.lteq => Date.today,
 25                           :done_date.not_eq => nil)
</code>```

How do I do something like that with metawhere?

答:
If Todo belongs_to or has_one contact, which I'm assuming is the case based on the Searchlogic query above, you would want to do something like (untested):</p>

```<code>@todos = Todo.joins(:contact).
              where(
                :contact => {
                  :user_id => current_user.id,
                  :campaign_id => @campaign.id
                },
                :current_date.lteq => Date.today,
                :done_date.not_eq => nil
              ).
              order(:contact_id, :current_date)
</code>```

Body:
When I was using searchlogic, I couuld use the following:

27 #      @todos = Todo.contact_user_id_is(current_user).
 28 #                    contact_campaign_id_is(@campaign).
 29 #                    current_date_lte(Date.today).
 30 #                    done_date_null.
 31 #                    ascend_by_contact_id.
 32 #                    ascend_by_current_date

For example, it would allow me to search for the campaign belong to a contact that belonged to the Todo record.

This is what I've tried (not sure how to do the sorting:

 22       @todos = Todo.joins(:contacts).where(:user_id.eq => current_user,
 23                           :contacts => { :campaign_id.eq => @campaign.id},
 24                           :current_date.lteq => Date.today,
 25                           :done_date.not_eq => nil)

How do I do something like that with metawhere?

Body:
If Todo belongs_to or has_one contact, which I'm assuming is the case based on the Searchlogic query above, you would want to do something like (untested):

@todos = Todo.joins(:contact).
              where(
                :contact => {
                  :user_id => current_user.id,
                  :campaign_id => @campaign.id
                },
                :current_date.lteq => Date.today,
                :done_date.not_eq => nil
              ).
              order(:contact_id, :current_date)


问:
Intellij IDEA: how hide main menu?
After installation of Enterprise Edition I see main menu only when hover a mouse to the up of the screen (with clock on the right). I accidentally pushed some button and now I can't hide main menu.

I am on Lubuntu.

答:
ctrl+shift+n ->
actions tab ->
main menu

Title: Intellij IDEA: how hide main menu?