问:
Flask - URL is wrong when i login
I have a problem today, and i need to resolve it to pass in another task.
When I want to log in, the connection is done without problem, however when I connect the url remains in "http://127.0.0.1/login" but displays my page index.html on this link. And I don't understand why I can't directly go to my "http://127.0.0.1/index" directory directly with my index.html.
At the end of my login function, instead of putting "return render_template('index.html', **templateData)" I put "index()" directly as in logout but I have the error code 500

I can share all of my directory python if you need.

Best regards
(sorry for my bad english .. !)

```<code>@app.route("/")
@app.route("/index")
def index():
    if not session.get('logged_in'):
        return render_template('login.html')
    else:
        if app.NOM == '':
            return render_template('login.html', login=1)
        else:
            var = "SELECT users.prenom, users.nom, data.bpm, data.oxy, data.chute FROM data, users WHERE users.ID = '" + str(app.ID) + "' AND data.User = '" + str(app.ID) + "' ORDER BY data.User DESC LIMIT 1 "
            try:
                cur = bdd_login()
            except pymysql.Error as e:
                return session_out(e)
            result = cur.execute(var)
            cur.close()
            print(result)
            if not result:
                bpm = 0
                oxy = 0
                chute = 0
            else:
                for row in cur:
                    print(row)
                bpm = row[2]
                oxy = row[3]
                chute = row[4]
                templateData = {'prenom': app.PRENOM, 'nom': app.NOM, 'rank': app.RANK, 'bpm': bpm, 'oxy': oxy}
                if bpm < 40 or bpm > 100:
                    if oxy < 80:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=0, state_oxy=0, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=0, state_oxy=0, state_chute=1)
                    elif 95 <= oxy <= 100:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=0, state_oxy=1, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=0, state_oxy=1, state_chute=1)
                    elif 80 <= oxy < 95:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=0, state_oxy=2, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=0, state_oxy=2, state_chute=1)
                elif 60 <= bpm <= 80:
                    if oxy < 80:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=1, state_oxy=0, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=1, state_oxy=0, state_chute=1)
                    elif 95 <= oxy <= 100:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=1, state_oxy=1, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=1, state_oxy=1, state_chute=1)
                    elif 80 <= oxy < 95:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=1, state_oxy=2, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=1, state_oxy=2, state_chute=1)
                elif 40 <= bpm < 60 or 80 < bpm <= 100:
                    if oxy < 80:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=2, state_oxy=0, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=2, state_oxy=0, state_chute=1)
                    elif 95 <= oxy <= 100:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=2, state_oxy=1, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=2, state_oxy=1, state_chute=1)
                    elif 80 <= oxy < 95:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=2, state_oxy=2, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=2, state_oxy=2, state_chute=1)

@app.route("/login", methods=['POST'])
def login():
    POST_NAME = str(request.form['nom'])
    POST_PRENOM = str(request.form['prenom'])
    POST_PASSWORD = str(request.form['password'])
    var = "SELECT id, nom, prenom, password, privilege FROM users WHERE nom = '" + POST_NAME + "' AND password = '" + POST_PASSWORD + "' AND prenom = '" + POST_PRENOM + "'"
    try:
        cur = bdd_login()
    except pymysql.Error as e:
        return session_out(e)
    result = cur.execute(var)
    cur.close()
    for row in cur:
        print(row)
    if result:
        session.permanent = True
        session['logged_in'] = True
        session['prenom'] = POST_PRENOM
        session['nom'] = POST_NAME
        session['ID'] = row[0]
        if row[4] == 'patient':
            session['rank'] = 0
        if row[4] == 'proche':
            session['rank'] = 1
        if row[4] == 'med':
            session['rank'] = 2
        if row[4] == 'admin':
            session['rank'] = 3
        app.NOM = session['nom']
        app.PRENOM = session['prenom']
        app.RANK = session['rank']
        app.ID = session['ID']
        templateData = {'prenom': app.PRENOM, 'nom': app.NOM, 'rank': app.RANK}
        return render_template('index.html', **templateData)
    else:
        return render_template('login.html', login=0)

@app.route("/logout")
def logout():
    session['logged_in'] = False
    session.pop('prenom', None)
    session.pop('nom', None)
    session.pop('ID', None)
    session.pop('rank', None)
    app.PRENOM = ""
    app.NOM = ""
    app.RANK = ""
    app.ID = ""
    return index()
</code>```

答:
if I understood correctly, you are dealing with below problems

After login, its showing index page but URL is not changing.

after logout its throwing error.

basically you are rendering index.html template inside login route, you have to redirect after a successful login request.

you can not directly call index() inside logout, treat these as routes not like normal functions

Title: Flask - URL is wrong when i login

Body:
I have a problem today, and i need to resolve it to pass in another task.
When I want to log in, the connection is done without problem, however when I connect the url remains in "http://127.0.0.1/login" but displays my page index.html on this link. And I don't understand why I can't directly go to my "http://127.0.0.1/index" directory directly with my index.html.
At the end of my login function, instead of putting "return render_template('index.html', **templateData)" I put "index()" directly as in logout but I have the error code 500

I can share all of my directory python if you need.

Best regards
(sorry for my bad english .. !)

@app.route("/")
@app.route("/index")
def index():
    if not session.get('logged_in'):
        return render_template('login.html')
    else:
        if app.NOM == '':
            return render_template('login.html', login=1)
        else:
            var = "SELECT users.prenom, users.nom, data.bpm, data.oxy, data.chute FROM data, users WHERE users.ID = '" + str(app.ID) + "' AND data.User = '" + str(app.ID) + "' ORDER BY data.User DESC LIMIT 1 "
            try:
                cur = bdd_login()
            except pymysql.Error as e:
                return session_out(e)
            result = cur.execute(var)
            cur.close()
            print(result)
            if not result:
                bpm = 0
                oxy = 0
                chute = 0
            else:
                for row in cur:
                    print(row)
                bpm = row[2]
                oxy = row[3]
                chute = row[4]
                templateData = {'prenom': app.PRENOM, 'nom': app.NOM, 'rank': app.RANK, 'bpm': bpm, 'oxy': oxy}
                if bpm < 40 or bpm > 100:
                    if oxy < 80:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=0, state_oxy=0, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=0, state_oxy=0, state_chute=1)
                    elif 95 <= oxy <= 100:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=0, state_oxy=1, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=0, state_oxy=1, state_chute=1)
                    elif 80 <= oxy < 95:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=0, state_oxy=2, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=0, state_oxy=2, state_chute=1)
                elif 60 <= bpm <= 80:
                    if oxy < 80:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=1, state_oxy=0, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=1, state_oxy=0, state_chute=1)
                    elif 95 <= oxy <= 100:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=1, state_oxy=1, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=1, state_oxy=1, state_chute=1)
                    elif 80 <= oxy < 95:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=1, state_oxy=2, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=1, state_oxy=2, state_chute=1)
                elif 40 <= bpm < 60 or 80 < bpm <= 100:
                    if oxy < 80:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=2, state_oxy=0, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=2, state_oxy=0, state_chute=1)
                    elif 95 <= oxy <= 100:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=2, state_oxy=1, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=2, state_oxy=1, state_chute=1)
                    elif 80 <= oxy < 95:
                        if chute == 0:
                            return render_template('index.html', **templateData, state_bpm=2, state_oxy=2, state_chute=0)
                        else:
                            return render_template('index.html', **templateData, state_bpm=2, state_oxy=2, state_chute=1)

@app.route("/login", methods=['POST'])
def login():
    POST_NAME = str(request.form['nom'])
    POST_PRENOM = str(request.form['prenom'])
    POST_PASSWORD = str(request.form['password'])
    var = "SELECT id, nom, prenom, password, privilege FROM users WHERE nom = '" + POST_NAME + "' AND password = '" + POST_PASSWORD + "' AND prenom = '" + POST_PRENOM + "'"
    try:
        cur = bdd_login()
    except pymysql.Error as e:
        return session_out(e)
    result = cur.execute(var)
    cur.close()
    for row in cur:
        print(row)
    if result:
        session.permanent = True
        session['logged_in'] = True
        session['prenom'] = POST_PRENOM
        session['nom'] = POST_NAME
        session['ID'] = row[0]
        if row[4] == 'patient':
            session['rank'] = 0
        if row[4] == 'proche':
            session['rank'] = 1
        if row[4] == 'med':
            session['rank'] = 2
        if row[4] == 'admin':
            session['rank'] = 3
        app.NOM = session['nom']
        app.PRENOM = session['prenom']
        app.RANK = session['rank']
        app.ID = session['ID']
        templateData = {'prenom': app.PRENOM, 'nom': app.NOM, 'rank': app.RANK}
        return render_template('index.html', **templateData)
    else:
        return render_template('login.html', login=0)

@app.route("/logout")
def logout():
    session['logged_in'] = False
    session.pop('prenom', None)
    session.pop('nom', None)
    session.pop('ID', None)
    session.pop('rank', None)
    app.PRENOM = ""
    app.NOM = ""
    app.RANK = ""
    app.ID = ""
    return index()


来源: stackexchange

问:
How to configure PHP for automatical regular removing of session data / sess_ files?
The PHP session data is stored on the server side in sess_{$hash} files in the directory defined in the session.save_path setting of php.ini.

If my understanding is correct, these files should get removed after a defined period of time. How to get and how to set this time? I tried settings session.cache_expire and session.gc_maxlifetime. E.g. I set session.cache_expire to 2 (minutes), but after two minutes the files are still there. I also set session.gc_maxlifetime to 120 (seconds). But this also didn't work.

How to configure PHP to get the sess_* files being removed after a defined period of time?

答:
The session.gc_maxlifetime is what defines when sessions data is marked for garbage collection (not necessarily when it's deleted). The actual deletion of that data depends on a number of variables. Most prominently the session.gc_probability and session.gc_divisor. The probability over the divisor determine the chance that the session initialization process will invoke the garbage collector to clean up marked garbage. By default they are 1 and 100, respectively (meaning there is a 1% chance the garbage collector will clean up).

This is PHP's default mechanism for garabage collection of session data. However, on some systems (most notably Ubuntu) the default session GC is replaced by an external cleanup mechanism which is implemented as a cron job that runs regularly to clean up session files based on stat calls and the session.gc_maxlifetime.

You tend not to notice these side effects on a busy site, as the number of session_start() calls increase, the probability that stale session data is regularly cleaned up increases. However, on a low traffic site (namely your development environment) this probability drops significantly enough that you might notice stale session data hanging around for a while. This is typically not something to be concerned with. As long as you are deleting the session cookie and regularly using session_destroy() when the session needs to be deleted, this is all moot.

ContentLicense: CC BY-SA 4.0


问:
EF Core Update Linked Object
I am trying to update a company and its contact details as in the example JSON request using EF Core

```<code>PUT https://localhost:6001/api/Company

{
  "CompanyId": 6,
  "Name": "string",
  "ContactDetail": {
    "Name": "string",
    "EmailAddress": "string",
    "Address1": "string",
    "Address2": "string",
    "Address3": "string",
    "PostCode": "string",
    "Telephone": "string"
  }
}
</code>```

The generated EF Scaffold looks like this

```<code>public partial class Company
{
    public long CompanyId { get; set; }
    public string Name { get; set; }
    public virtual ContactDetail ContactDetail { get; set; }
}

public partial class ContactDetail
{
    public ContactDetail()
    {
        Company = new HashSet<Company>();
    }

    public long ContactDetailId { get; set; }
    public string Name { get; set; }
    public string EmailAddress { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Address3 { get; set; }
    public string PostCode { get; set; }
    public string Telephone { get; set; }

    public virtual ICollection<Company> Company { get; set; }
}
</code>```

How can I update the ContactDetail in the cleanest way possible, if I was to provide the ContactDetailId then I presume it would all work fine, but ideally I only want to provide the CompanyId of the parent object.
The following code updates the Company but creates a new entry for the ContactDetail!?

```<code>  public Copmany Update(Copmany company)
  {
      _bigLoaderContext.Update(company);
      _bigLoaderContext.SaveChanges();

      return GetById(company.CompanyId);
  }
</code>```

Update - A solution I have now used is to get the ContactDetail id and then reassign it to the object.

```<code>public Company Update(Company company)
{
    var currentCompany = GetById(companyId, true);

    // Update the contact detail id so that it know what one to update
    company.ContactDetail.ContactDetailId = currentCompany.ContactDetailId;

    _bigLoaderContext.Update(company);
    _bigLoaderContext.SaveChanges();
}
</code>```

I was getting an error loading the object to get the value, so had to get it with the AsNoTracking in the GetById method.

```<code>_bigLoaderContext.Company.AsNoTracking().FirstOrDefault(f => f.CompanyId == companyId);
</code>```

答:
A solution I have now used is to get the ContactDetail id and then reassign it to the object.

```<code>public Company Update(Company company)
{
    var currentCompany = GetById(companyId, true);

    // Update the contact detail id so that it know what one to update
    company.ContactDetail.ContactDetailId = currentCompany.ContactDetailId;

    _bigLoaderContext.Update(company);
    _bigLoaderContext.SaveChanges();
}
</code>```

I was getting an error loading the object to get the value, so had to get it with the AsNoTracking in the GetById method.

```<code>_bigLoaderContext.Company.AsNoTracking().FirstOrDefault(f => f.CompanyId == companyId);
</code>```

Presume this is ok as it works!?

Title: EF Core Update Linked Object

Body:
I am trying to update a company and its contact details as in the example JSON request using EF Core

PUT https://localhost:6001/api/Company

{
  "CompanyId": 6,
  "Name": "string",
  "ContactDetail": {
    "Name": "string",
    "EmailAddress": "string",
    "Address1": "string",
    "Address2": "string",
    "Address3": "string",
    "PostCode": "string",
    "Telephone": "string"
  }
}

The generated EF Scaffold looks like this

public partial class Company
{
    public long CompanyId { get; set; }
    public string Name { get; set; }
    public virtual ContactDetail ContactDetail { get; set; }
}

public partial class ContactDetail
{
    public ContactDetail()
    {
        Company = new HashSet<Company>();
    }

    public long ContactDetailId { get; set; }
    public string Name { get; set; }
    public string EmailAddress { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Address3 { get; set; }
    public string PostCode { get; set; }
    public string Telephone { get; set; }

    public virtual ICollection<Company> Company { get; set; }
}

How can I update the ContactDetail in the cleanest way possible, if I was to provide the ContactDetailId then I presume it would all work fine, but ideally I only want to provide the CompanyId of the parent object.
The following code updates the Company but creates a new entry for the ContactDetail!?

  public Copmany Update(Copmany company)
  {
      _bigLoaderContext.Update(company);
      _bigLoaderContext.SaveChanges();

      return GetById(company.CompanyId);
  }

Update - A solution I have now used is to get the ContactDetail id and then reassign it to the object.

public Company Update(Company company)
{
    var currentCompany = GetById(companyId, true);

    // Update the contact detail id so that it know what one to update
    company.ContactDetail.ContactDetailId = currentCompany.ContactDetailId;

    _bigLoaderContext.Update(company);
    _bigLoaderContext.SaveChanges();
}

I was getting an error loading the object to get the value, so had to get it with the AsNoTracking in the GetById method.

_bigLoaderContext.Company.AsNoTracking().FirstOrDefault(f => f.CompanyId == companyId);

Body:
A solution I have now used is to get the ContactDetail id and then reassign it to the object.

public Company Update(Company company)
{
    var currentCompany = GetById(companyId, true);

    // Update the contact detail id so that it know what one to update
    company.ContactDetail.ContactDetailId = currentCompany.ContactDetailId;

    _bigLoaderContext.Update(company);
    _bigLoaderContext.SaveChanges();
}

I was getting an error loading the object to get the value, so had to get it with the AsNoTracking in the GetById method.

_bigLoaderContext.Company.AsNoTracking().FirstOrDefault(f => f.CompanyId == companyId);

Presume this is ok as it works!?


问:
automatically formatting code with prettier with onchange not working
i want to format the file with prettier whenever the file changes. So i run this command to achieve that

```<code>onchange '**/*.js' -- prettier --write {{changed}}
</code>```

This works absolutely fine when run through terminal, listen file changes and formats it.

But when i add this command as npm script in package.json it and execute it with npm run prettier-watch

it starts listening to changes but it doesn't format code when file is changed.

package.json

```<code>{
  "name": "pwa-svelte-rollup-template",
  "private": true,
  "scripts": {
    "start": "run-p serve autobuild",
    "serve": "sirv public --dev",
    "build": "rollup -c",
    "autobuild": "rollup -c -w",
    "clean": "rimraf public/bundle.*",
    "prettier-watch": "onchange '**/*.js' -- prettier --write {{changed}}"
  },
  "devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/plugin-proposal-class-properties": "^7.5.5",
    "@babel/preset-env": "^7.5.5",
    "babel-core": "^7.0.0-bridge.0",
    "babel-eslint": "^10.0.2",
    "babel-jest": "^24.8.0",
    "eslint": "^6.1.0",
    "eslint-config-standard": "^13.0.1",
    "eslint-plugin-import": "^2.18.2",
    "eslint-plugin-jest": "^22.14.0",
    "eslint-plugin-node": "^9.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.0",
    "node-sass": "^4.12.0",
    "npm-run-all": "^4.1.5",
    "onchange": "^6.0.0",
    "prettier": "^1.18.2",
    "rimraf": "^2.6.3",
    "rollup": "^1.17.0",
    "rollup-plugin-babel": "^4.3.3",
    "rollup-plugin-commonjs": "^10.0.1",
    "rollup-plugin-livereload": "^1.0.1",
    "rollup-plugin-node-resolve": "^5.2.0",
    "rollup-plugin-svelte": "^5.1.0",
    "rollup-plugin-terser": "^5.1.1",
    "sirv-cli": "^0.4.4",
    "svelte": "^3.6.9",
    "svelte-preprocess-sass": "^0.2.0"
  },
  "babel": {
    "presets": [
      [
        "@babel/preset-env",
        {
          "useBuiltIns": "entry",
          "corejs": "3.0.0"
        }
      ]
    ],
    "plugins": [
      [
        "@babel/plugin-proposal-class-properties"
      ]
    ],
    "sourceMaps": true
  },
  "browserslist": [
    "last 2 versions",
    "not dead",
    "not IE 11",
    "not < 0.2%"
  ],
  "eslintConfig": {
    "extends": [
      "standard"
    ],
    "env": {
      "browser": true,
      "serviceworker": true,
      "jest": true
    },
    "parser": "babel-eslint",
    "parserOptions": {
      "ecmaVersion": 8,
      "ecmaFeatures": {
        "experimentalObjectRestSpread": true
      },
      "sourceType": "module"
    }
  },
  "eslintIgnore": [
    ".cache",
    "dist",
    "node_modules"
  ]
}

</code>```

please tell me if i am doing something wrong

答:
I had same issue.
Change your prettier-watch script to this "onchange \"**/*.js\" -- prettier --write {{changed}}"

Body:
i want to format the file with prettier whenever the file changes. So i run this command to achieve that

onchange '**/*.js' -- prettier --write {{changed}}

This works absolutely fine when run through terminal, listen file changes and formats it.

But when i add this command as npm script in package.json it and execute it with npm run prettier-watch

it starts listening to changes but it doesn't format code when file is changed.

package.json

{
  "name": "pwa-svelte-rollup-template",
  "private": true,
  "scripts": {
    "start": "run-p serve autobuild",
    "serve": "sirv public --dev",
    "build": "rollup -c",
    "autobuild": "rollup -c -w",
    "clean": "rimraf public/bundle.*",
    "prettier-watch": "onchange '**/*.js' -- prettier --write {{changed}}"
  },
  "devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/plugin-proposal-class-properties": "^7.5.5",
    "@babel/preset-env": "^7.5.5",
    "babel-core": "^7.0.0-bridge.0",
    "babel-eslint": "^10.0.2",
    "babel-jest": "^24.8.0",
    "eslint": "^6.1.0",
    "eslint-config-standard": "^13.0.1",
    "eslint-plugin-import": "^2.18.2",
    "eslint-plugin-jest": "^22.14.0",
    "eslint-plugin-node": "^9.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.0",
    "node-sass": "^4.12.0",
    "npm-run-all": "^4.1.5",
    "onchange": "^6.0.0",
    "prettier": "^1.18.2",
    "rimraf": "^2.6.3",
    "rollup": "^1.17.0",
    "rollup-plugin-babel": "^4.3.3",
    "rollup-plugin-commonjs": "^10.0.1",
    "rollup-plugin-livereload": "^1.0.1",
    "rollup-plugin-node-resolve": "^5.2.0",
    "rollup-plugin-svelte": "^5.1.0",
    "rollup-plugin-terser": "^5.1.1",
    "sirv-cli": "^0.4.4",
    "svelte": "^3.6.9",
    "svelte-preprocess-sass": "^0.2.0"
  },
  "babel": {
    "presets": [
      [
        "@babel/preset-env",
        {
          "useBuiltIns": "entry",
          "corejs": "3.0.0"
        }
      ]
    ],
    "plugins": [
      [
        "@babel/plugin-proposal-class-properties"
      ]
    ],
    "sourceMaps": true
  },
  "browserslist": [
    "last 2 versions",
    "not dead",
    "not IE 11",
    "not < 0.2%"
  ],
  "eslintConfig": {
    "extends": [
      "standard"
    ],
    "env": {
      "browser": true,
      "serviceworker": true,
      "jest": true
    },
    "parser": "babel-eslint",
    "parserOptions": {
      "ecmaVersion": 8,
      "ecmaFeatures": {
        "experimentalObjectRestSpread": true
      },
      "sourceType": "module"
    }
  },
  "eslintIgnore": [
    ".cache",
    "dist",
    "node_modules"
  ]
}

please tell me if i am doing something wrong


问:
Remove last char in a string for each row in pandas df
I have a pandas dataframe with column keys, I need to remove the last character from each string.

```<code>id       keys
123      "https://www.cosmopolitan.com/entertainment/tv/a46533/"
124      "https://www.bazaar.com/entertainment/tv/a46533/"
</code>```

Currently, I am trying to create a function that would return a clean string and I would apply the function to df later. I tried the following:

```<code>url_test = "https://www.cosmopolitan.com/entertainment/tv/"

def clean_string(url):
    for string in url:
        new_string = string[:-1]
        return new_string
clean_string(url_test)
</code>```

It returns an empty string. And I want it to return "url_test = "https://www.cosmopolitan.com/entertainment/tv"

答:
You can use pandas string accessor methods

e.g.

```<code>import pandas as pd
test = pd.Series([
    "https://www.cosmopolitan.com/entertainment/tv/a46533/",
    "https://www.bazaar.com/entertainment/tv/a46533/"])
test = test.str[:-1]
</code>```

will trim the last character from the string. This allows you to operate on the entire column rather than one row at a time.

Body:
I have a pandas dataframe with column keys, I need to remove the last character from each string.

id       keys
123      "https://www.cosmopolitan.com/entertainment/tv/a46533/"
124      "https://www.bazaar.com/entertainment/tv/a46533/"

Currently, I am trying to create a function that would return a clean string and I would apply the function to df later. I tried the following:

url_test = "https://www.cosmopolitan.com/entertainment/tv/"

def clean_string(url):
    for string in url:
        new_string = string[:-1]
        return new_string
clean_string(url_test)

It returns an empty string. And I want it to return "url_test = "https://www.cosmopolitan.com/entertainment/tv"

Body:
You can use pandas string accessor methods

e.g.

import pandas as pd
test = pd.Series([
    "https://www.cosmopolitan.com/entertainment/tv/a46533/",
    "https://www.bazaar.com/entertainment/tv/a46533/"])
test = test.str[:-1]

will trim the last character from the string. This allows you to operate on the entire column rather than one row at a time.


问:
discord bot doesn't answer the key word
I wrote the code on pycharm to create a discord bot.

Some of the code works but some does not.

This is my code:

```<code>import discord

client = discord.Client()

@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
    id = client.get_guild(676561378265399296)
    print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}")
    if message.content_find("!Hello"):
        await message.channel_send("hi ")
</code>```

And then this is the error:

```<code>Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\no0x\AppData\Local\Programs\Python\venv\lib\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)`enter code here`
  File "C:/Users/no0x/AppData/Local/Programs/bot/bot.py", line 18, in on_message
    if message.content_find("!Hello"):
AttributeError: 'Message' object has no attribute 'content_find'
</code>```

答:
The Message object doesn't have a content_find-attribute. Although it has a content-attribute, declared as a string, which can use the find()-method.

What you probably meant to do was if (message.content.find("!Hello") >= 0):, which checks if the message content contains the string !Hello. If you want to check if the message starts with !Hello, alter the comparator to ==; alternatively you can use startswith().

Title: discord bot doesn't answer the key word

Body:
I wrote the code on pycharm to create a discord bot.

Some of the code works but some does not.

This is my code:

import discord

client = discord.Client()

@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
    id = client.get_guild(676561378265399296)
    print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}")
    if message.content_find("!Hello"):
        await message.channel_send("hi ")

And then this is the error:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\no0x\AppData\Local\Programs\Python\venv\lib\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)`enter code here`
  File "C:/Users/no0x/AppData/Local/Programs/bot/bot.py", line 18, in on_message
    if message.content_find("!Hello"):
AttributeError: 'Message' object has no attribute 'content_find'


问:
How can I pass more than one enum to a method that receives only one?
I'm wondering if the following is possible:

The method Regex.Match can receive an enum, so I can specify:

```<code>RegexOptions.IgnoreCase
RegexOptions.IgnorePatternWhiteSpace
RegexOptions.Multiline
</code>```

What if I need to specify more than just one? (eg. I want my regex to be Multiline and I want it to ignore the pattern whitespace).

Could I use | operator like in C/C++?

答:
Just to enhance the answers a bit, the Flags attribute is not a requirement. Every enum value can be combined with the bitwise | operator. The Flags attribute only makes the enum a bit more readable when converted into a string (eg. instead of seeing a number with the bitwise result as a number, you see the selected flags combined).

To test if a condition is set you normally would use a bitwise &. This will also work without the Flags attribute.

In the MSDN documentation for this attribute there is an example of two enums, one with and the other without it: FlaggsAttribute.

ContentLicense: CC BY-SA 3.0

Body:
I'm wondering if the following is possible:

The method Regex.Match can receive an enum, so I can specify:

RegexOptions.IgnoreCase
RegexOptions.IgnorePatternWhiteSpace
RegexOptions.Multiline

What if I need to specify more than just one? (eg. I want my regex to be Multiline and I want it to ignore the pattern whitespace).

Could I use | operator like in C/C++?


问:
Regex to find a single character within a python list
I am trying to determine if a python list item has a single character in it and if so replace it with an uncontracted version. The issue I am facing is that I cannot get it to detect a single letter (X) without it converting say boxer -> bocrossbreeder

```<code>list = ['canine', 'dog', 'X', 'boxer', 'XBreed', ' x ']
list_trimmed = [re.sub(r'\040x\040', 'CrossBreed', lst) for lst in list]
</code>```

works okay for removing the ' x ' but if i try

```<code>list_trimmed = [re.sub(r'x', 'CrossBreed', lst) for lst in list]
</code>```

it creates boCrossBreeder as it detects the x in a word in the list item.

答:
Try this.

```<code>list_trimmed = [re.sub(r'\b[Xx]\b', 'CrossBreed', lst) for lst in list]
</code>```

\b.\b

Detects if its a single character

[Xx]

To detect capital and small both

Body:
I am trying to determine if a python list item has a single character in it and if so replace it with an uncontracted version. The issue I am facing is that I cannot get it to detect a single letter (X) without it converting say boxer -> bocrossbreeder

list = ['canine', 'dog', 'X', 'boxer', 'XBreed', ' x ']
list_trimmed = [re.sub(r'\040x\040', 'CrossBreed', lst) for lst in list]

works okay for removing the ' x ' but if i try

list_trimmed = [re.sub(r'x', 'CrossBreed', lst) for lst in list]

it creates boCrossBreeder as it detects the x in a word in the list item.

Body:
Try this.

list_trimmed = [re.sub(r'\b[Xx]\b', 'CrossBreed', lst) for lst in list]

\b.\b

Detects if its a single character

[Xx]

To detect capital and small both


问:
Issues with Firebase web development tutorial in codelabs.com
I am new in Firebase web development and currently using this website to learn it. The tutorial was straight-forward enough, but there's a few pages I don't get it.

1 . On page 7, the tutorial shows how to connect Google auth sign in with a button. I'm familiar with HTML code where every button has it's own onclick event to call a function in javascript. However, in the code, there's no onclick event is triggered and yet the button calls the function. How is this possible?

```<code>//Button code in index.html
<button hidden id="sign-out" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-color-text--white">
Sign-out
</button>

//Script to call the function in main.js
function signIn() {
    var provider = new firebase.auth.GoogleAuthProvider();
    firebase.auth().signInWithPopup(provider);
}
</code>```

On page 8, I didn't managed to get the output displayed in that page. I copied and paste the code to my main.js and yet nothing happened. I'm not sure how to debug this.

Can anyone advise me on how to continue this? Thank you.

答:
For your first question: when you started the codelab, you created a copy of the starter project. That project contains a default implementation of signIn:

```<code>// Signs-in Friendly Chat.
function signIn() {
  alert('TODO: Implement Google Sign-In');
  // TODO 1: Sign in Firebase with credential from the Google user.
}
</code>```

You then implement this method in step 7, so that it becomes:

```<code>// Signs-in Friendly Chat.
function signIn() {
  // Sign in Firebase using popup auth and Google as the identity provider.
  var provider = new firebase.auth.GoogleAuthProvider();
  firebase.auth().signInWithPopup(provider);
}
</code>```

This signIn method you implement is already hooked up to the button in the HTML in the starter project, with this code near the bottom of main.js:

```<code>signInButtonElement.addEventListener('click', signIn);
</code>```

Body:
I am new in Firebase web development and currently using this website to learn it. The tutorial was straight-forward enough, but there's a few pages I don't get it.

1 . On page 7, the tutorial shows how to connect Google auth sign in with a button. I'm familiar with HTML code where every button has it's own onclick event to call a function in javascript. However, in the code, there's no onclick event is triggered and yet the button calls the function. How is this possible?

//Button code in index.html
<button hidden id="sign-out" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-color-text--white">
Sign-out
</button>

//Script to call the function in main.js
function signIn() {
    var provider = new firebase.auth.GoogleAuthProvider();
    firebase.auth().signInWithPopup(provider);
}

On page 8, I didn't managed to get the output displayed in that page. I copied and paste the code to my main.js and yet nothing happened. I'm not sure how to debug this.

Can anyone advise me on how to continue this? Thank you.

Body:
For your first question: when you started the codelab, you created a copy of the starter project. That project contains a default implementation of signIn:

// Signs-in Friendly Chat.
function signIn() {
  alert('TODO: Implement Google Sign-In');
  // TODO 1: Sign in Firebase with credential from the Google user.
}

You then implement this method in step 7, so that it becomes:

// Signs-in Friendly Chat.
function signIn() {
  // Sign in Firebase using popup auth and Google as the identity provider.
  var provider = new firebase.auth.GoogleAuthProvider();
  firebase.auth().signInWithPopup(provider);
}

This signIn method you implement is already hooked up to the button in the HTML in the starter project, with this code near the bottom of main.js:

signInButtonElement.addEventListener('click', signIn);


问:
Uninstall Chrome silently using Powershell
I have the following PowerShell script, which I am using to get the uninstall string for Google Chrome, and then I want to uninstall it silently. Line 3 in the script will pop up the GUI uninstaller (so it seems like everything is correct thus far), but if I add "/qn" or "/quiet" to the argument list, the uninstall doesn't seem to run at all, even if I let it sit for a couple hours.

What am I missing?

```<code>    $AppName = "Google Chrome"
    $Chrome = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object {$_.DisplayName -match $($AppName)}
    Start-Process -Wait -FilePath MsiExec.exe -Argumentlist "/X",$Chrome.UninstallString.TrimStart("MsiExec.exe /X")
</code>```

答:
If it's an msi you can use uninstall-package:</p>

```<code>get-package *chrome* | uninstall-package -whatif
</code>```

Body:
I have the following PowerShell script, which I am using to get the uninstall string for Google Chrome, and then I want to uninstall it silently. Line 3 in the script will pop up the GUI uninstaller (so it seems like everything is correct thus far), but if I add "/qn" or "/quiet" to the argument list, the uninstall doesn't seem to run at all, even if I let it sit for a couple hours.

What am I missing?

    $AppName = "Google Chrome"
    $Chrome = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object {$_.DisplayName -match $($AppName)}
    Start-Process -Wait -FilePath MsiExec.exe -Argumentlist "/X",$Chrome.UninstallString.TrimStart("MsiExec.exe /X")

Body:
If it's an msi you can use uninstall-package:

get-package *chrome* | uninstall-package -whatif


问:
Issues with template class conversion - unable to deduce function called
How do I make the following code work properly?

The non-template version compiles perfectly but the template version fails miserably. Why template version fails to figure out which function version to call and how to fix it? I thought about adding to template class AT operator that implicitly converts to BT but it doesn't work either.

```<code>class A {};

class B
{
    public:
    B(A){};
};

void func(B){};

template<typename T>
class AT {};

template<typename T>
class BT
{
    public:
    BT(AT<T>){};
};

template<typename T>
void funcT(BT<T>){};

int main()
{
    func(A{});
    funcT(AT<int>{}); // unable to deduce the funcT template argument
    funcT<int>(AT<int>{}); // compiles but I don't want to write that

    return 0;
}
</code>```

There are dumb fixes like writing function version that accepts AT<T> and casts it to BT<T>. But I don't want to write a bunch of functions when everything should work as is. I could understand it if it was an ambiguous call...

答:
Implicit conversion won't be considered in template argument deduction:

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.

That means, for funcT which expects a BT<T> but passed a AT<int>, T can't be deduced and the fails to be called.

The workaround, as you showed, is to specify template argument explicitly to bypass the template argument deduction.

Non-template functions don't have such issue; they don't require template argument deduction.

Body:
How do I make the following code work properly?

The non-template version compiles perfectly but the template version fails miserably. Why template version fails to figure out which function version to call and how to fix it? I thought about adding to template class AT operator that implicitly converts to BT but it doesn't work either.

class A {};

class B
{
    public:
    B(A){};
};

void func(B){};

template<typename T>
class AT {};

template<typename T>
class BT
{
    public:
    BT(AT<T>){};
};

template<typename T>
void funcT(BT<T>){};

int main()
{
    func(A{});
    funcT(AT<int>{}); // unable to deduce the funcT template argument
    funcT<int>(AT<int>{}); // compiles but I don't want to write that

    return 0;
}

There are dumb fixes like writing function version that accepts AT<T> and casts it to BT<T>. But I don't want to write a bunch of functions when everything should work as is. I could understand it if it was an ambiguous call...


问:
Calling one ModalPopupExtender from two different buttons?
I have a panel that is hooked up to a ModalPopupExtender but it can be called two different ways, by either adding a user (one button click) or editing a user (a totally different button click).  The controls on the panel never change, but they are all blank when adding, or they are binded to the data of the particular user being edited.  What should I set the TargetControlID attribute to when I have two different buttons that need to open the same panel as a modal window?  </p>

答: My recommendation is to have 2 modalpopupextenders, both using the same PopupControlID for the panel you want to display in both instances.</p>

ContentLicense: CC BY-SA 2.5


问:
How to input a parameter in a custom target with cmake
I have a custom target:

```<code> add_custom_target(
      create-po
      COMMAND ${MSGINIT} --no-translator -i "${PROJECT_SOURCE_DIR}/data/${PACKAGE}.pot" - "${PROJECT_SOURCE_DIR}/po/es.po" -l es_MX.utf8
 )
</code>```

so, is invoked like this:

```<code> # make create-po
</code>```

my idea is to change it to something like this:

```<code> # make create-po "es"
</code>```

so, any user can create a custom localed po file. I don't know the word exactly for this, but I'd like to add a parameter in the target name..is it posible with cmake? Thanks

答:
After so long time I found this question for the same reason: Can I use CMake to initialize a .po file if I want to add a new translation? I expect to use it only once in a while for my project, so make the build system do it seems more comfortable to me than find out all the required options and paths every time.

I ended up with the following CMake snippet:

```<code>set(INIT_LANG CACHE STRING "give a locale here to create a target which initializes a related .po file")
IF(INIT_LANG)
  add_custom_target(
    create-po-${INIT_LANG}
    ... # integrate INIT_LANG in your command
  )
ENDIF(INIT_LANG)
</code>```

Then, if you want to initialize a new translation file, call (assuming your build dir in under the project root):

```<code># cmake -DINIT_LANG=es_MX.utf8 ..
</code>```

... and you should get a corresponding make target:

```<code># make create-po-es_MX.utf8
</code>```

Yes, it's not as straight-forward as the OP's idea/expectation (and mine as well), but users can create new .po files by themselves (of course, this will be documented properly for them in the project ;) ).

Body:
I have a custom target:

 add_custom_target(
      create-po
      COMMAND ${MSGINIT} --no-translator -i "${PROJECT_SOURCE_DIR}/data/${PACKAGE}.pot" - "${PROJECT_SOURCE_DIR}/po/es.po" -l es_MX.utf8
 )

so, is invoked like this:

 # make create-po

my idea is to change it to something like this:

 # make create-po "es"

so, any user can create a custom localed po file. I don't know the word exactly for this, but I'd like to add a parameter in the target name..is it posible with cmake? Thanks

Body:
After so long time I found this question for the same reason: Can I use CMake to initialize a .po file if I want to add a new translation? I expect to use it only once in a while for my project, so make the build system do it seems more comfortable to me than find out all the required options and paths every time.

I ended up with the following CMake snippet:

set(INIT_LANG CACHE STRING "give a locale here to create a target which initializes a related .po file")
IF(INIT_LANG)
  add_custom_target(
    create-po-${INIT_LANG}
    ... # integrate INIT_LANG in your command
  )
ENDIF(INIT_LANG)

Then, if you want to initialize a new translation file, call (assuming your build dir in under the project root):

# cmake -DINIT_LANG=es_MX.utf8 ..

... and you should get a corresponding make target:

# make create-po-es_MX.utf8

Yes, it's not as straight-forward as the OP's idea/expectation (and mine as well), but users can create new .po files by themselves (of course, this will be documented properly for them in the project ;) ).


问:
Dataset deserialization to object issue - vb .net
Hi everyone i'm having some trouble deserializing a dataset (with parent table) to the correspondent object.
Every table have is array object inside his parent object for deserialization, every array have default {}, but if parent table have no rows the inner object is set to nothing, not empty array... how may i correct this issue?!?

Thanks a lot to everyone.

VB .Net code:

```<code>Public Function DeserializeDataSetToObj(ByRef DataSetIn As DataSet, ByVal t As Type) As Object
        Dim obj As Object = Nothing
        Dim stream As MemoryStream = New MemoryStream()

        Using writer As XmlWriter = XmlWriter.Create(stream)
            DataSetIn.WriteXml(writer)
        End Using

        stream.Seek(0, SeekOrigin.Begin)

        Using reader As XmlReader = XmlReader.Create(stream)
            Try
                Dim xmlSer As System.Xml.Serialization.XmlSerializer = New System.Xml.Serialization.XmlSerializer(t)
                obj = xmlSer.Deserialize(reader)
            Catch ex As Exception

            End Try
        End Using

        Return obj
    End Function
</code>```

Objects Class

```<code><Serializable(), XmlRoot("MainDataset"), XmlType("MainDataset")>
Public Class MainDataset

        <XmlElement("Header1")>
        Public Property Header1() as HeaderType

        <XmlElement("Header2")>
        Public Property Header2() as HeaderType
End Class

<Serializable()>
Public Class HeaderType

        <XmlElement("Rows")>
        Public Property Rows() as RowType
End Class

<Serializable()>
Public Class RowType

        <XmlElement("ColumnA")>
        Public Property ColumnA as String

        <XmlElement("ColumnB")>
        Public Property ColumnB as String

        <XmlElement("ColumnC")>
        Public Property ColumnC as String
End Class
</code>```

XSD:

```<code><?xml version="1.0" standalone="yes"?>
<xs:schema id="MainDataset" xmlns="" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element msdata:UseCurrentLocale="true" name="MainDataset">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Header1">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="Rows">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element minOccurs="0" name="ColumnA" type="xs:string"/>
                                        <xs:element minOccurs="0" name="ColumnB" type="xs:string"/>
                                        <xs:element minOccurs="0" name="ColumnC" type="xs:string"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>

                <xs:element name="Header2">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="Rows">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element minOccurs="0" name="ColumnA" type="xs:string"/>
                                        <xs:element minOccurs="0" name="ColumnB" type="xs:string"/>
                                        <xs:element minOccurs="0" name="ColumnC" type="xs:string"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
</code>```

答:
Problem solved... if i use list instead array i receive an empty list not a nothing object.
Thanks to everyone</p>

Body:
Hi everyone i'm having some trouble deserializing a dataset (with parent table) to the correspondent object.
Every table have is array object inside his parent object for deserialization, every array have default {}, but if parent table have no rows the inner object is set to nothing, not empty array... how may i correct this issue?!?

Thanks a lot to everyone.

VB .Net code:

Public Function DeserializeDataSetToObj(ByRef DataSetIn As DataSet, ByVal t As Type) As Object
        Dim obj As Object = Nothing
        Dim stream As MemoryStream = New MemoryStream()

        Using writer As XmlWriter = XmlWriter.Create(stream)
            DataSetIn.WriteXml(writer)
        End Using

        stream.Seek(0, SeekOrigin.Begin)

        Using reader As XmlReader = XmlReader.Create(stream)
            Try
                Dim xmlSer As System.Xml.Serialization.XmlSerializer = New System.Xml.Serialization.XmlSerializer(t)
                obj = xmlSer.Deserialize(reader)
            Catch ex As Exception

            End Try
        End Using

        Return obj
    End Function

Objects Class

<Serializable(), XmlRoot("MainDataset"), XmlType("MainDataset")>
Public Class MainDataset

        <XmlElement("Header1")>
        Public Property Header1() as HeaderType

        <XmlElement("Header2")>
        Public Property Header2() as HeaderType
End Class

<Serializable()>
Public Class HeaderType

        <XmlElement("Rows")>
        Public Property Rows() as RowType
End Class

<Serializable()>
Public Class RowType

        <XmlElement("ColumnA")>
        Public Property ColumnA as String

        <XmlElement("ColumnB")>
        Public Property ColumnB as String

        <XmlElement("ColumnC")>
        Public Property ColumnC as String
End Class

XSD:

<?xml version="1.0" standalone="yes"?>
<xs:schema id="MainDataset" xmlns="" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element msdata:UseCurrentLocale="true" name="MainDataset">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Header1">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="Rows">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element minOccurs="0" name="ColumnA" type="xs:string"/>
                                        <xs:element minOccurs="0" name="ColumnB" type="xs:string"/>
                                        <xs:element minOccurs="0" name="ColumnC" type="xs:string"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>

                <xs:element name="Header2">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="Rows">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element minOccurs="0" name="ColumnA" type="xs:string"/>
                                        <xs:element minOccurs="0" name="ColumnB" type="xs:string"/>
                                        <xs:element minOccurs="0" name="ColumnC" type="xs:string"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>


问:
Trying to concatenate keras models: ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float)
I'm trying to concatenate two parallel models in keras, each with different inputs. The relevant code is below.

```<code># model 1
model1_in = Input(shape=(train_x_1.shape[1], train_x_1.shape[2]))
model1_out = LSTM(50, activation='relu',return_sequences=False, name='layer_1')(model1_in)
model1 = Model(model1_in, model1_out)

# model 2
model2_in = Input(shape=(1))
model2_out = Dense(8, activation='relu', name='layer_2')(model2_in)
model2 = Model(model2_in, model2_out)

concatenated = concatenate(inputs=[model1.output, model2.output])
out = Dense(1, activation='relu', name='output_layer')(concatenated)
model = Model([model1_in, model2_in], out)
model.compile(loss='mean_absolute_error', optimizer='adam')

# fit network
history = model.fit([train_x_1,train_x_2], train_y, epochs=100, batch_size=72, validation_data=([test_x_1,test_x_2], test_y), verbose=2, shuffle=False)
</code>```

The error I'm getting is

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float).

and occurs at the model.fit line.

I'm running in IDLE. The train and test values are all arrays, and I've checked that all training inputs are of the same length:

```<code>#train_x_1.shape[0]
15465
#train_y.shape[0]
15465
#train_x_2.shape[0]
15465
#test_x_1.shape[0]
1719
#test_x_2.shape[0]
1719
#test_y.shape[0]
1719
#test_x_1
array([[[0.6243922 ],
        [0.5463666 ],
        [0.7083546 ], ... etc ...
</code>```

Any help would be greatly appreciated- thanks in advance!

Full error trace is as below:

Traceback (most recent call last):   File "filepath.py", line 220,
  in
      history = model.fit([train_x_1,train_x_2], train_y, epochs=100, batch_size=72, validation_data=([test_x_1,test_x_2], test_y),
  verbose=2, shuffle=False)   File
  "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training.py",
  line 728, in fit
      use_multiprocessing=use_multiprocessing)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_v2.py", line 224, in fit
      distribution_strategy=strategy)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_v2.py", line 547, in _process_training_inputs
      use_multiprocessing=use_multiprocessing)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_v2.py", line 606, in _process_inputs
      use_multiprocessing=use_multiprocessing)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/data_adapter.py",
  line 217, in init
      x = _process_numpy_inputs(x)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/data_adapter.py",
  line 703, in _process_numpy_inputs
      inputs = nest.map_structure(_convert_non_tensor, inputs)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/util/nest.py",
  line 535, in map_structure
      structure[0], [func(*x) for x in entries],   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/util/nest.py",
  line 535, in
      structure[0], [func(*x) for x in entries],   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/data_adapter.py",
  line 700, in _convert_non_tensor
      return ops.convert_to_tensor(x)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py",
  line 1184, in convert_to_tensor
      return convert_to_tensor_v2(value, dtype, preferred_dtype, name)   File
  "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py",
  line 1242, in convert_to_tensor_v2
      as_ref=False)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py",
  line 1296, in internal_convert_to_tensor
      ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)   File
  "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py",
  line 52, in _default_conversion_function
      return constant_op.constant(value, dtype, name=name)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py",
  line 227, in constant
      allow_broadcast=True)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py",
  line 235, in _constant_impl
      t = convert_to_eager_tensor(value, ctx, dtype)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py",
  line 96, in convert_to_eager_tensor
      return ops.EagerTensor(value, ctx.device_name, dtype) ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type
  float).

答:
Specifying the Solution in Answer Section (even though it is present in the Comments Section), for the benefit of the Community.

The values of x_2 were all as type float, whilst the x_1 values were as float32.

Modifying x2 to float32 using x2.astype('float32') has resolved the issue.

Body:
I'm trying to concatenate two parallel models in keras, each with different inputs. The relevant code is below.

# model 1
model1_in = Input(shape=(train_x_1.shape[1], train_x_1.shape[2]))
model1_out = LSTM(50, activation='relu',return_sequences=False, name='layer_1')(model1_in)
model1 = Model(model1_in, model1_out)

# model 2
model2_in = Input(shape=(1))
model2_out = Dense(8, activation='relu', name='layer_2')(model2_in)
model2 = Model(model2_in, model2_out)

concatenated = concatenate(inputs=[model1.output, model2.output])
out = Dense(1, activation='relu', name='output_layer')(concatenated)
model = Model([model1_in, model2_in], out)
model.compile(loss='mean_absolute_error', optimizer='adam')

# fit network
history = model.fit([train_x_1,train_x_2], train_y, epochs=100, batch_size=72, validation_data=([test_x_1,test_x_2], test_y), verbose=2, shuffle=False)

The error I'm getting is

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float).

and occurs at the model.fit line.

I'm running in IDLE. The train and test values are all arrays, and I've checked that all training inputs are of the same length:

#train_x_1.shape[0]
15465
#train_y.shape[0]
15465
#train_x_2.shape[0]
15465
#test_x_1.shape[0]
1719
#test_x_2.shape[0]
1719
#test_y.shape[0]
1719
#test_x_1
array([[[0.6243922 ],
        [0.5463666 ],
        [0.7083546 ], ... etc ...

Any help would be greatly appreciated- thanks in advance!

Full error trace is as below:

Traceback (most recent call last):   File "filepath.py", line 220,
  in
      history = model.fit([train_x_1,train_x_2], train_y, epochs=100, batch_size=72, validation_data=([test_x_1,test_x_2], test_y),
  verbose=2, shuffle=False)   File
  "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training.py",
  line 728, in fit
      use_multiprocessing=use_multiprocessing)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_v2.py", line 224, in fit
      distribution_strategy=strategy)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_v2.py", line 547, in _process_training_inputs
      use_multiprocessing=use_multiprocessing)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_v2.py", line 606, in _process_inputs
      use_multiprocessing=use_multiprocessing)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/data_adapter.py",
  line 217, in init
      x = _process_numpy_inputs(x)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/data_adapter.py",
  line 703, in _process_numpy_inputs
      inputs = nest.map_structure(_convert_non_tensor, inputs)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/util/nest.py",
  line 535, in map_structure
      structure[0], [func(*x) for x in entries],   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/util/nest.py",
  line 535, in
      structure[0], [func(*x) for x in entries],   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/data_adapter.py",
  line 700, in _convert_non_tensor
      return ops.convert_to_tensor(x)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py",
  line 1184, in convert_to_tensor
      return convert_to_tensor_v2(value, dtype, preferred_dtype, name)   File
  "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py",
  line 1242, in convert_to_tensor_v2
      as_ref=False)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py",
  line 1296, in internal_convert_to_tensor
      ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)   File
  "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py",
  line 52, in _default_conversion_function
      return constant_op.constant(value, dtype, name=name)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py",
  line 227, in constant
      allow_broadcast=True)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py",
  line 235, in _constant_impl
      t = convert_to_eager_tensor(value, ctx, dtype)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py",
  line 96, in convert_to_eager_tensor
      return ops.EagerTensor(value, ctx.device_name, dtype) ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type
  float).


问:
Why can an instance only be seen by main methods
```<code>public static void main(String[] args)
    {
        GUI TestGUI = new GUI();

        TestGUI.setVisible(true);
    }

    public void blahh()
    {
        TestGUI.setVisible(true);
    }
</code>```

Can not find symbol for TestGUI in blahh, but can be seen in the main method.
How can I access TestGUI from other methods?

答:
because you declared TestGUI inside main method as a local varaible to a method , declare it as a class   property</p>

```<code>static GUI TestGUI;
public static void main(String[] args)
{
    Test = new GUI();

    TestGUI.setVisible(true);
}

public void blahh()
{
    TestGUI.setVisible(true);
}
</code>```

Body:
public static void main(String[] args)
    {
        GUI TestGUI = new GUI();

        TestGUI.setVisible(true);
    }

    public void blahh()
    {
        TestGUI.setVisible(true);
    }

Can not find symbol for TestGUI in blahh, but can be seen in the main method.
How can I access TestGUI from other methods?

Body:
because you declared TestGUI inside main method as a local varaible to a method , declare it as a class   property

static GUI TestGUI;
public static void main(String[] args)
{
    Test = new GUI();

    TestGUI.setVisible(true);
}

public void blahh()
{
    TestGUI.setVisible(true);
}


问:
Pasting into contentedittable results in random tag insertion
I am using a contentedittable field as user input so that I can exploit text formatting. Unfortunately I have found that when a user pastes into the field a massive amound of unnessessary html comes with it. I only want the plain text from the clipboard.

Why is this happening?!

A Truncated Example:

```<code><div><br></div><div><span class="Apple-style-span" style="font-family: Arial, 'Liberation Sans', 'DejaVu Sans', sans-serif; font-size: 13px; line-height: 12px; color: rgb(0, 0, 0); "><table style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; border-collapse: collapse; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; background-position: initial initial; background-repeat: initial initial; "><tbody style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; background-position: initial initial; background-repeat: initial initial; "><tr style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; background-position: initial initial; background-repeat: initial initial; "><td class="votecell" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: top; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; width: 60px; background-position: initial initial; background-repeat: initial initial; "><div class="vote" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; text-align: center; background-position: initial initial; background-repeat: initial initial; "><span class="vote-count-post" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 31px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; display: block; color: rgb(128, 129, 133); font-weight: bold; background-position: initial initial; background-repeat: initial initial; ">1</span><a class="vote-down-off" title="This question does not show any research effort; it is unclear or not useful (click again to undo)" style="margin-top: 0px; margin-right: auto; margin-bottom: 0px; margin-left: auto; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 1px; vertical-align: baseline; background-image: url(http://sstatic.net/stackoverflow/img/sprites.png?v=3); background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; color: rgb(0, 119, 204); text-decoration: none; cursor: pointer; overflow-x: hidden; overflow-y: hidden; display: block; width: 41px; height: 25px; text-indent: -9999em; background-position: 0px -300px; background-repeat: no-repeat no-repeat; ">...
</code>```

答:
You're getting all that extra nonsense because a contenteditable element supports the text/html MIME type. When you paste something from the clipboard, there is often a content negotiation phase:

The paste target says "I support these content types: ...."

The clipboard manager then discusses that list with the data source to get the pasted data in a suitable format for the paste target.

And finally, the data gets dumped in your contenteditable element as text/html with all that extra noise.

The process may not be exactly like the above but it will be similar. Your best bet would probably to add a handler for the paste event and use that handler to convert the pasted data to text/plain.

Body:
I am using a contentedittable field as user input so that I can exploit text formatting. Unfortunately I have found that when a user pastes into the field a massive amound of unnessessary html comes with it. I only want the plain text from the clipboard.

Why is this happening?!

A Truncated Example:

<table style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; border-collapse: collapse; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; background-position: initial initial; background-repeat: initial initial; "><tbody style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; background-position: initial initial; background-repeat: initial initial; "><tr style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; background-position: initial initial; background-repeat: initial initial; "><td class="votecell" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: top; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; width: 60px; background-position: initial initial; background-repeat: initial initial; "><div class="vote" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; text-align: center; background-position: initial initial; background-repeat: initial initial; "><span class="vote-count-post" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 31px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; display: block; color: rgb(128, 129, 133); font-weight: bold; background-position: initial initial; background-repeat: initial initial; ">1<a class="vote-down-off" title="This question does not show any research effort; it is unclear or not useful (click again to undo)" style="margin-top: 0px; margin-right: auto; margin-bottom: 0px; margin-left: auto; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 1px; vertical-align: baseline; background-image: url(http://sstatic.net/stackoverflow/img/sprites.png?v=3); background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; color: rgb(0, 119, 204); text-decoration: none; cursor: pointer; overflow-x: hidden; overflow-y: hidden; display: block; width: 41px; height: 25px; text-indent: -9999em; background-position: 0px -300px; background-repeat: no-repeat no-repeat; ">...


问:
When calling batch script inside Jenkins file doesn't get the values after asterisk
When calling a batch script inside Jenkins file it doesn't catch/read the value after asterik *.

Below are the few lines of my batch code:

```<code>SET HOUSE=GREENVILLA
SET NUMBER=10
SET HOUSE_NAME=%HOUSE%-%NUMBER%.*.y
</code>```

I only see that HOUSE_NAME is set to GREENVILLA-10.*.y instead of GREENVILLA-10.44.6.y.

The actual path is \\servername\c\house\name containing the particular file greenvilla-10.44.6.y. I expect greenvilla-10.44.6.y being assigned to environment variable HOUSE_NAME.

Batch file coding is a new thing for me. I'm not sure about missing some basic things here.

答:
solution was I have to replace/remove any extra characters(space,*), when passing an input. I had a special character(") passed in with the number,where batch thought thats the end of the path and didn't give me the other values.
used Inputval = Inputval.replaceAll("\\W", "") before passing the value to the batch script in jenkinsfile.

Body:
When calling a batch script inside Jenkins file it doesn't catch/read the value after asterik *.

Below are the few lines of my batch code:

SET HOUSE=GREENVILLA
SET NUMBER=10
SET HOUSE_NAME=%HOUSE%-%NUMBER%.*.y

I only see that HOUSE_NAME is set to GREENVILLA-10.*.y instead of GREENVILLA-10.44.6.y.

The actual path is \\servername\c\house\name containing the particular file greenvilla-10.44.6.y. I expect greenvilla-10.44.6.y being assigned to environment variable HOUSE_NAME.

Batch file coding is a new thing for me. I'm not sure about missing some basic things here.


问:
How to write a step definition that compares a json response to a scenario outline table
I have json response example:

```<code>{
   "colours": ["green","blue", "red"],
   "type" :   ["shoes","socks","t-shirts"],
   "make" :   ["nike", "adidas"],
}
</code>```

I have Scenario outline table:

```<code>    |colours|type    |make  |
    |red    |shoes   |nike  |
    |blue   |socks   |nike  |
    |green  |t-shirts|adidas|
</code>```

I want to use the scenario table to assert against the json response. Now I know how to check this one by one, for example

```<code>* Assert colour is correct: <colours>
* Assert type is correct: <type>
* Assert make is correct: <make>
</code>```

And then perform the step definition like the example below for colour:

```<code>    @Step("Assert colour is correct: <colours>")
    public void assertColourIsCorrect(String colourValue) {
        String responseBody = BridgeTestState.getLastResponse().getBody().toString();
        itemState itemStateResp = new Gson().fromJson(responseBody, itemState.class);

        assertThat("colours", itemStateResp.getColour(), is(equalTo(colourValue.toLowerCase())));
    }
</code>```

Note The getColour() comes from a getter and setter I have set.

Now this works but as you can see it's a bit long winded as I have to create three separate steps to assert against each column.

I want to be a little smarter than this but don't know how to implement. What I would like is a step definition where it will look at the json response and compare it to the table based on its field and then from there view the value.

Something along the lines of:

Assert correct "fields" and "values" are outputted.

I hope that makes sense, basically a smart one step definition to perform the check between the json response and the table row.

答:
From the comments it seems you want a way to do a row by row where you use the headlines of a datatable as keys for the json. You cannot achieve that by using it by example, because that is specifically meant to be mapped directly into steps the way you describe yourself. As I see there are two ways of dealing with this, depending on your use case.

First, still deal with it as parameters in the steps, i.e.,

```<code>Then the "colours" is <colours>
And the "type" is <type>
</code>```

and then just have one step implmentation

Then("the {string} is {string}")
public void theKeyIsValue(String key, String value) {
    assertThat(json.get(key)).contains(value);
}
```

<p>Another, and most likely better would be to deal with it as a normal scenario as already suggested in the comments (I did not understand why you claim that you can't). Which most often is better.</p>

<p>However, most likely the correct solution is - annoyingly enough - to actually rethink your scenario. There are some really great guidelines for best practices etc. on https://cucumber.io/docs/bdd/ they are fairly fast and easy to read, and will help with a lot of the initial problems.</p>

<p>It's hard without a complete example, but from what you write I suspect that your tests might be too technical. It's an extremely hard balance, but try to keep them so vague that they do not specify the "How" but only the "What". Example <code>Given the username "Kate"</code> is a better step than <code>Given I type the username "Kate"</code>, because in the latter you are specifying that there should be something you can type text in. I usually ask people if their tests works with a voice assistant.</p>

<p>Another thing I suspect is that you try to test too many things at once. One thing I notice for instance is that there are no apparent connection between your json and your table. I.e., if they data should match on the index for instance, it might make more sense. However, looking at the sparse data, I think the tests you need are:</p>

```Scenario: The colour options
  Given ...

  When the options are given

  Then the following can be chosen
    | Colour |
    | red    |
    | blue   |
    | green  |

Scenario: The clothing options
  Given ..

  When the options are given

  Then the following can be chosen
    | Type     |
    | shoes    |
    | socks    |
    | t-shirts |
```

That way you can still re-use the steps, you can use the headline for a key in the json, and judging by your data the tests actually relate more closely to the expected things.

Writing acceptance tests is an art the requires practice. I hope some of the suggestions here can be used, however, it is hard to come with more direct suggestions without more context.

Body:
I have json response example:

{
   "colours": ["green","blue", "red"],
   "type" :   ["shoes","socks","t-shirts"],
   "make" :   ["nike", "adidas"],
}

I have Scenario outline table:

    |colours|type    |make  |
    |red    |shoes   |nike  |
    |blue   |socks   |nike  |
    |green  |t-shirts|adidas|

I want to use the scenario table to assert against the json response. Now I know how to check this one by one, for example

* Assert colour is correct: <colours>
* Assert type is correct: <type>
* Assert make is correct: <make>

And then perform the step definition like the example below for colour:

    @Step("Assert colour is correct: <colours>")
    public void assertColourIsCorrect(String colourValue) {
        String responseBody = BridgeTestState.getLastResponse().getBody().toString();
        itemState itemStateResp = new Gson().fromJson(responseBody, itemState.class);

        assertThat("colours", itemStateResp.getColour(), is(equalTo(colourValue.toLowerCase())));
    }

Note The getColour() comes from a getter and setter I have set.

Now this works but as you can see it's a bit long winded as I have to create three separate steps to assert against each column.

I want to be a little smarter than this but don't know how to implement. What I would like is a step definition where it will look at the json response and compare it to the table based on its field and then from there view the value.

Something along the lines of:

Assert correct "fields" and "values" are outputted.

I hope that makes sense, basically a smart one step definition to perform the check between the json response and the table row.

Body:
From the comments it seems you want a way to do a row by row where you use the headlines of a datatable as keys for the json. You cannot achieve that by using it by example, because that is specifically meant to be mapped directly into steps the way you describe yourself. As I see there are two ways of dealing with this, depending on your use case.

First, still deal with it as parameters in the steps, i.e.,

Then the "colours" is <colours>
And the "type" is <type>

and then just have one step implmentation

Then("the {string} is {string}")
public void theKeyIsValue(String key, String value) {
    assertThat(json.get(key)).contains(value);
}

Another, and most likely better would be to deal with it as a normal scenario as already suggested in the comments (I did not understand why you claim that you can't). Which most often is better.

However, most likely the correct solution is - annoyingly enough - to actually rethink your scenario. There are some really great guidelines for best practices etc. on https://cucumber.io/docs/bdd/ they are fairly fast and easy to read, and will help with a lot of the initial problems.

It's hard without a complete example, but from what you write I suspect that your tests might be too technical. It's an extremely hard balance, but try to keep them so vague that they do not specify the "How" but only the "What". Example Given the username "Kate" is a better step than Given I type the username "Kate", because in the latter you are specifying that there should be something you can type text in. I usually ask people if their tests works with a voice assistant.

Another thing I suspect is that you try to test too many things at once. One thing I notice for instance is that there are no apparent connection between your json and your table. I.e., if they data should match on the index for instance, it might make more sense. However, looking at the sparse data, I think the tests you need are:

Scenario: The colour options
  Given ...

  When the options are given

  Then the following can be chosen
    | Colour |
    | red    |
    | blue   |
    | green  |

Scenario: The clothing options
  Given ..

  When the options are given

  Then the following can be chosen
    | Type     |
    | shoes    |
    | socks    |
    | t-shirts |

That way you can still re-use the steps, you can use the headline for a key in the json, and judging by your data the tests actually relate more closely to the expected things.

Writing acceptance tests is an art the requires practice. I hope some of the suggestions here can be used, however, it is hard to come with more direct suggestions without more context.


问:
How to override the default browser selection in Windows 7 when opening webppages with Python
I have a program written with Python 3.7.4 on Windows that opens web pages in a browser.  It displays the default browser and gives the user the chance to change which browser they want to use to open programs with.

The default browser is detected when the program is initialised using this technique:

```<code>from winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx

import webbroswer

reg_path = r'Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice'
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
firefox_path = 'C:/Program Files (x86)/Mozilla Firefox/firefox.exe %s'

with OpenKey(HKEY_CURRENT_USER, reg_path) as key:
    print(QueryValueEx(key, 'ProgId'))
    thedefaultbrowser = (QueryValueEx(key, 'ProgId'))
    thedefaultbrowser = (thedefaultbrowser[0])
    thedefaultbrowser = (thedefaultbrowser[0:2])
    if thedefaultbrowser == "Fi":
        browser_path = firefox_path
    if thedefaultbrowser == "Ch":
        browser_path = chrome_path
</code>```

And links are opened like this, as part of an infinite loop that happens later in the program:

```<code>while True:

    # [lots of GUI code that isn't relevant]

    event = input()

    if event == 'pleasegetmealinknao':
        x=open("C:/folder/atextfilewithalinkinit.txt", "r")
        the_url1 = x.read()
        webbrowser.get(browser_path).open(the_url1)
        x.close()
</code>```

In the same loop, input can be accepted from the user to change the browser type:

```<code>    elif event == "Firefox":
        browser_path = firefox_path
        continue
    elif event == "Chrome":
        browser_path = chrome_path
        continue
</code>```

So I can open a webpage with this just fine.  I can then change the browser type just fine, and then open another webpage in the newly user-selected browser, but - only in Windows 10.

In Windows 7, Firefox co-operates beautifully, and so does Chrome but only if Chrome is set as the default browser before the program runs.  However if Firefox is set as the default browser before the program is started, as soon as I switch to Chrome and then try to open anything in Chrome, the program gets very upset and stops running.  No crash, no error message or traceback, it just freezes completely and needs to be hard-restarted.  Sometimes I can rescue the program from its frozen state by closing the new browser window that was just opened, but this of course defeats the purpose of the program.

HOWEVER - if I scrap all this fancy business and just accept whatever the default browser is, like this:

```<code>    if event == 'pleasegetmealinknao':
        x=open("C:/folder/atextfilewithalinkinit.txt", "r")
        the_url1 = x.read()
        webbrowser.open(the_url1)
        x.close()
</code>```

Then the chosen link will open happily in whatever the system default browser is, whether it be Firefox, Chrome, Internet Explorer, or anything else.

So why is this happening and how can I fix?  Or do I just have to bury my dream of selectable browsers?

My guess is that this might have something to do with Chrome detecting that it is not the default browser and asking the user to change the default browser setting, that would make sense.  However then the question is, how do I make the Python program ignore whatever this behaviour is.  A popup related to this doesn't always appear.

EDIT: further testing and sometimes the Windows 7 pattern of behaviour also happens in Windows 10... but seemingly not all the time.  This makes me think even more that it's browser-related rather than strictly OS related and has a lot to do with Chrome asking for default status, but I'm still no closer to working out what to do about it.

答:
Have you tried the webbrowser module?

```<code>import webbrowser
webbrowser.get('firefox %s').open('http://google.com')
</code>```

You can see a list of browsers and what they are called here webbrowser docs

Body:
I have a program written with Python 3.7.4 on Windows that opens web pages in a browser.  It displays the default browser and gives the user the chance to change which browser they want to use to open programs with.

The default browser is detected when the program is initialised using this technique:

from winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx

import webbroswer

reg_path = r'Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice'
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
firefox_path = 'C:/Program Files (x86)/Mozilla Firefox/firefox.exe %s'

with OpenKey(HKEY_CURRENT_USER, reg_path) as key:
    print(QueryValueEx(key, 'ProgId'))
    thedefaultbrowser = (QueryValueEx(key, 'ProgId'))
    thedefaultbrowser = (thedefaultbrowser[0])
    thedefaultbrowser = (thedefaultbrowser[0:2])
    if thedefaultbrowser == "Fi":
        browser_path = firefox_path
    if thedefaultbrowser == "Ch":
        browser_path = chrome_path

And links are opened like this, as part of an infinite loop that happens later in the program:

while True:

    # [lots of GUI code that isn't relevant]

    event = input()

    if event == 'pleasegetmealinknao':
        x=open("C:/folder/atextfilewithalinkinit.txt", "r")
        the_url1 = x.read()
        webbrowser.get(browser_path).open(the_url1)
        x.close()

In the same loop, input can be accepted from the user to change the browser type:

    elif event == "Firefox":
        browser_path = firefox_path
        continue
    elif event == "Chrome":
        browser_path = chrome_path
        continue

So I can open a webpage with this just fine.  I can then change the browser type just fine, and then open another webpage in the newly user-selected browser, but - only in Windows 10.

In Windows 7, Firefox co-operates beautifully, and so does Chrome but only if Chrome is set as the default browser before the program runs.  However if Firefox is set as the default browser before the program is started, as soon as I switch to Chrome and then try to open anything in Chrome, the program gets very upset and stops running.  No crash, no error message or traceback, it just freezes completely and needs to be hard-restarted.  Sometimes I can rescue the program from its frozen state by closing the new browser window that was just opened, but this of course defeats the purpose of the program.

HOWEVER - if I scrap all this fancy business and just accept whatever the default browser is, like this:

    if event == 'pleasegetmealinknao':
        x=open("C:/folder/atextfilewithalinkinit.txt", "r")
        the_url1 = x.read()
        webbrowser.open(the_url1)
        x.close()

Then the chosen link will open happily in whatever the system default browser is, whether it be Firefox, Chrome, Internet Explorer, or anything else.

So why is this happening and how can I fix?  Or do I just have to bury my dream of selectable browsers?

My guess is that this might have something to do with Chrome detecting that it is not the default browser and asking the user to change the default browser setting, that would make sense.  However then the question is, how do I make the Python program ignore whatever this behaviour is.  A popup related to this doesn't always appear.

EDIT: further testing and sometimes the Windows 7 pattern of behaviour also happens in Windows 10... but seemingly not all the time.  This makes me think even more that it's browser-related rather than strictly OS related and has a lot to do with Chrome asking for default status, but I'm still no closer to working out what to do about it.

Body:
Have you tried the webbrowser module?

import webbrowser
webbrowser.get('firefox %s').open('http://google.com')

You can see a list of browsers and what they are called here webbrowser docs


问:
How to write a generator class?
I see lot of examples of generator functions, but I want to know how to write generators for classes. Lets say, I wanted to write Fibonacci series as a class.

```<code>class Fib:
    def __init__(self):
        self.a, self.b = 0, 1

    def __next__(self):
        yield self.a
        self.a, self.b = self.b, self.a+self.b

f = Fib()

for i in range(3):
    print(next(f))
</code>```

Output:

<generator object __next__ at 0x000000000A3E4F68>
<generator object __next__ at 0x000000000A3E4F68>
<generator object __next__ at 0x000000000A3E4F68>
```

Why is the value self.a not getting printed?  Also, how do I write unittest for generators?

答:
Using yield in a method makes that method a generator, and calling that method returns a generator iterator. next() expects a generator iterator which implements __next__() and returns an item. That is why yielding in __next__() causes your generator class to output generator iterators when next() is called on it.

https://docs.python.org/3/glossary.html#term-generator

When implementing an interface, you need to define methods and map them to your class implementation. In this case the __next__() method needs to call through to the generator iterator.

class Fib:
    def __init__(self):
        self.a, self.b = 0, 1
        self.generator_iterator = self.generator()

    def __next__(self):
        return next(self.generator_iterator)

    def generator(self):
        while True:
            yield self.a
            self.a, self.b = self.b, self.a+self.b

f = Fib()

for i in range(3):
    print(next(f))
# 0
# 1
# 1
```

Title: How to write a generator class?

Body:
I see lot of examples of generator functions, but I want to know how to write generators for classes. Lets say, I wanted to write Fibonacci series as a class.

class Fib:
    def __init__(self):
        self.a, self.b = 0, 1

    def __next__(self):
        yield self.a
        self.a, self.b = self.b, self.a+self.b

f = Fib()

for i in range(3):
    print(next(f))

Output:

<generator object __next__ at 0x000000000A3E4F68>
<generator object __next__ at 0x000000000A3E4F68>
<generator object __next__ at 0x000000000A3E4F68>

Why is the value self.a not getting printed?  Also, how do I write unittest for generators?