问:
Can I use different argument types in a function in javascript?
Since we can not overload function in JS, i try to pass different types, which failed:

```<code>  static fromRaw(raw: CourseRaw | CourseNameSearchRaw): Course | CourseNameSearch {
    if (raw instanceof CourseRaw) {
      return {
        ...raw,
        metaInfo: MetaInfoFactory.fromRaw(raw.metaInfo),
        // terrain: TagFactory.fromRaw(courseRaw.terrain),
        ratingInfo: RatingFactory.fromRaw(raw.ratingInfo),
        images: ImageFactory.fromRaw(raw.images)
      };
    }
  }
</code>```

--> 'CourseRaw' only refers to a type, but is being used as a value here.ts(2693)

CourseRaw and CourseNameSearchRaw are both interfaces with different object structures:

```<code>export interface CourseNameSearchRaw {
  trackId: number;
  typeCode: number;
  trackName: string;
}
</code>```

My idea was to handle each type differently and return the respect type.

答:
In similar cases I always prefer going with Named params, when I am defining a function. This way wherever you have to call the function you have to specify a Key as well, instead of providing a single value.

For example:

```<code>const func = ({ key1, key2, key3 = “defaultValue3” }) => {
    if (key1) {}
    if(key2) {}
    ....etc
}
</code>```

And of course you can define an interface with types for each key.
Hope this solution works for you! :)

Body:
Since we can not overload function in JS, i try to pass different types, which failed:

  static fromRaw(raw: CourseRaw | CourseNameSearchRaw): Course | CourseNameSearch {
    if (raw instanceof CourseRaw) {
      return {
        ...raw,
        metaInfo: MetaInfoFactory.fromRaw(raw.metaInfo),
        // terrain: TagFactory.fromRaw(courseRaw.terrain),
        ratingInfo: RatingFactory.fromRaw(raw.ratingInfo),
        images: ImageFactory.fromRaw(raw.images)
      };
    }
  }

--> 'CourseRaw' only refers to a type, but is being used as a value here.ts(2693)

CourseRaw and CourseNameSearchRaw are both interfaces with different object structures:

export interface CourseNameSearchRaw {
  trackId: number;
  typeCode: number;
  trackName: string;
}

My idea was to handle each type differently and return the respect type.

Body:
In similar cases I always prefer going with Named params, when I am defining a function. This way wherever you have to call the function you have to specify a Key as well, instead of providing a single value.

For example:

const func = ({ key1, key2, key3 = “defaultValue3” }) => {
    if (key1) {}
    if(key2) {}
    ....etc
}

And of course you can define an interface with types for each key.
Hope this solution works for you! :)


来源: stackexchange

问:
The progress bar cannot be displayed
I am working with Android Studio and I am trying to create a loading dialog. The problem arises when I take the progress bar from the widgets and put it in XML.
Nothing is displayed...

I attach the part of the code that is for visualization.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ProgressBar
    android:id="@+id/progressBar"
    style="@style/Widget.AppCompat.ProgressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="visible"
    android:indeterminate="true"
    android:progressTint="@color/CobaltBlue"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    />

<TextView
    android:id="@+id/tx_loading"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:textSize="18dp"
    android:text="Loading . . . "
    android:textColor="@color/Black"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progressBar" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

And this is what it produces:

[]

but I expect to get this result

[]

答:
You can try with this piece of xml. The  android:indeterminateTint is missing attribute.

```<code><ProgressBar
                android:id="@+id/pb_FilterStopsFromListActivity"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:indeterminate="true"
                android:indeterminateTint="@color/black" />
</code>```

ContentLicense: CC BY-SA 4.0

Title: The progress bar cannot be displayed

Body:
I am working with Android Studio and I am trying to create a loading dialog. The problem arises when I take the progress bar from the widgets and put it in XML.
Nothing is displayed...

I attach the part of the code that is for visualization.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ProgressBar
    android:id="@+id/progressBar"
    style="@style/Widget.AppCompat.ProgressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="visible"
    android:indeterminate="true"
    android:progressTint="@color/CobaltBlue"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    />

<TextView
    android:id="@+id/tx_loading"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:textSize="18dp"
    android:text="Loading . . . "
    android:textColor="@color/Black"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progressBar" />

</androidx.constraintlayout.widget.ConstraintLayout>

And this is what it produces:

[]

but I expect to get this result

[]

Body:
You can try with this piece of xml. The  android:indeterminateTint is missing attribute.

<ProgressBar
                android:id="@+id/pb_FilterStopsFromListActivity"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:indeterminate="true"
                android:indeterminateTint="@color/black" />


问:
Can you make Python3 give an error when comparing strings to bytes
When converting code from Python 2 to Python 3 one issue is that the behaviour when testing strings and bytes for equality has changed. For example:

```<code>foo = b'foo'
if foo == 'foo':
    print("They match!")
</code>```

prints nothing on Python 3 and "They match!" on Python 2. In this case it is easy to spot but in many cases the check is performed on variables which may have been defined elsewhere so there is no obvious type information.

I would like to make the Python 3 interpreter give an error whenever there is an equality test between string and bytes rather than silently conclude that they are different. Is there any way to accomplish this?

答:
(EDITED: to fix an issue where I was incorrectly suggesting that modifying __eq__ on the instance would affect the == evaluation as suggested by @user2357112supportsMonica).

Normally, you would do this by overriding the __eq__ method of the type(s) you would like to guard.
Unfortunately for you, this cannot be done for built-in types, notably str and bytes, therefore code like this:

foo = b'foo'
bytes.__eq__ = ...  # a custom equal function
# str.__eq__ = ...  # if it were 'foo' == foo (or `type(foo)`)
if foo == 'foo':
    print("They match!")
```

<p>would just throw:</p>

<blockquote>
  <pre class="lang-none prettyprint-override"><code>AttributeError: 'bytes' object attribute '__eq__' is read-only
</code>```

You may need to manually guard the comparison with something like:

def str_eq_bytes(x, y):
    if isinstance(x, str) and isinstance(y, bytes):
        raise TypeError("Comparison between `str` and `bytes` detected.")
    elif isinstance(x, bytes) and isinstance(y, str):
        raise TypeError("Comparison between `bytes` and `str` detected.")
```

<p>to be used as follows:</p>

<pre class="lang-py prettyprint-override"><code>foo = 'foo'
if str_eq_bytes(foo, 'foo') or foo == 'foo':
    print("They match!")
# They match!

foo = 'bar'
if str_eq_bytes(foo, 'foo') or foo == 'foo':
    print("They match!")
# <nothing gets printed>

foo = b'foo'
if str_eq_bytes(foo, 'foo') or foo == 'foo':
    print("They match!")
</code>```

TypeError: Comparison between `bytes` and `str` detected.
```

The other option would be to hack in your own Python fork and override __eq__.
Note that also Pypy does not allow you to override methods for built-in types.

Body:
When converting code from Python 2 to Python 3 one issue is that the behaviour when testing strings and bytes for equality has changed. For example:

foo = b'foo'
if foo == 'foo':
    print("They match!")

prints nothing on Python 3 and "They match!" on Python 2. In this case it is easy to spot but in many cases the check is performed on variables which may have been defined elsewhere so there is no obvious type information.

I would like to make the Python 3 interpreter give an error whenever there is an equality test between string and bytes rather than silently conclude that they are different. Is there any way to accomplish this?

Body:
(EDITED: to fix an issue where I was incorrectly suggesting that modifying __eq__ on the instance would affect the == evaluation as suggested by @user2357112supportsMonica).

Normally, you would do this by overriding the __eq__ method of the type(s) you would like to guard.
Unfortunately for you, this cannot be done for built-in types, notably str and bytes, therefore code like this:

foo = b'foo'
bytes.__eq__ = ...  # a custom equal function
# str.__eq__ = ...  # if it were 'foo' == foo (or `type(foo)`)
if foo == 'foo':
    print("They match!")

would just throw:

AttributeError: 'bytes' object attribute '__eq__' is read-only

You may need to manually guard the comparison with something like:

def str_eq_bytes(x, y):
    if isinstance(x, str) and isinstance(y, bytes):
        raise TypeError("Comparison between `str` and `bytes` detected.")
    elif isinstance(x, bytes) and isinstance(y, str):
        raise TypeError("Comparison between `bytes` and `str` detected.")

to be used as follows:

foo = 'foo'
if str_eq_bytes(foo, 'foo') or foo == 'foo':
    print("They match!")
# They match!

foo = 'bar'
if str_eq_bytes(foo, 'foo') or foo == 'foo':
    print("They match!")
# <nothing gets printed>

foo = b'foo'
if str_eq_bytes(foo, 'foo') or foo == 'foo':
    print("They match!")

TypeError: Comparison between `bytes` and `str` detected.

The other option would be to hack in your own Python fork and override __eq__.
Note that also Pypy does not allow you to override methods for built-in types.


问:
Identifying a function name or property in Javascript
I'm using an npm module that throws an empty function i.e. UnauthorizedException upon error. I want to be able to identify the function thrown so i can handle it accordingly

```<code>function UnauthorizedException() {

}

const f = () => {
  throw (new UnauthorizedException());
};

try {
  f();
} catch (err) {
  // How to identity a function name/property/etc so I can handle the error accordingly
  console.log(err);
  console.log(typeof (err));
}
</code>```

答:
The UnauthorizedException function is used as constructor. You can check if an object was created from a constructor using the instanceof operator:

function UnauthorizedException() {}

const f = () => {
  throw (new UnauthorizedException());
};

try {
  f();
} catch (err) {
  console.log(err instanceof UnauthorizedException);
}```

Body:
I'm using an npm module that throws an empty function i.e. UnauthorizedException upon error. I want to be able to identify the function thrown so i can handle it accordingly

function UnauthorizedException() {

}

const f = () => {
  throw (new UnauthorizedException());
};

try {
  f();
} catch (err) {
  // How to identity a function name/property/etc so I can handle the error accordingly
  console.log(err);
  console.log(typeof (err));
}


问:
Huawei phone showing a biometric problem when using gallery
I am opening the gallery from code to select a photo and when going back to my app I get the following error:

```<code>2020-05-24 13:06:41.408 1767-1767/? E/AuthenticationService: Failed to get biometric interface NoSuchElementException:
    java.util.NoSuchElementException
        at android.os.HwBinder.getService(Native Method)
        at android.os.HwBinder.getService(HwBinder.java:91)
        at vendor.huawei.hardware.biometrics.fingerprint.V2_1.IExtBiometricsFingerprint.getService(IExtBiometricsFingerprint.java:48)
        at vendor.huawei.hardware.biometrics.fingerprint.V2_1.IExtBiometricsFingerprint.getService(IExtBiometricsFingerprint.java:52)
        at com.huawei.systemserver.securitymgr.AuthenticationServiceImpl.getFingerprintDaemonEx(AuthenticationServiceImpl.java:1483)
        at com.huawei.systemserver.securitymgr.AuthenticationServiceImpl.sendCmdToHal(AuthenticationServiceImpl.java:1502)
        at com.huawei.systemserver.securitymgr.AuthenticationServiceImpl.se_native_NavigationAFDDFDSwitch(AuthenticationServiceImpl.java:1344)
        at com.huawei.systemserver.securitymgr.AuthenticationServiceImpl.switchAFDDFD(AuthenticationServiceImpl.java:1453)
        at com.huawei.systemserver.securitymgr.AuthenticationServiceImpl.access$700(AuthenticationServiceImpl.java:59)
        at com.huawei.systemserver.securitymgr.AuthenticationServiceImpl$SettingsObserver.onChange(AuthenticationServiceImpl.java:1394)
        at android.database.ContentObserver.onChange(ContentObserver.java:130)
        at android.database.ContentObserver.onChange(ContentObserver.java:145)
        at android.database.ContentObserver$NotificationRunnable.run(ContentObserver.java:216)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
2020-05-24 13:06:41.408 1767-1767/? W/AuthenticationService: fingerprint HIDL not available
2020-05-24 13:06:41.409 1767-1767/? E/AuthenticationService: Fingerprintd is not available!
</code>```

Do you have any idea on the possible cause?

答: So apparently the problem was not the root cause but a (confusing) consequence of the original error which was caused by the way I tried to open the photo gallery, copy pasting some other snippet from google solved the issue.</p>

Body:
I am opening the gallery from code to select a photo and when going back to my app I get the following error:

2020-05-24 13:06:41.408 1767-1767/? E/AuthenticationService: Failed to get biometric interface NoSuchElementException:
    java.util.NoSuchElementException
        at android.os.HwBinder.getService(Native Method)
        at android.os.HwBinder.getService(HwBinder.java:91)
        at vendor.huawei.hardware.biometrics.fingerprint.V2_1.IExtBiometricsFingerprint.getService(IExtBiometricsFingerprint.java:48)
        at vendor.huawei.hardware.biometrics.fingerprint.V2_1.IExtBiometricsFingerprint.getService(IExtBiometricsFingerprint.java:52)
        at com.huawei.systemserver.securitymgr.AuthenticationServiceImpl.getFingerprintDaemonEx(AuthenticationServiceImpl.java:1483)
        at com.huawei.systemserver.securitymgr.AuthenticationServiceImpl.sendCmdToHal(AuthenticationServiceImpl.java:1502)
        at com.huawei.systemserver.securitymgr.AuthenticationServiceImpl.se_native_NavigationAFDDFDSwitch(AuthenticationServiceImpl.java:1344)
        at com.huawei.systemserver.securitymgr.AuthenticationServiceImpl.switchAFDDFD(AuthenticationServiceImpl.java:1453)
        at com.huawei.systemserver.securitymgr.AuthenticationServiceImpl.access$700(AuthenticationServiceImpl.java:59)
        at com.huawei.systemserver.securitymgr.AuthenticationServiceImpl$SettingsObserver.onChange(AuthenticationServiceImpl.java:1394)
        at android.database.ContentObserver.onChange(ContentObserver.java:130)
        at android.database.ContentObserver.onChange(ContentObserver.java:145)
        at android.database.ContentObserver$NotificationRunnable.run(ContentObserver.java:216)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
2020-05-24 13:06:41.408 1767-1767/? W/AuthenticationService: fingerprint HIDL not available
2020-05-24 13:06:41.409 1767-1767/? E/AuthenticationService: Fingerprintd is not available!

Do you have any idea on the possible cause?


问:
beginner question: How can I merge 'function' and 'for phrase'
sorry. I jut start python (It's probably been about two days)

```<code>def grade(point):
    result = ""
    if point >= 90:
        result = "A"
    elif point >= 80:
        result = "B"
    else:
        result = "C"
    return result

subject_ls = ["English", "Science","math"]
score_ls = [80,90,100]

for data in score_ls:
    result = grade(data)
    for data2 in subject_ls:
        result2 = subject
    print("{} {}".format(result2,result),end="\t")
</code>```

when I run this.
out is [math B  math A  math A]
I just want [English B, Science A, math A]
What am I missing? plz answer me

答:
First issues is that you are assigning result2 = subject but 'subject' is not defined.

Secondly, the second for loop is running 3 times for each subject which is not what you want.

A simple way to do it is to use while and set a counter and then print the output.

```<code>i=0
while i< len(subject_ls):
  subject= subject_ls[i]
  result=grade(score_ls[i])
  print("{} {}".format(subject,result),end="\t")
  i+=1

</code>```

The are shorter ways to do this but since you are new to python you might understand this better!

Body:
sorry. I jut start python (It's probably been about two days)

def grade(point):
    result = ""
    if point >= 90:
        result = "A"
    elif point >= 80:
        result = "B"
    else:
        result = "C"
    return result

subject_ls = ["English", "Science","math"]
score_ls = [80,90,100]

for data in score_ls:
    result = grade(data)
    for data2 in subject_ls:
        result2 = subject
    print("{} {}".format(result2,result),end="\t")

when I run this.
out is [math B  math A  math A]
I just want [English B, Science A, math A]
What am I missing? plz answer me

Body:
First issues is that you are assigning result2 = subject but 'subject' is not defined.

Secondly, the second for loop is running 3 times for each subject which is not what you want.

A simple way to do it is to use while and set a counter and then print the output.

i=0
while i< len(subject_ls):
  subject= subject_ls[i]
  result=grade(score_ls[i])
  print("{} {}".format(subject,result),end="\t")
  i+=1

The are shorter ways to do this but since you are new to python you might understand this better!


问:
Unexpected babel build output
I get the following output when I transpile a javascript file with Babel 7.

I don't understand the presence of the cov_5hsavp2s2() function. It seems to be some metadata.

Is there a way (a flag or config) to prevent it from being generated as it has nothing to do with the functionality of the module.

```<code>Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _useMuiTheme = _interopRequireDefault(require("./useRepl"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function cov_5hsavp2s2() {
  var path = "/home/me/use-repl/src/index.js";
  var hash = "8995b4e9d98ed443cd65fa7d3cf9e2594de820db";
  var global = new Function("return this")();
  var gcv = "__coverage__";
  var coverageData = {
    path: "/home/me/use-repl/src/index.js",
    statementMap: {},
    fnMap: {},
    branchMap: {},
    s: {},
    f: {},
    b: {},
    _coverageSchema: "1a1c01bbd47fc00a2c39e90264f33305004495a9",
    hash: "8995b4e9d98ed443cd65fa7d3cf9e2594de820db"
  };
  var coverage = global[gcv] || (global[gcv] = {});

  if (!coverage[path] || coverage[path].hash !== hash) {
    coverage[path] = coverageData;
  }

  var actualCoverage = coverage[path];
  {
    // @ts-ignore
    cov_5hsavp2s2 = function () {
      return actualCoverage;
    };
  }
  return actualCoverage;
}

cov_5hsavp2s2();
var _default = _useMuiRepl.default;
exports.default = _default;
</code>```

Package.json

```<code>{
  "name": "@devskope/use-repl",
  "version": "1.0.0",
  "main": "./lib/index.js",
  "files": [
    "/lib"
  ],
  "scripts": {
    "build": "babel --delete-dir-on-start --copy-files src --out-dir lib ",
    "test": "nyc mocha"
  },
  "babel": {
    "presets": [
      [
        "@babel/preset-env",
        {
          "targets": {
            "node": "current"
          }
        }
      ],
      "@babel/preset-react"
    ],
    "plugins": [
      "istanbul"
    ]
  },
  "nyc": {
    "require": [
      "@babel/register"
    ]
  },
  "engines": {
    "node": ">=.10.0.0"
  },
  "author": "devskope",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/devskope/use-mui-theme.git"
  },
  "bugs": {
    "url": "https://github.com/devskope/use-mui-theme/issues"
  },
  "homepage": "https://github.com/devskope/use-mui-theme#readme",
  "license": "MIT",
  "keywords": [
    "hook",
    "hooks",
    "material-ui",
    "material ui",
    "mui",
    "react",
    "theme"
  ],
  "peerDependencies": {
    "@material-ui/core": "^4.4.0",
    "react": "^16.8.0",
    "react-dom": "^16.8.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.10.1",
    "@babel/core": "^7.10.1",
    "@babel/preset-env": "^7.10.1",
    "@babel/preset-react": "^7.10.1",
    "@babel/register": "^7.10.1",
    "babel-plugin-istanbul": "^6.0.0",
    "chai": "^4.2.0",
    "dotenv": "^8.2.0",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.2",
    "jsdom": "^16.2.2",
    "mocha": "^7.2.0",
    "nodemon": "^2.0.4",
    "nyc": "^15.0.1",
    "prop-types": "^15.7.2"
  },
  "dependencies": {
    "@material-ui/core": "^4.4.0"
  }
}
</code>```

答:
Solved by adding an env stanza to the babel config to restrict Istanbul to the test environment.</p>

```<code>{ //...rest of package.json
    "babel": {
    "presets": [
      [
        "@babel/preset-env",
        {
          "targets": {
            "node": "current"
          }
        }
      ],
      "@babel/preset-react"
    ],
    "env": {
      "test": {
        "plugins": [
          "istanbul"
        ]
      }
    }
  },
}
</code>```

Title: Unexpected babel build output

Body:
I get the following output when I transpile a javascript file with Babel 7.

I don't understand the presence of the cov_5hsavp2s2() function. It seems to be some metadata.

Is there a way (a flag or config) to prevent it from being generated as it has nothing to do with the functionality of the module.

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _useMuiTheme = _interopRequireDefault(require("./useRepl"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function cov_5hsavp2s2() {
  var path = "/home/me/use-repl/src/index.js";
  var hash = "8995b4e9d98ed443cd65fa7d3cf9e2594de820db";
  var global = new Function("return this")();
  var gcv = "__coverage__";
  var coverageData = {
    path: "/home/me/use-repl/src/index.js",
    statementMap: {},
    fnMap: {},
    branchMap: {},
    s: {},
    f: {},
    b: {},
    _coverageSchema: "1a1c01bbd47fc00a2c39e90264f33305004495a9",
    hash: "8995b4e9d98ed443cd65fa7d3cf9e2594de820db"
  };
  var coverage = global[gcv] || (global[gcv] = {});

  if (!coverage[path] || coverage[path].hash !== hash) {
    coverage[path] = coverageData;
  }

  var actualCoverage = coverage[path];
  {
    // @ts-ignore
    cov_5hsavp2s2 = function () {
      return actualCoverage;
    };
  }
  return actualCoverage;
}

cov_5hsavp2s2();
var _default = _useMuiRepl.default;
exports.default = _default;

Package.json

{
  "name": "@devskope/use-repl",
  "version": "1.0.0",
  "main": "./lib/index.js",
  "files": [
    "/lib"
  ],
  "scripts": {
    "build": "babel --delete-dir-on-start --copy-files src --out-dir lib ",
    "test": "nyc mocha"
  },
  "babel": {
    "presets": [
      [
        "@babel/preset-env",
        {
          "targets": {
            "node": "current"
          }
        }
      ],
      "@babel/preset-react"
    ],
    "plugins": [
      "istanbul"
    ]
  },
  "nyc": {
    "require": [
      "@babel/register"
    ]
  },
  "engines": {
    "node": ">=.10.0.0"
  },
  "author": "devskope",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/devskope/use-mui-theme.git"
  },
  "bugs": {
    "url": "https://github.com/devskope/use-mui-theme/issues"
  },
  "homepage": "https://github.com/devskope/use-mui-theme#readme",
  "license": "MIT",
  "keywords": [
    "hook",
    "hooks",
    "material-ui",
    "material ui",
    "mui",
    "react",
    "theme"
  ],
  "peerDependencies": {
    "@material-ui/core": "^4.4.0",
    "react": "^16.8.0",
    "react-dom": "^16.8.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.10.1",
    "@babel/core": "^7.10.1",
    "@babel/preset-env": "^7.10.1",
    "@babel/preset-react": "^7.10.1",
    "@babel/register": "^7.10.1",
    "babel-plugin-istanbul": "^6.0.0",
    "chai": "^4.2.0",
    "dotenv": "^8.2.0",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.2",
    "jsdom": "^16.2.2",
    "mocha": "^7.2.0",
    "nodemon": "^2.0.4",
    "nyc": "^15.0.1",
    "prop-types": "^15.7.2"
  },
  "dependencies": {
    "@material-ui/core": "^4.4.0"
  }
}

Body:
Solved by adding an env stanza to the babel config to restrict Istanbul to the test environment.

{ //...rest of package.json
    "babel": {
    "presets": [
      [
        "@babel/preset-env",
        {
          "targets": {
            "node": "current"
          }
        }
      ],
      "@babel/preset-react"
    ],
    "env": {
      "test": {
        "plugins": [
          "istanbul"
        ]
      }
    }
  },
}


问:
trying to create a div below a div css
I realize this is a a pretty basic question, and perhaps I'm taking advantage of you all while I should be sifting through some dense css books/materials. But I can't figure out why my code doesn't work.

I'm trying to create two divs on a page, one below the other and it seems like I should be able to give the lower and absolute position which is below the top div.

I've got to div box whose css layouts are all the same but they don't look anything like eachother. Why is it that the second one looks completely unlike the first, why can't I make a "copy" of the first and place it below the first?

Heres the code. the top is the desired scroller is the desired effect. http://jsfiddle.net/7YueC/

答:
You don't have to use absolute positioning to position one div below another.

Check out this, a jsFiddle I did to demonstrate how to get one div below another.

ContentLicense: CC BY-SA 3.0

Title: trying to create a div below a div css


问:
How to make the new elasticsearch node.js client only returns body in promises?
"The returned value of an API call will no longer be the body, statusCode, and headers for callbacks, and only the body for promises. The new returned value will be a unique object containing the body, statusCode, headers, warnings, and meta, for both callback and promises."

This is a problem if I stringify and store the result in redis (now I will need to JSON parse when I get the value back from redis). Is there anyway I can switch on "body only" mode on promises?

答:
As a workaround you could overwrite/proxy the search() method of your Client-instance. So you could define your proxy with something like:

```<code>function initializeSearchProxy(client) {
    const origSearch = client.search;
    client.search = async function () {
        const {body} = await origSearch.apply(this, arguments);
        return body;
    }
}
</code>```

Then initialize your search-proxy after requiring and instantiating the elasticsearch-Client,

```<code>const {Client} = require('@elastic/elasticsearch');
const client = new Client({node: 'http://localhost:9200'});
initializeSearchProxy(client);
...
// all client.search calls now return the body directly
</code>```

Body:
As a workaround you could overwrite/proxy the search() method of your Client-instance. So you could define your proxy with something like:

function initializeSearchProxy(client) {
    const origSearch = client.search;
    client.search = async function () {
        const {body} = await origSearch.apply(this, arguments);
        return body;
    }
}

Then initialize your search-proxy after requiring and instantiating the elasticsearch-Client,

const {Client} = require('@elastic/elasticsearch');
const client = new Client({node: 'http://localhost:9200'});
initializeSearchProxy(client);
...
// all client.search calls now return the body directly


问:
pandas mix type value list: move string at the end of the list
I have a dataframe that I try to organize by a column value in ascending order. In this column, there are some values that are strings, I want to move them at the bottom of the dataframe but I can't seem to figure it out.

I have this:

```<code>   index Transporteur     Prix
0      0      t1      'unavailable'
1      0      t2           66
2      0      t3          145
3      0      t4         401.3
</code>```

when i do

```<code> final_df = final_df.sort_values('Prix', ascending=True).reset_index()
 final_df = final_df.replace(0.00,'unavailable')
</code>```

the "unavailable" value gets printed out at the top but I need it at the bottom.

Sorry if this sounds like a noob question but honestly I cannot find a way to fix it. Thank you for any help!

答:
You can use pd.to_numeric with errors='coerce':

```<code>final_df = final_df.loc[pd.to_numeric(final_df['Prix'], errors='coerce').sort_values().index]
</code>```

Output:

```<code>   index Transporteur           Prix
1      0           t2             66
2      0           t3            145
3      0           t4          401.3
0      0           t1  'unavailable'
</code>```

Body:
I have a dataframe that I try to organize by a column value in ascending order. In this column, there are some values that are strings, I want to move them at the bottom of the dataframe but I can't seem to figure it out.

I have this:

   index Transporteur     Prix
0      0      t1      'unavailable'
1      0      t2           66
2      0      t3          145
3      0      t4         401.3

when i do

 final_df = final_df.sort_values('Prix', ascending=True).reset_index()
 final_df = final_df.replace(0.00,'unavailable')

the "unavailable" value gets printed out at the top but I need it at the bottom.

Sorry if this sounds like a noob question but honestly I cannot find a way to fix it. Thank you for any help!

Body:
You can use pd.to_numeric with errors='coerce':

final_df = final_df.loc[pd.to_numeric(final_df['Prix'], errors='coerce').sort_values().index]

Output:

   index Transporteur           Prix
1      0           t2             66
2      0           t3            145
3      0           t4          401.3
0      0           t1  'unavailable'


答:
You can simplify your code and use zip for this purpose:</p>

```<code>for (subject,score) in zip(subject_ls,score_ls):
    print("{} {}".format(subject,grade(score)),end="\t")

OUT: English B       Science A       math A
</code>```

Title: beginner question: How can I merge 'function' and 'for phrase'

Body:
You can simplify your code and use zip for this purpose:

for (subject,score) in zip(subject_ls,score_ls):
    print("{} {}".format(subject,grade(score)),end="\t")

OUT: English B       Science A       math A


问:
ironSource - How to activate a banner ad unit in an existing application
I created an application in ironSource and activated the ad units "Rewarded Video" and "Interstitial".

ironSource

Now I want to activate the "Banner" ad unit for this existing application, but cannot find how.

答:
Login to Ironsource

Goto Monetize -> Ad Units & Placement

On the Right hand side goto extreme right and you will find Banner

Inside banner create New Placement


问:
When core data is changed, how to update the table view data?
Using NSXMLParser to get data from an xml file on internet with an update button to get update database and store it by using xcode template core data.
However, when I updated all core data, console can only show right data until I quited the app and run it  again.
Any way to update all data correctly without quiting the app?

Thanks for that answer.
With using Xcode template (Navigation-based Application with core data), fetchedResultsController and managedObjectContext and so on are all included. Yet, every time I changed xml file and run parser to store data again, both my table view and nslog messege come up with a list of wrong data, eg, list of numbers only while my data contains lots of strings.
Display comes back to normal only I killed and rerun app again.
Any ideas?

答:
Using CoreData the simplest thing to do is to use a NSFetchedResultsController.  You can set your view controller to be the delegate for the NSFetchedResultsController, which will give you notifications when your data changes.  You can then update your table appropriately.

This tutorial might help: http://www.raywenderlich.com/999/core-data-tutorial-how-to-use-nsfetchedresultscontrolleY


问:
try to distinguish button because two button have one class name
i am making a simple project with selenium about making followers generator.But, i get stuck in a case that two button have same class name,i want to automatically press that button but every times i try it's take me to press first button that redirect me to login with facebook(second button is 'sign up' button that exactly i want to press)

see instagram and inspect sign up button and 'login with facebook' button you will notice that both button is using css name
  https://i.stack.imgur.com/UPSOp.png

答:
There are different ways to reach the element so try Xpath to reach 'Sign up' button:-</p>

```<code>.//button[contains(text(),'Sign up')]
</code>```

Body:
There are different ways to reach the element so try Xpath to reach 'Sign up' button:-

.//button[contains(text(),'Sign up')]


问:
Python convert simple integer list to Fibonacci sequence
I have an int element list.

I want to change that list to a Fibonacci series sequence.

```<code>data = [1,0,2,4,5]
output_data = [1,1,3,7,12]
</code>```

答:
import itertools as it

data = [1,0,2,4,5]

l = [e for e in it.accumulate(data)]

print(l)
# output_data = [1,1,3,7,12]
```

Body:
I have an int element list.

I want to change that list to a Fibonacci series sequence.

data = [1,0,2,4,5]
output_data = [1,1,3,7,12]


问:
can't change background-color of text input
Perhaps a stupid question:

Here is a screenshot of my login page with a text-input field where I set the background-color. In the developer tools the background color property shows up as red, but in the page it is still grey. Any ideas on how to change it to red?

edit: under computed it says:

edit:
this issue might be related to the chromium browser. On Chrome the background color is red

答:
Could you try this

input:-webkit-autofill {
background-color: transparent;
}


问:
Calling stored procedure with temporary table inside transactions
I have a javascript stored procedure which creates a temporary table inside it using the CTAS syntax to hold some temporary results during computation. I want to be able to call this stored procedure inside a transaction.
Is this not allowed?

CREATE PROCEDURE my_stored_proc()
RETURNS BOOLEAN NOT NULL
LANGUAGE javascript
EXECUTE AS CALLER
AS
$$
    ...
    var stmt = snowflake.createStatement(
        {sqlText: "CREATE TEMPORARY TABLE temp_table..."}
        );
    var rs = stmt.execute();
    ...
$$;

BEGIN;
...
CALL my_stored_proc();
...
COMMIT;```

I tried to wrap this stored proc with a transaction but it commits as soon as the stored proc completes, I want to be able to rollback the statements if there is an error thrown by the stored proc during execution.

答:
Remember that DDL statements (CREATE TABLE, etc.) cause an implicit COMMIT. Such statements should not be used inside a stored procedure if the procedure will be called inside a transaction.

https://docs.snowflake.com/en/sql-reference/stored-procedures-usage.html#transaction-management

Body:
I have a javascript stored procedure which creates a temporary table inside it using the CTAS syntax to hold some temporary results during computation. I want to be able to call this stored procedure inside a transaction.
Is this not allowed?

CREATE PROCEDURE my_stored_proc()
RETURNS BOOLEAN NOT NULL
LANGUAGE javascript
EXECUTE AS CALLER
AS
$$
    ...
    var stmt = snowflake.createStatement(
        {sqlText: "CREATE TEMPORARY TABLE temp_table..."}
        );
    var rs = stmt.execute();
    ...
$$;

BEGIN;
...
CALL my_stored_proc();
...
COMMIT;

I tried to wrap this stored proc with a transaction but it commits as soon as the stored proc completes, I want to be able to rollback the statements if there is an error thrown by the stored proc during execution.


问:
Problem with reading from a json file when refreshing th page Angular
I have an angular application and the client wants the path of the Backend in a json file, so he can change it easily whithout needing of another deployment.

Well i did it, but when i refresh the page or close the app and reopen it, the app don't detect the path of the backend, it is like a problem of retard or synchronisation.

This is the error in the console :

```<code> http://***/undefinedapi/Leave/GetlistLeave
</code>```

This is how i did it :
The json file :

```<code>    {
      "ApiRoot": "http://***/"
    }
</code>```

How i read from the constant from the json file :

```<code>     import { Injectable } from '@angular/core';
     import { Http, Response } from '@angular/http';
     import { Observable } from 'rxjs';
     import { apiRoot } from '../model/model.apiRoot';
     import { map } from 'rxjs/operators';

     @Injectable({
     providedIn: 'root'
     })
     export class apiRootService {
    static apiRoot: string;
     constructor(private http: Http) { }
     public initialiseApiRoot()
     {

         this.http.get('./assets/apiRoot/apiRoot.json').pipe(map((response: Response) =>
      <apiRoot>response.json())).subscribe(data => {
          apiRootService.apiRoot = data['ApiRoot'];
      })

     }
   }
</code>```

and then i call this function in the constructor of app.component.ts like this :

```<code>        this.apiRootService.initialiseApiRoot();
</code>```

and change the call of the api in every servic elike this :

```<code>       return this.http.get(apiRootService.apiRoot + .....
</code>```

Any hlp and thanks

答:
Well, let's suppose you're not facing a cache problem. If it isn't a cache problem, maybe it's a matter of timing.

You can try to set your apiRoot while your app is initializing (before app.component.ts is loaded). You can do that by providing an APP_INITIALIZER as described in Angular docs. If you use a factory that returns a function providing a promise, you'll delay your app initialization until your json file is loaded so you can initialize apiRoot. A factory is a useful approach because it will allow you to inject HttpClient service during initialization in the provider (you'll need it to get your json file).

You can do something like (in your app.module.ts):

...
import {APP_INITIALIZER} from '@angular/core';
...

// Angular will inject the HttpClient because you'll
// tell it that this is a dependency of this factory
// in the providers array
export function getApiRoot(http: HttpClient) {
  return () => {
    return this.http.get('./assets/apiRoot/apiRoot.json').pipe(
      map((response: Response) => <apiRoot>response.json()),
      tap((data: any) => apiRootService.apiRoot = data['ApiRoot'])
    ).toPromise();
  };
}

...

@NgModule({
  imports: [
    ...
    HttpClientModule,
    ...
  ],
  providers: [
    ...
    {
      provide: APP_INTIALIZER,
      useFactory: getApiRoot,
      multi: true,
      deps: [HttpClient]
    }
    ...
  ]

})
export class AppModule {}
```

Body:
I have an angular application and the client wants the path of the Backend in a json file, so he can change it easily whithout needing of another deployment.

Well i did it, but when i refresh the page or close the app and reopen it, the app don't detect the path of the backend, it is like a problem of retard or synchronisation.

This is the error in the console :

 http://***/undefinedapi/Leave/GetlistLeave

This is how i did it :
The json file :

    {
      "ApiRoot": "http://***/"
    }

How i read from the constant from the json file :

     import { Injectable } from '@angular/core';
     import { Http, Response } from '@angular/http';
     import { Observable } from 'rxjs';
     import { apiRoot } from '../model/model.apiRoot';
     import { map } from 'rxjs/operators';

     @Injectable({
     providedIn: 'root'
     })
     export class apiRootService {
    static apiRoot: string;
     constructor(private http: Http) { }
     public initialiseApiRoot()
     {

         this.http.get('./assets/apiRoot/apiRoot.json').pipe(map((response: Response) =>
      <apiRoot>response.json())).subscribe(data => {
          apiRootService.apiRoot = data['ApiRoot'];
      })

     }
   }

and then i call this function in the constructor of app.component.ts like this :

        this.apiRootService.initialiseApiRoot();

and change the call of the api in every servic elike this :

       return this.http.get(apiRootService.apiRoot + .....

Any hlp and thanks


问:
Psycopg2 auto reconnect inside a class
I've got class to connect to my Database.

```<code>import psycopg2, psycopg2.extensions
from parseini import config
import pandas as pd, pandas.io.sql as sqlio

class MyDatabase:
    def __init__(self, name='mydb.ini'):
        self.params = config(filename=name)
        self.my_connection = psycopg2.connect(**self.params)
        self.my_cursor = self.my_connection.cursor()

    def fetch_all_as_df(self, sql_statement):
        return sqlio.read_sql_query(sql_statement, self.my_connection)

    def df_to_sql(self, df):
        table = 'sometable'
        return sqlio.to_sql(df, table, self.my_connection)

    def __del__(self):
        self.my_cursor.close()
        self.my_connection.close()
</code>```

How could I reconnect to database and handle psycopg2.OperationalError in my case?

答:
You could make a decorator that tries to reconnect when psycopg2.InterfaceError or psycopg2.OperationalError are raised.

That's just an example how it could work and probably needs adjustments:

```<code>import time
from functools import wraps
import psycopg2, psycopg2.extensions

def retry(fn):
    @wraps(fn)
    def wrapper(*args, **kw):
        cls = args[0]
        for x in range(cls._reconnectTries):
            print(x, cls._reconnectTries)
            try:
                return fn(*args, **kw)
            except (psycopg2.InterfaceError, psycopg2.OperationalError) as e:
                print ("\nDatabase Connection [InterfaceError or OperationalError]")
                print ("Idle for %s seconds" % (cls._reconnectIdle))
                time.sleep(cls._reconnectIdle)
                cls._connect()
    return wrapper

class MyDatabase:
    _reconnectTries = 5
    _reconnectIdle = 2  # wait seconds before retying

    def __init__(self, name='mydb.ini'):
        self.my_connection = None
        self.my_cursor = None
        self.params = config(filename=name)
        self._connect()

    def _connect(self):
        self.my_connection = psycopg2.connect(**self.params)
        self.my_cursor = self.my_connection.cursor()

    @retry
    def fetch_all_as_df(self, sql_statement):
        return sqlio.read_sql_query(sql_statement, self.my_connection)

    @retry
    def dummy(self):
        self.my_cursor.execute('select 1+2 as result')
        return self.my_cursor.fetchone()

    @retry
    def df_to_sql(self, df):
        table = 'sometable'
        return sqlio.to_sql(df, table, self.my_connection)

    def __del__(self):
        # Maybe there is a connection but no cursor, whatever close silently!
        for c in (self.my_cursor, self.my_connection):
            try:
                c.close()
            except:
                pass

db = MyDatabase()
time.sleep(30)  # some time to shutdown the database
print(db.dummy())
</code>```

Output:

```<code>Database Connection [InterfaceError or OperationalError]
Idle for 2 seconds

Database Connection [InterfaceError or OperationalError]
Idle for 2 seconds

Database Connection [InterfaceError or OperationalError]
Idle for 2 seconds

Database Connection [InterfaceError or OperationalError]
Idle for 2 seconds
(3,)
</code>```

Note: _connect itself is not decorated, so this code assumes an initial connect always works!

Title: Psycopg2 auto reconnect inside a class

Body:
I've got class to connect to my Database.

import psycopg2, psycopg2.extensions
from parseini import config
import pandas as pd, pandas.io.sql as sqlio

class MyDatabase:
    def __init__(self, name='mydb.ini'):
        self.params = config(filename=name)
        self.my_connection = psycopg2.connect(**self.params)
        self.my_cursor = self.my_connection.cursor()

    def fetch_all_as_df(self, sql_statement):
        return sqlio.read_sql_query(sql_statement, self.my_connection)

    def df_to_sql(self, df):
        table = 'sometable'
        return sqlio.to_sql(df, table, self.my_connection)

    def __del__(self):
        self.my_cursor.close()
        self.my_connection.close()

How could I reconnect to database and handle psycopg2.OperationalError in my case?

Body:
You could make a decorator that tries to reconnect when psycopg2.InterfaceError or psycopg2.OperationalError are raised.

That's just an example how it could work and probably needs adjustments:

import time
from functools import wraps
import psycopg2, psycopg2.extensions

def retry(fn):
    @wraps(fn)
    def wrapper(*args, **kw):
        cls = args[0]
        for x in range(cls._reconnectTries):
            print(x, cls._reconnectTries)
            try:
                return fn(*args, **kw)
            except (psycopg2.InterfaceError, psycopg2.OperationalError) as e:
                print ("\nDatabase Connection [InterfaceError or OperationalError]")
                print ("Idle for %s seconds" % (cls._reconnectIdle))
                time.sleep(cls._reconnectIdle)
                cls._connect()
    return wrapper

class MyDatabase:
    _reconnectTries = 5
    _reconnectIdle = 2  # wait seconds before retying

    def __init__(self, name='mydb.ini'):
        self.my_connection = None
        self.my_cursor = None
        self.params = config(filename=name)
        self._connect()

    def _connect(self):
        self.my_connection = psycopg2.connect(**self.params)
        self.my_cursor = self.my_connection.cursor()

    @retry
    def fetch_all_as_df(self, sql_statement):
        return sqlio.read_sql_query(sql_statement, self.my_connection)

    @retry
    def dummy(self):
        self.my_cursor.execute('select 1+2 as result')
        return self.my_cursor.fetchone()

    @retry
    def df_to_sql(self, df):
        table = 'sometable'
        return sqlio.to_sql(df, table, self.my_connection)

    def __del__(self):
        # Maybe there is a connection but no cursor, whatever close silently!
        for c in (self.my_cursor, self.my_connection):
            try:
                c.close()
            except:
                pass

db = MyDatabase()
time.sleep(30)  # some time to shutdown the database
print(db.dummy())

Output:

Database Connection [InterfaceError or OperationalError]
Idle for 2 seconds

Database Connection [InterfaceError or OperationalError]
Idle for 2 seconds

Database Connection [InterfaceError or OperationalError]
Idle for 2 seconds

Database Connection [InterfaceError or OperationalError]
Idle for 2 seconds
(3,)

Note: _connect itself is not decorated, so this code assumes an initial connect always works!


问:
Start a redis server during jest tests
I am trying to write tests for a service that uses ioredis to connect to an elasticache server in AWS. I want to be able to isolate tests from the integration points and want to be able to connect to a redis server locally during the jest tests.

I am able to run setup/teardown of local infrastructure components via `jest. One of the necessary components is redis.

I don't see any tools to be able to start an in-memory server of redis for your application to then use and connect to via localhost:port.

The only thing I found is https://www.npmjs.com/package/redis-server which is 2 years old. Is this still the recommended tool for this type of job?

I can also try to start a docker container of redis during jest, but don't see any tools to be able to run the docker container from within jest.

Has anyone been able to solve this problem? The ioredis-mock is not really what I'm looking for as it seems to replace the entire ioredis suite instead of just allowing the 'real' ioredis to connect to a redis implementation over tcp (whether it be the real thing or a mock).

答:
You can always drop to the command line, and do what you need there. In the jest setup just run redis as you normally would via the command line, and in teardown do the same.
Child Process</p>

Title: Start a redis server during jest tests


答:
it doesn't need nesting for loops and subject is not defined in yours code.

```<code>def grade(point):
    result = ""
    if point >= 90:
        result = "A"
    elif point >= 80:
        result = "B"
    else:
        result = "C"
    return result
subject_ls = ["English", "Science", "math"]
score_ls = [80, 90, 100]

for i,subject in enumerate(subject_ls):
    print("{} {}".format(subject, score_ls[i]))
</code>```

Body:
it doesn't need nesting for loops and subject is not defined in yours code.

def grade(point):
    result = ""
    if point >= 90:
        result = "A"
    elif point >= 80:
        result = "B"
    else:
        result = "C"
    return result
subject_ls = ["English", "Science", "math"]
score_ls = [80, 90, 100]

for i,subject in enumerate(subject_ls):
    print("{} {}".format(subject, score_ls[i]))


问:
Cannot add JLabel or JButton to a JFrame. The frame won't show it
I'm new to Java. I'm trying to add JLabel to a JFrame but it doesn't show. I've tried adding JButton also but it does't seem to work. I've tried so many things over the past few days.

Anything wrong with my code?

```<code>public class F2 extends JPanel implements ActionListener {

    JFrame frame = new JFrame();
    JLabel label = new JLabel();
    int j = 2;
    ArrayList<Person> people = new ArrayList<>();

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        F2 f = new F2();

    }

    public F2() {
        j++;
        frame = new JFrame();
        frame.setSize(1380, 728);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Timer t = new Timer(20, this);
        t.restart();
        label.setText("Test");

        add(label);
frame.pack();
        frame.add(this);
        frame.setVisible(true);

        for (int i = 0; i < 100; i++) {
            people.add(new Person(0));
        }
    }

    public void paint(Graphics g) {
        super.paintComponent(g);
        Places p1 = new Places(g);
        for (Person p : people) {
            p.paint(g); //recall that each Person object has a paint method. We're passing g as the argument
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
    }
}
</code>```

答:
Copying Alex Rudenko answer:

You should have added the label to your panel and then add your panel to the frame. Now your empty panel replaces the label.

```<code>this.add(label)
frame.add(this)
</code>```

Maybe make it also visible and play with the coordinates and the size... or just copy a premade code from the internet... the way you are using the jpanel in the main class is maybe confusing you.

Body:
I'm new to Java. I'm trying to add JLabel to a JFrame but it doesn't show. I've tried adding JButton also but it does't seem to work. I've tried so many things over the past few days.

Anything wrong with my code?

public class F2 extends JPanel implements ActionListener {

    JFrame frame = new JFrame();
    JLabel label = new JLabel();
    int j = 2;
    ArrayList<Person> people = new ArrayList<>();

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        F2 f = new F2();

    }

    public F2() {
        j++;
        frame = new JFrame();
        frame.setSize(1380, 728);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Timer t = new Timer(20, this);
        t.restart();
        label.setText("Test");

        add(label);
frame.pack();
        frame.add(this);
        frame.setVisible(true);

        for (int i = 0; i < 100; i++) {
            people.add(new Person(0));
        }
    }

    public void paint(Graphics g) {
        super.paintComponent(g);
        Places p1 = new Places(g);
        for (Person p : people) {
            p.paint(g); //recall that each Person object has a paint method. We're passing g as the argument
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
    }
}

Body:
Copying Alex Rudenko answer:

You should have added the label to your panel and then add your panel to the frame. Now your empty panel replaces the label.

this.add(label)
frame.add(this)

Maybe make it also visible and play with the coordinates and the size... or just copy a premade code from the internet... the way you are using the jpanel in the main class is maybe confusing you.


问:
Grid gap being added to the one end of the grid
Im not sure why but my grid gap is being added to the right side of my grid , twice. This shouldnt be the classic using % problem as im using fr and in the developer tools i can see two grid gaps being added, Does anyone know why this is happening?

```<code>    .Portfolio .wrapper{
    grid-gap:10px;
    padding:40px 0px;
    width: 95%;
    margin: auto;
    display: grid;
    grid-template-columns: repeat(5,1fr) ;
    grid-auto-rows: 200px;
    grid-template-areas:
        "img-30 img-30 img-30 img-31 img-31"
        "img-30 img-30 img-30 img-31 img-31"
        "img-35 img-35 img-34 img-34 img-34"
        "img-35 img-35 img-34 img-34 img-34"
        "img-36 img-36 img-36 img-32 img-32"
        "img-36 img-36 img-36 img-32 img-32"

;
}
.Portfolio .wrapper >*{
    background-position: center;
    background-size: cover;
    cursor: pointer;
}
.Portfolio .wrapper .img-30{
    background-image: url("Images/30.jpg");
    grid-area: img-30;

}
.Portfolio .wrapper .img-31{
    background-image: url("Images/31.jpg");
    grid-area: img-31;

}
.Portfolio .wrapper .img-32{
    background-image: url("Images/32.jpg");
    grid-area: img-32;
}
.Portfolio .wrapper .img-33{
    background-image: url("Images/33.jpg");
    grid-area: img-33;
}
.Portfolio .wrapper .img-34{
    background-image: url("Images/34.jpg");
    grid-area: img-34;
}
.Portfolio .wrapper .img-35{
    background-image: url("Images/35.jpg");
    grid-area: img-35;
    background-color: red;
}
.Portfolio .wrapper .img-36{
    background-image: url("Images/36.jpg");
    grid-area: img-36;
}

<main class="Portfolio">
    <div class="wrapper">
        <div class="img-30"></div>
        <div class="img-31"></div>
        <div class="img-32"></div>
        <div class="img-33"></div>
        <div class="img-34"></div>
        <div class="img-35"></div>
        <div class="img-36"></div>
    </div>
</code>```

Here is my HTML - NOTE!! it says repeat(3,1fr) but its actually repeat(5,1fr)

答:
You haven't used .img-33 in your grid-template-areas:. The following code works for me:

CSS:

```<code>    .Portfolio .wrapper{
    grid-gap:10px;
    padding:40px 0px;
    width: 95%;
    margin: auto;
    display: grid;
    grid-template-columns: repeat(5,1fr) ;
    grid-auto-rows: 200px;
    grid-template-areas:
        "img-30 img-30 img-30 img-31 img-31"
        "img-30 img-30 img-30 img-31 img-31"
        "img-35 img-35 img-34 img-34 img-34"
        "img-35 img-35 img-34 img-34 img-34"
        "img-36 img-36 img-36 img-32 img-32"
        "img-36 img-36 img-36 img-32 img-32"
        "img-33 img-33 img-33 img-33 img-33";
}
.Portfolio .wrapper > * {
    background-position: center;
    background-size: cover;
    cursor: pointer;
}
.Portfolio .wrapper .img-30{
    background: blue;
    grid-area: img-30;

}
.Portfolio .wrapper .img-31{
    background: green;
    grid-area: img-31;

}
.Portfolio .wrapper .img-32{
    background: cyan;
    grid-area: img-32;
}
.Portfolio .wrapper .img-33{
    background: purple;
    grid-area: img-33;
}
.Portfolio .wrapper .img-34{
    background: pink;
    grid-area: img-34;
}
.Portfolio .wrapper .img-35{
    background: orange;
    grid-area: img-35;
    background-color: red;
}
.Portfolio .wrapper .img-36{
    background: yellow;
    grid-area: img-36;
}
</code>```

HTML:

```<code><main class="Portfolio">
    <div class="wrapper">
        <div class="img-30">30</div>
        <div class="img-31">31</div>
        <div class="img-32">32</div>
        <div class="img-33">33</div>
        <div class="img-34">34</div>
        <div class="img-35">35</div>
        <div class="img-36">36</div>
    </div>
</main>
</code>```

Check this demo: JSfiddle.

Body:
Im not sure why but my grid gap is being added to the right side of my grid , twice. This shouldnt be the classic using % problem as im using fr and in the developer tools i can see two grid gaps being added, Does anyone know why this is happening?

    .Portfolio .wrapper{
    grid-gap:10px;
    padding:40px 0px;
    width: 95%;
    margin: auto;
    display: grid;
    grid-template-columns: repeat(5,1fr) ;
    grid-auto-rows: 200px;
    grid-template-areas:
        "img-30 img-30 img-30 img-31 img-31"
        "img-30 img-30 img-30 img-31 img-31"
        "img-35 img-35 img-34 img-34 img-34"
        "img-35 img-35 img-34 img-34 img-34"
        "img-36 img-36 img-36 img-32 img-32"
        "img-36 img-36 img-36 img-32 img-32"

;
}
.Portfolio .wrapper >*{
    background-position: center;
    background-size: cover;
    cursor: pointer;
}
.Portfolio .wrapper .img-30{
    background-image: url("Images/30.jpg");
    grid-area: img-30;

}
.Portfolio .wrapper .img-31{
    background-image: url("Images/31.jpg");
    grid-area: img-31;

}
.Portfolio .wrapper .img-32{
    background-image: url("Images/32.jpg");
    grid-area: img-32;
}
.Portfolio .wrapper .img-33{
    background-image: url("Images/33.jpg");
    grid-area: img-33;
}
.Portfolio .wrapper .img-34{
    background-image: url("Images/34.jpg");
    grid-area: img-34;
}
.Portfolio .wrapper .img-35{
    background-image: url("Images/35.jpg");
    grid-area: img-35;
    background-color: red;
}
.Portfolio .wrapper .img-36{
    background-image: url("Images/36.jpg");
    grid-area: img-36;
}

Here is my HTML - NOTE!! it says repeat(3,1fr) but its actually repeat(5,1fr)

Body:
You haven't used .img-33 in your grid-template-areas:. The following code works for me:

CSS:

    .Portfolio .wrapper{
    grid-gap:10px;
    padding:40px 0px;
    width: 95%;
    margin: auto;
    display: grid;
    grid-template-columns: repeat(5,1fr) ;
    grid-auto-rows: 200px;
    grid-template-areas:
        "img-30 img-30 img-30 img-31 img-31"
        "img-30 img-30 img-30 img-31 img-31"
        "img-35 img-35 img-34 img-34 img-34"
        "img-35 img-35 img-34 img-34 img-34"
        "img-36 img-36 img-36 img-32 img-32"
        "img-36 img-36 img-36 img-32 img-32"
        "img-33 img-33 img-33 img-33 img-33";
}
.Portfolio .wrapper > * {
    background-position: center;
    background-size: cover;
    cursor: pointer;
}
.Portfolio .wrapper .img-30{
    background: blue;
    grid-area: img-30;

}
.Portfolio .wrapper .img-31{
    background: green;
    grid-area: img-31;

}
.Portfolio .wrapper .img-32{
    background: cyan;
    grid-area: img-32;
}
.Portfolio .wrapper .img-33{
    background: purple;
    grid-area: img-33;
}
.Portfolio .wrapper .img-34{
    background: pink;
    grid-area: img-34;
}
.Portfolio .wrapper .img-35{
    background: orange;
    grid-area: img-35;
    background-color: red;
}
.Portfolio .wrapper .img-36{
    background: yellow;
    grid-area: img-36;
}

HTML:

<main class="Portfolio">
    <div class="wrapper">
        <div class="img-30">30</div>
        <div class="img-31">31</div>
        <div class="img-32">32</div>
        <div class="img-33">33</div>
        <div class="img-34">34</div>
        <div class="img-35">35</div>
        <div class="img-36">36</div>
    </div>
</main>

Check this demo: JSfiddle.


问:
HTML Form not sending any data to Laravel serverside
I am trying to upload a file using a form and Laravel. My form:

```<code><form action="testUpload" nctype='multipart/form-data' method='POST'>
  <input type="hidden" name="_Token" value="{{ csrf_token() }}">
  <div class="col-md-12" style="margin-top: 25px">
     <div class="input-group mb-3">
        <div class="custom-file">
           <input type="file" class="custom-file-input" id="inputGroupFile01">
           <label class="custom-file-label" id="uploadFile" for="inputGroupFile01">Choose file</label>
       </div>
    </div>
    <input type="submit" class="btn btn-success" />
 </div>
</form>
</code>```

My route is as follows:

```<code>Route::group(['middleware' => 'web'], function(){
    Route::post('/testUpload', 'uploadController@upload');
});
</code>```

And my controller:

```<code>public function upload(){
    $data = Request::all();
    return $data;
}
</code>```

Currently, I am getting a 419 Page Expired error when pressing the button. What am I missing? I have tried clearing all my route cache

答:
You are missing CSRF field in your form. All forms should have it.
You can add it easy with @csrf between <form> and </form>

Note: nctype='multipart/form-data' should be enctype='multipart/form-data'

Body:
I am trying to upload a file using a form and Laravel. My form:

<form action="testUpload" nctype='multipart/form-data' method='POST'>
  <input type="hidden" name="_Token" value="{{ csrf_token() }}">

           <input type="file" class="custom-file-input" id="inputGroupFile01">
           Choose file

    <input type="submit" class="btn btn-success" />

</form>

My route is as follows:

Route::group(['middleware' => 'web'], function(){
    Route::post('/testUpload', 'uploadController@upload');
});

And my controller:

public function upload(){
    $data = Request::all();
    return $data;
}

Currently, I am getting a 419 Page Expired error when pressing the button. What am I missing? I have tried clearing all my route cache


问:
SearchDelegate does not call buildResults method
I have a list view and an Appbar. The Appbar has a search icon on which I am calling the SearchDelegate. Following is my code for SearchDelegate

```<code>class StudentSearch extends SearchDelegate<StudentModel> {
  final Observable<StudentModel> studentModelDataList;

  StudentSearch(this.studentModelDataList);

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
          icon: Icon(Icons.clear),
          onPressed: () {
            query = "";
          }),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
        icon: Icon(Icons.arrow_back),
        onPressed: () {
          close(context, null);
        });
  }

  @override
  Widget buildResults(BuildContext context) {
    return Text(query);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return StreamBuilder(
        stream: studentModelDataList,
        builder: (context, AsyncSnapshot<StudentModel> snapshot) {
          if (!snapshot.hasData || snapshot.data == null) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }

          final results = snapshot.data.studentModelData.studentData
              .where((a) => a.studName.toLowerCase().contains(query.toLowerCase()))
              .toList();

          if (snapshot.data != null) {
            return Refresh(
              year_id: "2",
              schoolId: "1",
              lastIndex: "0",
              disciplineId: "1",
              child: ListView.builder(
                itemBuilder: (context, int index) {
                  return ListTile(
                    onTap: (){
                      print(snapshot.data.studentModelData.studentData[index].studName);
query = snapshot.data.studentModelData.studentData[index].studName;
                          close(context, snapshot.data);

                    },
                    title: Text(results[index].studName),
                    subtitle: Text('${results[index].studentEmail} '),
                    trailing: Column(
                      children: [
                        Icon(Icons.comment),
                        Text('${results[index].classCode}'),
                      ],
                    ),
                  );
                },
                itemCount: results.length,
              ),
            );
          }
        });
  }
}
</code>```

What I understand from the documentation is that whenever I enter an item to be searched, the SearchDelegate first shows buildSuggestions and then  buildResults. So I am trying to search by a student name and the buildSuggestions method works properly but when I click on an item of buildSuggestions, it does not show me buildresults

答:
BuildSuggestions is meant to do just that, build a list of suggestions to whatever is typed in the search bar. The listener responds to each and every change to the Text Field state. This could be used to provide autocomplete suggestions to the user.

BuildResults is called when the user calls for the results by clicking on the "magnifying glass" button on the keyboard, or whatever is used to "submit" the results indicating that the user has finished their typing and is requesting the results of the text search.

You can see an explanation here Flutter's Search Support (The Boring Flutter Development Show, Ep. 10)

Taken from the documentation for  buildResults(BuildContext context) → Widget "The results shown after the user submits a search from the search page."

Body:
I have a list view and an Appbar. The Appbar has a search icon on which I am calling the SearchDelegate. Following is my code for SearchDelegate

class StudentSearch extends SearchDelegate<StudentModel> {
  final Observable<StudentModel> studentModelDataList;

  StudentSearch(this.studentModelDataList);

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
          icon: Icon(Icons.clear),
          onPressed: () {
            query = "";
          }),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
        icon: Icon(Icons.arrow_back),
        onPressed: () {
          close(context, null);
        });
  }

  @override
  Widget buildResults(BuildContext context) {
    return Text(query);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return StreamBuilder(
        stream: studentModelDataList,
        builder: (context, AsyncSnapshot<StudentModel> snapshot) {
          if (!snapshot.hasData || snapshot.data == null) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }

          final results = snapshot.data.studentModelData.studentData
              .where((a) => a.studName.toLowerCase().contains(query.toLowerCase()))
              .toList();

          if (snapshot.data != null) {
            return Refresh(
              year_id: "2",
              schoolId: "1",
              lastIndex: "0",
              disciplineId: "1",
              child: ListView.builder(
                itemBuilder: (context, int index) {
                  return ListTile(
                    onTap: (){
                      print(snapshot.data.studentModelData.studentData[index].studName);
query = snapshot.data.studentModelData.studentData[index].studName;
                          close(context, snapshot.data);

                    },
                    title: Text(results[index].studName),
                    subtitle: Text('${results[index].studentEmail} '),
                    trailing: Column(
                      children: [
                        Icon(Icons.comment),
                        Text('${results[index].classCode}'),
                      ],
                    ),
                  );
                },
                itemCount: results.length,
              ),
            );
          }
        });
  }
}

What I understand from the documentation is that whenever I enter an item to be searched, the SearchDelegate first shows buildSuggestions and then  buildResults. So I am trying to search by a student name and the buildSuggestions method works properly but when I click on an item of buildSuggestions, it does not show me buildresults


问:
Strange behavior when mobile website is added to iPhone's "Home Screen" as a web app
I have a mobile oriented web site which is not intended to be run as a mobile web app. When users add the mobile site to their iPhone's home screen links do not work and the site gets broken.
Is there a way to detect a mobile site is running as an iPhone web app (from the Home Screen) and have it automatically launch in Safari instead? In other words, if the user "Add to Home Screen" to have it behave like a bookmark?</p>

答: Remove <meta name="apple-mobile-web-app-capable" content="yes"> from your HTML. Websites as home screen icons open in Safari unless specifically ordered not to using that meta tag.


问:
Rails 6: link to destroy_user_session_path using GET instead of DELETE
I have just started a simple Rails 6.0.3.1 project.

I'm setting up the Devise actions, but the logout link doesn't seem to work. It's performing a GET request instead of a DELETE despite the fact that I specify the method:

```<code>- if user_signed_in?
  = link_to 'Logout',
    destroy_user_session_path,
    class: 'button is-light',
    method: :delete

</code>```

Clicking the link yields:

There are no errors in the console:

My app/javascript/packs/application.js looks like this:

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
```

<p>So Rails ujs should be intercepting the link click and performing a <code>DELETE</code>, but it's not.</p>

<p>My <code>config/webpack/environment.js</code> looks like this:</p>

<pre class="lang-js prettyprint-override"><code>const { environment } = require('@rails/webpacker')
const { VueLoaderPlugin } = require('vue-loader')
const vue = require('./loaders/vue')

environment.plugins.prepend('VueLoaderPlugin', new VueLoaderPlugin())
environment.loaders.prepend('vue', vue)
module.exports = environment
</code>```

I tried searching for a solution on other SO threads but I didn't find something that works. Some people suggested using a button instead of a link, but I want a link not a button.

The issue occurred after I installed Bulma CSS framework via yarn:

yarn add bulma
```

<p>which I then imported into my project in <code>app/javascript/packs/application.scss</code> with:</p>

```@import '~bulma';
```

<p>My layout file (<code>application.html.erb</code>) includes the lines:</p>

```<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= stylesheet_pack_tag 'application' %>
```

I've created a simple dummy app to reproduce the problem.

Any advice on what I might be doing incorrectly here?

Thanks in advance!

答:
I ultimately found the solution.

I created the file app/javascript/stylesheets/application.scss where I put the line:

```<code>@import '~bulma';
</code>```

Then, in app/javascript/stylesheets/application.js I added the line:

import 'stylesheets/application'
```

It seems that webpacker requires the application.js file to import the appropriate CSS files in order to work.

Body:
I have just started a simple Rails 6.0.3.1 project.

I'm setting up the Devise actions, but the logout link doesn't seem to work. It's performing a GET request instead of a DELETE despite the fact that I specify the method:

- if user_signed_in?
  = link_to 'Logout',
    destroy_user_session_path,
    class: 'button is-light',
    method: :delete

Clicking the link yields:

There are no errors in the console:

My app/javascript/packs/application.js looks like this:

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

So Rails ujs should be intercepting the link click and performing a DELETE, but it's not.

My config/webpack/environment.js looks like this:

const { environment } = require('@rails/webpacker')
const { VueLoaderPlugin } = require('vue-loader')
const vue = require('./loaders/vue')

environment.plugins.prepend('VueLoaderPlugin', new VueLoaderPlugin())
environment.loaders.prepend('vue', vue)
module.exports = environment

I tried searching for a solution on other SO threads but I didn't find something that works. Some people suggested using a button instead of a link, but I want a link not a button.

The issue occurred after I installed Bulma CSS framework via yarn:

yarn add bulma

which I then imported into my project in app/javascript/packs/application.scss with:

@import '~bulma';

My layout file (application.html.erb) includes the lines:

<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= stylesheet_pack_tag 'application' %>

I've created a simple dummy app to reproduce the problem.

Any advice on what I might be doing incorrectly here?

Thanks in advance!

Body:
I ultimately found the solution.

I created the file app/javascript/stylesheets/application.scss where I put the line:

@import '~bulma';

Then, in app/javascript/stylesheets/application.js I added the line:

import 'stylesheets/application'

It seems that webpacker requires the application.js file to import the appropriate CSS files in order to work.


问:
Showing TextField's error text does not work
I'm building the changePassword module on an app and I want to check that the field its not empty but its not working and I don't know why

```<code>Card(
  color: Color(0xFFDBE2EF),
  margin: EdgeInsets.symmetric(
      vertical: 10, horizontal: 25),
  child: TextField(
    controller: passwordConfirmController,
    obscureText: true,
    decoration: InputDecoration(
        border: OutlineInputBorder(),
        labelText: 'Confirmar contraseña',
        labelStyle:
            TextStyle(fontFamily: 'Montserrat')),
  ),
),
SizedBox(
  height: 20,
),
RaisedButton(
    color: Color(0xFFDBE2EF),
    onPressed: () => {
          setState(() {
            print("Valor _validate antes");
            print(_validate);
            print("Valor isEmpty");
            print(passwordController.text.isEmpty);
            passwordController.text.isEmpty
                ? _validate = true
                : _validate = false;
            _isLoading = true;
            print("Valor _validate después");
            print(_validate);
          }),
          changePass(passwordController.text),
        },
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(5),
    ),
    child: Text(
      'Actualizar',
      style: TextStyle(
          fontSize: 20,
          fontFamily: 'Montserrat',
          color: Color(0xFF002D53),
          fontWeight: FontWeight.bold),
    )),
</code>```

The values on raisedbutton where I check if the password is empty seems to be working printing the expected values, but the error text does not work

答:
You have to change _validate property inside setState(), and based on that change TextField error text

```<code>class FirstScreen extends StatefulWidget {
  @override
  _FirstScreenState createState() => _FirstScreenState();
}

class _FirstScreenState extends State<FirstScreen> {
  final passwordConfirmController = TextEditingController();
  bool _validate = false;

  void _validatePassword() {
    if (passwordConfirmController.text.isEmpty) {
      _validate = true;
    } else {
      _validate = false;
    }
    setState(() {
      _validate;
      print("Valor _validate después");
      print(_validate);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: <Widget>[
          Card(
            color: Color(0xFFDBE2EF),
            margin: EdgeInsets.symmetric(vertical: 10, horizontal: 25),
            child: TextField(
              controller: passwordConfirmController,
              obscureText: true,
              decoration: InputDecoration(
                  errorText: _validate ? "Enter Password" : null,
                  border: OutlineInputBorder(),
                  labelText: 'Confirmar contraseña',
                  labelStyle: TextStyle(fontFamily: 'Montserrat')),
            ),
          ),
          SizedBox(
            height: 20,
          ),
          RaisedButton(
              color: Color(0xFFDBE2EF),
              onPressed: () => {_validatePassword()},
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5),
              ),
              child: Text(
                'Actualizar',
                style: TextStyle(
                    fontSize: 20,
                    fontFamily: 'Montserrat',
                    color: Color(0xFF002D53),
                    fontWeight: FontWeight.bold),
              )),
        ],
      ),
    );
  }
}
</code>```

Body:
I'm building the changePassword module on an app and I want to check that the field its not empty but its not working and I don't know why

Card(
  color: Color(0xFFDBE2EF),
  margin: EdgeInsets.symmetric(
      vertical: 10, horizontal: 25),
  child: TextField(
    controller: passwordConfirmController,
    obscureText: true,
    decoration: InputDecoration(
        border: OutlineInputBorder(),
        labelText: 'Confirmar contraseña',
        labelStyle:
            TextStyle(fontFamily: 'Montserrat')),
  ),
),
SizedBox(
  height: 20,
),
RaisedButton(
    color: Color(0xFFDBE2EF),
    onPressed: () => {
          setState(() {
            print("Valor _validate antes");
            print(_validate);
            print("Valor isEmpty");
            print(passwordController.text.isEmpty);
            passwordController.text.isEmpty
                ? _validate = true
                : _validate = false;
            _isLoading = true;
            print("Valor _validate después");
            print(_validate);
          }),
          changePass(passwordController.text),
        },
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(5),
    ),
    child: Text(
      'Actualizar',
      style: TextStyle(
          fontSize: 20,
          fontFamily: 'Montserrat',
          color: Color(0xFF002D53),
          fontWeight: FontWeight.bold),
    )),

The values on raisedbutton where I check if the password is empty seems to be working printing the expected values, but the error text does not work

Body:
You have to change _validate property inside setState(), and based on that change TextField error text

class FirstScreen extends StatefulWidget {
  @override
  _FirstScreenState createState() => _FirstScreenState();
}

class _FirstScreenState extends State<FirstScreen> {
  final passwordConfirmController = TextEditingController();
  bool _validate = false;

  void _validatePassword() {
    if (passwordConfirmController.text.isEmpty) {
      _validate = true;
    } else {
      _validate = false;
    }
    setState(() {
      _validate;
      print("Valor _validate después");
      print(_validate);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: <Widget>[
          Card(
            color: Color(0xFFDBE2EF),
            margin: EdgeInsets.symmetric(vertical: 10, horizontal: 25),
            child: TextField(
              controller: passwordConfirmController,
              obscureText: true,
              decoration: InputDecoration(
                  errorText: _validate ? "Enter Password" : null,
                  border: OutlineInputBorder(),
                  labelText: 'Confirmar contraseña',
                  labelStyle: TextStyle(fontFamily: 'Montserrat')),
            ),
          ),
          SizedBox(
            height: 20,
          ),
          RaisedButton(
              color: Color(0xFFDBE2EF),
              onPressed: () => {_validatePassword()},
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5),
              ),
              child: Text(
                'Actualizar',
                style: TextStyle(
                    fontSize: 20,
                    fontFamily: 'Montserrat',
                    color: Color(0xFF002D53),
                    fontWeight: FontWeight.bold),
              )),
        ],
      ),
    );
  }
}


问:
python click module input for each function
I'm a new bee for python currently working on the Click module. So here I have a doubt to providing input for the main cli function only. But I want to provide the input for my all the function one by one. is it possible to click? Thanks for advance.

```<code>@click.option('--create', default='sub', help='Create')
@click.command()
def create(create):
    click.echo('create called')
    os.system('curl http://127.0.0.1:5000/create')
@click.option('--conn', default='in', help='connect to server')
@click.command()
def conn(conn):
    click.echo('conn called')
    os.system('curl http://127.0.0.1:5000/')
</code>```

and my setup.py

```<code>from setuptools import setup
setup(
     name="hello",
     version='0.1',
     py_modules=['hello'],
     install_requires=[
                    'Click',
     ],
     entry_points='''
     [console_scripts]
     hello=hello:cli
''',
)
</code>```

My output expectation

```<code>$ hello --conn in
  success
  hello --create sub
  success
</code>```

答:
Sounds to me like you want different commands based on input provided to your hello  cli. For that reason, Click has the useful notion of a group, a collection of commands that can be invoked.

You can reorganize your code as follows:

@click.group()
def cli():
    pass

@cli.command()
def create():
    click.echo('create called')
    os.system('curl http://127.0.0.1:5000/create')

@cli.command()
def conn():
    click.echo('conn called')
    os.system('curl http://127.0.0.1:5000/')

def main():
    value = click.prompt('Select a command to run', type=click.Choice(list(cli.commands.keys()) + ['exit']))
    while value != 'exit':
        cli.commands[value]()

if __name__ == "__main__":
    main()

```

<p>and the calls would be:</p>

<pre class="lang-sh prettyprint-override"><code>$ hello con
$ hello create
</code>```

It doesn't seem like you need the options, as you don't change the behaviour of each command based on the option being passed in or not. For more information, please refer to the commands and groups Click documentation

Body:
I'm a new bee for python currently working on the Click module. So here I have a doubt to providing input for the main cli function only. But I want to provide the input for my all the function one by one. is it possible to click? Thanks for advance.

@click.option('--create', default='sub', help='Create')
@click.command()
def create(create):
    click.echo('create called')
    os.system('curl http://127.0.0.1:5000/create')
@click.option('--conn', default='in', help='connect to server')
@click.command()
def conn(conn):
    click.echo('conn called')
    os.system('curl http://127.0.0.1:5000/')

and my setup.py

from setuptools import setup
setup(
     name="hello",
     version='0.1',
     py_modules=['hello'],
     install_requires=[
                    'Click',
     ],
     entry_points='''
     [console_scripts]
     hello=hello:cli
''',
)

My output expectation

$ hello --conn in
  success
  hello --create sub
  success

Body:
Sounds to me like you want different commands based on input provided to your hello  cli. For that reason, Click has the useful notion of a group, a collection of commands that can be invoked.

You can reorganize your code as follows:

@click.group()
def cli():
    pass

@cli.command()
def create():
    click.echo('create called')
    os.system('curl http://127.0.0.1:5000/create')

@cli.command()
def conn():
    click.echo('conn called')
    os.system('curl http://127.0.0.1:5000/')

def main():
    value = click.prompt('Select a command to run', type=click.Choice(list(cli.commands.keys()) + ['exit']))
    while value != 'exit':
        cli.commands[value]()

if __name__ == "__main__":
    main()

and the calls would be:

$ hello con
$ hello create

It doesn't seem like you need the options, as you don't change the behaviour of each command based on the option being passed in or not. For more information, please refer to the commands and groups Click documentation


问:
Unable to load variable from service in Angular 9
I am trying to create a web-app for a game that involves starting and joining rooms. I am using Angular and Socket.io for the project. I have components named Startpage and Lobby. Startpage contains text boxes for player name and Room ID. It also has buttons for "Start Game" and "Join Game". Clicking on the "Start Game" button triggers the startThisGame() function.

```<code>//startpage.component.ts

import { Component, OnInit, Output, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { SocketioService } from '../socketio.service';

@Component({
  selector: 'app-startpage',
  templateUrl: './startpage.component.html',
  styleUrls: ['./startpage.component.css']
})

export class StartpageComponent implements OnInit {

  constructor( private router: Router, public zone: NgZone, private socketService: SocketioService ) {}

  ngOnInit() {
    this.socketService.setupSocketConnection();
  }
  testRoomId = 'xxxx'

  startThisGame() {
    var playerName = (document.getElementById("nameInput") as HTMLInputElement).value;
    if (playerName) {
      this.testRoomId = this.socketService.startGame(playerName);
      alert("In component: " + this.testRoomId)
      this.zone.run(() => {this.router.navigate(['/lobby']); });
    }
    else{
      alert("Enter a player name!")
    }
  }
}
</code>```

The code inside socketService goes as follows.

```<code>import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class SocketioService {
  socket;
  public roomId: string;
  public playerName: string;
  constructor() {}

  setupSocketConnection() {
    this.socket = io(environment.SOCKET_ENDPOINT)
    alert("Connection set-up")
  }

  startGame(inputPlayerName) {
    this.socket.emit('startGame', {name: inputPlayerName})
    this.playerName = inputPlayerName
    this.socket.on('recieveRoomId', (data: any) => {
      this.roomId = data.code
      alert("In service startGame: " + this.roomId)
    })
    return this.roomId
  }

  getRoomId() {
    alert("In service getRoomId: " + this.roomId)
    return this.roomId;
  }
}
</code>```

The server code creates a unique room ID and passes it to the roomId variable in socketService. My first question starts here. If you notice, I have left a trail of alert messages along the way. I would expect the order of alert messages to be alert("In service startGame: " + this.roomId) and then alert("In component: " + this.testRoomId). However, I get the alert messages in the opposite order and the roomId's are undefined even though the server generates and emits a unique roomId. I do not seem to understand why this is happening.

Secondly, you can see that the startThisGame() function causes socketService to store the generated roomId and playerName inside the class and then reroutes the app to the lobby component. The lobby code goes as follows.

```<code>import { Component, OnInit, OnChanges, AfterContentInit, SimpleChanges, Input } from '@angular/core';
import { SocketioService } from '../socketio.service';

@Component({
  selector: 'app-lobby',
  templateUrl: './lobby.component.html',
  styleUrls: ['./lobby.component.css']
})
export class LobbyComponent implements OnInit, AfterContentInit {
  constructor(private socketService: SocketioService) { }
  @Input()  roomId: string;

  ngOnInit(): void {
    // alert("On init fetched")
    this.socketService.setupSocketConnection()
    this.roomId = this.socketService.getRoomId()
    if (this.roomId) {
      alert("Value obtained in init: " + this.roomId)
    }
    else {
      alert("No value obtained inside init")
    }
    document.getElementById("generated_code").innerHTML = this.roomId
  }
}
</code>```

Here, OnInit, the socketService.getRoomId() function returns an undefined value. If I press back, go to the startpage again, enter a playerName and start a new game again, the previously generated roomId is being rendered. What am I missing here? How do I load the roomId and display the same when I am rerouted to the lobby?

答:
The problem here is that that every socket is asynchronous.

The reason why you are getting the alerts in reversed orer is that you wrote

```<code> if (playerName) {
  this.testRoomId = this.socketService.startGame(playerName);
  alert("In component: " + this.testRoomId)
  this.zone.run(() => {this.router.navigate(['/lobby']); });
}

this.socket.on('recieveRoomId', (data: any) => {
      this.roomId = data.code
      alert("In service startGame: " + this.roomId)
    })
</code>```

This way the alert is emitted on the event of reciving  a new room id which is asnyc. This way the the code finishes to execute the startgame function and the returns to the main function which then alerts the 'In component' alert and when the socket receives the event it alerts the dialog.

The solution what I think shouléd be the the best is to work with RxJs and put roomId into a ReplaySubject.

So modify the service to

```<code>private roomId: ReplaySubject<string>=new ReplaySubject();
        startGame(inputPlayerName) {
            this.socket.emit('startGame', {name: inputPlayerName})
            this.playerName = inputPlayerName
            this.socket.on('recieveRoomId', (data: any) => {
              this.roomId.next(data.code)
              alert("In service startGame: " + this.roomId)
            })
          }

        getRoomId() {
          alert("In service getRoomId: " + this.roomId)
          return this.roomId.asObservable();
        }
</code>```

And in the component

```<code>     ngOnInit(): void {
            // alert("On init fetched")
            this.socketService.setupSocketConnection()
            this.socketService.getRoomId().subscribe((roomId)=>{
                 this.roomId=roomId;
                 //More logic here when getting a new roomId
            });
          }
</code>```

And dont forget to call the startGame method :)
If you want to learn more about ReplaySubject check out its awesome docs.

Body:
I am trying to create a web-app for a game that involves starting and joining rooms. I am using Angular and Socket.io for the project. I have components named Startpage and Lobby. Startpage contains text boxes for player name and Room ID. It also has buttons for "Start Game" and "Join Game". Clicking on the "Start Game" button triggers the startThisGame() function.

//startpage.component.ts

import { Component, OnInit, Output, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { SocketioService } from '../socketio.service';

@Component({
  selector: 'app-startpage',
  templateUrl: './startpage.component.html',
  styleUrls: ['./startpage.component.css']
})

export class StartpageComponent implements OnInit {

  constructor( private router: Router, public zone: NgZone, private socketService: SocketioService ) {}

  ngOnInit() {
    this.socketService.setupSocketConnection();
  }
  testRoomId = 'xxxx'

  startThisGame() {
    var playerName = (document.getElementById("nameInput") as HTMLInputElement).value;
    if (playerName) {
      this.testRoomId = this.socketService.startGame(playerName);
      alert("In component: " + this.testRoomId)
      this.zone.run(() => {this.router.navigate(['/lobby']); });
    }
    else{
      alert("Enter a player name!")
    }
  }
}

The code inside socketService goes as follows.

import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class SocketioService {
  socket;
  public roomId: string;
  public playerName: string;
  constructor() {}

  setupSocketConnection() {
    this.socket = io(environment.SOCKET_ENDPOINT)
    alert("Connection set-up")
  }

  startGame(inputPlayerName) {
    this.socket.emit('startGame', {name: inputPlayerName})
    this.playerName = inputPlayerName
    this.socket.on('recieveRoomId', (data: any) => {
      this.roomId = data.code
      alert("In service startGame: " + this.roomId)
    })
    return this.roomId
  }

  getRoomId() {
    alert("In service getRoomId: " + this.roomId)
    return this.roomId;
  }
}

The server code creates a unique room ID and passes it to the roomId variable in socketService. My first question starts here. If you notice, I have left a trail of alert messages along the way. I would expect the order of alert messages to be alert("In service startGame: " + this.roomId) and then alert("In component: " + this.testRoomId). However, I get the alert messages in the opposite order and the roomId's are undefined even though the server generates and emits a unique roomId. I do not seem to understand why this is happening.

Secondly, you can see that the startThisGame() function causes socketService to store the generated roomId and playerName inside the class and then reroutes the app to the lobby component. The lobby code goes as follows.

import { Component, OnInit, OnChanges, AfterContentInit, SimpleChanges, Input } from '@angular/core';
import { SocketioService } from '../socketio.service';

@Component({
  selector: 'app-lobby',
  templateUrl: './lobby.component.html',
  styleUrls: ['./lobby.component.css']
})
export class LobbyComponent implements OnInit, AfterContentInit {
  constructor(private socketService: SocketioService) { }
  @Input()  roomId: string;

  ngOnInit(): void {
    // alert("On init fetched")
    this.socketService.setupSocketConnection()
    this.roomId = this.socketService.getRoomId()
    if (this.roomId) {
      alert("Value obtained in init: " + this.roomId)
    }
    else {
      alert("No value obtained inside init")
    }
    document.getElementById("generated_code").innerHTML = this.roomId
  }
}

Here, OnInit, the socketService.getRoomId() function returns an undefined value. If I press back, go to the startpage again, enter a playerName and start a new game again, the previously generated roomId is being rendered. What am I missing here? How do I load the roomId and display the same when I am rerouted to the lobby?

Body:
The problem here is that that every socket is asynchronous.

The reason why you are getting the alerts in reversed orer is that you wrote

 if (playerName) {
  this.testRoomId = this.socketService.startGame(playerName);
  alert("In component: " + this.testRoomId)
  this.zone.run(() => {this.router.navigate(['/lobby']); });
}

this.socket.on('recieveRoomId', (data: any) => {
      this.roomId = data.code
      alert("In service startGame: " + this.roomId)
    })

This way the alert is emitted on the event of reciving  a new room id which is asnyc. This way the the code finishes to execute the startgame function and the returns to the main function which then alerts the 'In component' alert and when the socket receives the event it alerts the dialog.

The solution what I think shouléd be the the best is to work with RxJs and put roomId into a ReplaySubject.

So modify the service to

private roomId: ReplaySubject<string>=new ReplaySubject();
        startGame(inputPlayerName) {
            this.socket.emit('startGame', {name: inputPlayerName})
            this.playerName = inputPlayerName
            this.socket.on('recieveRoomId', (data: any) => {
              this.roomId.next(data.code)
              alert("In service startGame: " + this.roomId)
            })
          }

        getRoomId() {
          alert("In service getRoomId: " + this.roomId)
          return this.roomId.asObservable();
        }

And in the component

     ngOnInit(): void {
            // alert("On init fetched")
            this.socketService.setupSocketConnection()
            this.socketService.getRoomId().subscribe((roomId)=>{
                 this.roomId=roomId;
                 //More logic here when getting a new roomId
            });
          }

And dont forget to call the startGame method :)
If you want to learn more about ReplaySubject check out its awesome docs.