问:
How to make webpack module (inner logic) self execute?
This is the following module output that webpack generates:
I can see that it saves in the window.webpackJsonp array, however, the logic business of the module doesn't seem to execute in the case when I include the below result on any other page from where the whole project sits (parallel subproject that doesn't have webpack architecture)

My question can somebody please give small insight of why it happens and if there a possible workaround to make this module:

- Make it independent and really self-executed it's business logic whenever it's loaded to the page

- or what webpack dependencies should be loaded previously on the page to ensure that it will pick up the modules registered in webpack.webpackJsonp and execute them

(window["webpackJsonp"] = window["webpackJsonp"] || []).push([
    ["xxx-fit-responsive/xxx-fit-responsive-package/src/main/jcr_root/apps/xxx/fit/responsive/par/alertribbon/clientlib/publish/alertribbon.publish.bundle.js"],
    {
        /***/ "../../../xxx-fit-responsive/xxx-fit-responsive-package/src/main/jcr_root/apps/xxx/fit/responsive/par/alertribbon/clientlib/publish/alertribbon.publish.entry.js": /***/ function (
            module,
            __webpack_exports__,
            __webpack_require__
        ) {
            "use strict";
            eval(
                'eval("__webpack_require__.r(__webpack_exports__);\\n/* harmony import */ var core_js_modules_es_array_index_of__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(\\"./node_modules/core-js/modules/es.array.index-of.js\\");\\n/* harmony import */ var core_js_modules_es_array_index_of__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(core_js_modules_es_array_index_of__WEBPACK_IMPORTED_MODULE_0__);\\n\\n\\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\\"Cannot call a class as a function\\"); } }\\n\\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\\"value\\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\\n\\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\\n\\nvar AlertRibbon =\\n/*#__PURE__*/\\nfunction () {\\n  function AlertRibbon(el) {\\n    _classCallCheck(this, AlertRibbon);\\n\\n    if (!el) {\\n      return;\\n    }\\n\\n    debugger;\\n    this.$elements = {\\n      el: el\\n    };\\n    this.init();\\n  }\\n\\n  _createClass(AlertRibbon, [{\\n    key: \\"setElements\\",\\n    value: function setElements() {\\n      this.$elements.closeButton = this.$elements.el.querySelector(\'.alertribbon__closeButton\');\\n    }\\n    /**\\n     * @param {event} event\\n     */\\n\\n  }, {\\n    key: \\"slideComponentOutUp\\",\\n    value: function slideComponentOutUp(event) {\\n      var _this = this;\\n\\n      var eventType = event.type;\\n      var closeKeyCodes = [13, 32];\\n\\n      if (eventType === \'click\' || eventType === \'keydown\' && closeKeyCodes.indexOf(event.keyCode) >= 0) {\\n        this.$elements.el.style.maxHeight = \\"\\".concat(this.$elements.el.offsetHeight, \\"px\\");\\n        setTimeout(function () {\\n          _this.$elements.el.style.maxHeight = \'0px\';\\n        });\\n      }\\n    }\\n    /*\\n    This logic excludes element from keyboard navigation flow */\\n\\n  }, {\\n    key: \\"hideComponent\\",\\n    value: function hideComponent() {\\n      this.$elements.el.classList.add(\'alertribbon__base--hidden\');\\n    }\\n  }, {\\n    key: \\"addEventListeners\\",\\n    value: function addEventListeners() {\\n      this.$elements.closeButton.addEventListener(\'click\', this.slideComponentOutUp.bind(this));\\n      this.$elements.closeButton.addEventListener(\'keydown\', this.slideComponentOutUp.bind(this));\\n      this.$elements.el.addEventListener(\'transitionend\', this.hideComponent.bind(this));\\n    }\\n  }, {\\n    key: \\"init\\",\\n    value: function init() {\\n      this.setElements();\\n      this.addEventListeners();\\n    }\\n  }]);\\n\\n  return AlertRibbon;\\n}();\\n\\ndebugger;\\n\\nif (window.nc) {\\n  window.nc.loaderRegister({\\n    AlertRibbon: AlertRibbon\\n  });\\n  /*\\n  Location Finder workaround, since it doesn\'t use nc.loader for now (6.3 Release) */\\n} else {\\n  document.addEventListener(\'DOMContentLoaded\', function () {\\n    var $alertRibbon = document.querySelector(\'.alertribbon__base\');\\n\\n    if ($alertRibbon) {\\n      new AlertRibbon($alertRibbon).init();\\n    }\\n  });\\n}//# sourceURL=[module]\\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 5356 characters]\\n//# sourceURL=webpack-internal:///../../../xxx-fit-responsive/xxx-fit-responsive-package/src/main/jcr_root/apps/xxx/fit/responsive/par/alertribbon/clientlib/publish/alertribbon.publish.entry.js\\n");\n\n//# sourceURL=webpack:////Users/bohdan.afanasyev/Projects/xxx-internet-fit/xxx-fit-responsive/xxx-fit-responsive-package/src/main/jcr_root/apps/xxx/fit/responsive/par/alertribbon/clientlib/publish/alertribbon.publish.entry.js?'
            );

            /***/
        },
    },
    [
        [
            "../../../xxx-fit-responsive/xxx-fit-responsive-package/src/main/jcr_root/apps/xxx/fit/responsive/par/alertribbon/clientlib/publish/alertribbon.publish.entry.js",
            "xxx-fit-design/xxx-fit-design-package/src/main/jcr_root/etc/designs/fit/includes/es6-main-publish/clientlib/publish/loader/runtime.publish.bundle.js",
            "xxx-fit-design/xxx-fit-design-package/src/main/jcr_root/etc/designs/fit/includes/es6-main-publish/clientlib/publish/vendors/vendors.corejs/vendors.corejs.bundle.js",
            "xxx-fit-design/xxx-fit-design-package/src/main/jcr_root/etc/designs/fit/includes/es6-main-publish/clientlib/publish/vendors/vendors.default/vendors.default.bundle.js",
        ],
    ],
]);

console.log(`Modules loaded`, webpackJsonp)```

答:
If you are using webpack for building an application it runs your's entries code when it will be loaded.

For example for the simple "Hello World" code, you will get something like this

!function(arrayOfEntries) {
  var t = {};

  function runEntryByIndex(n) {
    if (t[n]) return t[n].exports;
    var o = t[n] = {i: n, l: !1, exports: {}};
    return arrayOfEntries[n].call(o.exports, o, o.exports, runEntryByIndex), o.l = !0, o.exports;
  }

  runEntryByIndex.m = arrayOfEntries, runEntryByIndex.c = t, runEntryByIndex.d = function(e, t, n) {
    runEntryByIndex.o(e, t) || Object.defineProperty(e, t, {
      enumerable: !0,
      get: n
    });
  }, runEntryByIndex.runEntryByIndex = function(e) {'undefined' != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, {value: 'Module'}), Object.defineProperty(e, '__esModule', {value: !0});}, runEntryByIndex.t = function(e, t) {
    if (1 & t && (e = runEntryByIndex(e)), 8 & t) return e;
    if (4 & t && 'object' == typeof e && e && e.__esModule) return e;
    var n = Object.create(null);
    if (runEntryByIndex.r(n), Object.defineProperty(n, 'default', {
      enumerable: !0,
      value: e
    }), 2 & t && 'string' != typeof e) for (var o in e) runEntryByIndex.d(n, o, function(t) {return e[t];}.bind(null, o));
    return n;
  }, runEntryByIndex.n = function(e) {
    var t = e && e.__esModule ? function() {return e.default;} : function() {return e;};
    return runEntryByIndex.d(t, 'a', t), t;
  }, runEntryByIndex.o = function(e, t) {return Object.prototype.hasOwnProperty.call(e, t);}, runEntryByIndex.p = '', runEntryByIndex(runEntryByIndex.s = 0);
}([function(e, t) {console.log('Hello World!');}]);
```

<p>If you follow the statements above you will see that it will run the function which contains <code>console.log("Hello World")</code>.</p>

<p>If we are talking about dependency's code then it'll be executed when you require it. For example, we have two files "A.js" and "B.js". "A.js" depends on "B.js"</p>

<p>A.js</p>

<pre class="lang-js prettyprint-override"><code>console.log("A");
require("./B.js");
</code>```

B.js

```<code>console.log("B");
</code>```

If you build this application where A.js would be entry point than you will see output

```<code>"A"
"B"
</code>```

Lets' change the order of statements inside "A.js"

A.js

require("./B.js")
console.log("A");
```

<p>In this case, the output will be</p>

```"B"
"A"
```

Webpack also allows you to build library code. You can read about it here https://webpack.js.org/guides/author-libraries/

If you are curious about what is "webpackJsonp" you can read about it here
https://webpack.js.org/configuration/output/#outputjsonpfunction

Body:
If you are using webpack for building an application it runs your's entries code when it will be loaded.

For example for the simple "Hello World" code, you will get something like this

!function(arrayOfEntries) {
  var t = {};

  function runEntryByIndex(n) {
    if (t[n]) return t[n].exports;
    var o = t[n] = {i: n, l: !1, exports: {}};
    return arrayOfEntries[n].call(o.exports, o, o.exports, runEntryByIndex), o.l = !0, o.exports;
  }

  runEntryByIndex.m = arrayOfEntries, runEntryByIndex.c = t, runEntryByIndex.d = function(e, t, n) {
    runEntryByIndex.o(e, t) || Object.defineProperty(e, t, {
      enumerable: !0,
      get: n
    });
  }, runEntryByIndex.runEntryByIndex = function(e) {'undefined' != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, {value: 'Module'}), Object.defineProperty(e, '__esModule', {value: !0});}, runEntryByIndex.t = function(e, t) {
    if (1 & t && (e = runEntryByIndex(e)), 8 & t) return e;
    if (4 & t && 'object' == typeof e && e && e.__esModule) return e;
    var n = Object.create(null);
    if (runEntryByIndex.r(n), Object.defineProperty(n, 'default', {
      enumerable: !0,
      value: e
    }), 2 & t && 'string' != typeof e) for (var o in e) runEntryByIndex.d(n, o, function(t) {return e[t];}.bind(null, o));
    return n;
  }, runEntryByIndex.n = function(e) {
    var t = e && e.__esModule ? function() {return e.default;} : function() {return e;};
    return runEntryByIndex.d(t, 'a', t), t;
  }, runEntryByIndex.o = function(e, t) {return Object.prototype.hasOwnProperty.call(e, t);}, runEntryByIndex.p = '', runEntryByIndex(runEntryByIndex.s = 0);
}([function(e, t) {console.log('Hello World!');}]);

If you follow the statements above you will see that it will run the function which contains console.log("Hello World").

If we are talking about dependency's code then it'll be executed when you require it. For example, we have two files "A.js" and "B.js". "A.js" depends on "B.js"

A.js

console.log("A");
require("./B.js");

B.js

console.log("B");

If you build this application where A.js would be entry point than you will see output

"A"
"B"

Lets' change the order of statements inside "A.js"

A.js

require("./B.js")
console.log("A");

In this case, the output will be

"B"
"A"

Webpack also allows you to build library code. You can read about it here https://webpack.js.org/guides/author-libraries/

If you are curious about what is "webpackJsonp" you can read about it here
https://webpack.js.org/configuration/output/#outputjsonpfunction


来源: stackexchange

问:
BitmapFactory: Unable to decode stream: java.io.FileNotFoundException:open failed: EACCES (Permission denied) on Android Q
I granted permissions but BitmapFactory.decodeFile() returns this error:

```<code>E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/IMG_20200130_165131.jpg: open failed: EACCES (Permission denied)
</code>```

I want to take the last image from the gallery and save it to another file. I tested it on the Android P test device it was running on. But it returns this error in android emulator with android version Q (API level 29). What's wrong with that?

These are my code snippets:

```<code>writeStoragePermissionGranted();

BitmapFactory.Options options = null;
Bitmap bm = null;

String[] projection = new String[]{
            MediaStore.Images.ImageColumns._ID,
            MediaStore.Images.ImageColumns.DATA,
            MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
            MediaStore.Images.ImageColumns.DATE_TAKEN,
            MediaStore.Images.ImageColumns.MIME_TYPE,
            MediaStore.Images.ImageColumns.DISPLAY_NAME,
    };

    final Cursor cursor = this.getContentResolver()
            .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
                    null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
      if (cursor.moveToFirst()) {
        final ImageView imageView = (ImageView) findViewById(R.id.pictureView);
        String imageLocation = cursor.getString(1);
        File imageFile = new File(imageLocation);

        if (imageFile.exists()) {
            options = new BitmapFactory.Options();
            options.inSampleSize = 2;

            try {
                    bm = BitmapFactory.decodeFile(imageLocation, options);
            } catch(Exception e) {
                    e.printStackTrace();
            }
        }

        imageView.setImageBitmap(bm);

        try {
            saveImage(bm,"NAME" );
        } catch (IOException e) {
                e.printStackTrace();
        }
    }
</code>```

writeStoragePermissionGranted() function:

```<code> public void writeStoragePermissionGranted() {
       if (Build.VERSION.SDK_INT >= 23) {
           if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                   == PackageManager.PERMISSION_GRANTED) {
            startPeriodicRequest();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Constants.REQUEST_CODE_WRITE_EXTERNAL_STORAGE_PERMISSION);
        }
    } else {
        return;
    }
}
</code>```

and manifest permissions:

```<code> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

I know there are many question about that. But no one worked on the android emulator version Q. On the other hand, this code works on android pie (API level 28)

答: Adding android:requestLegacyExternalStorage="true" to the manifest's application block could actually solve the issue!

ContentLicense: CC BY-SA 4.0

Body:
I granted permissions but BitmapFactory.decodeFile() returns this error:

E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/IMG_20200130_165131.jpg: open failed: EACCES (Permission denied)

I want to take the last image from the gallery and save it to another file. I tested it on the Android P test device it was running on. But it returns this error in android emulator with android version Q (API level 29). What's wrong with that?

These are my code snippets:

writeStoragePermissionGranted();

BitmapFactory.Options options = null;
Bitmap bm = null;

String[] projection = new String[]{
            MediaStore.Images.ImageColumns._ID,
            MediaStore.Images.ImageColumns.DATA,
            MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
            MediaStore.Images.ImageColumns.DATE_TAKEN,
            MediaStore.Images.ImageColumns.MIME_TYPE,
            MediaStore.Images.ImageColumns.DISPLAY_NAME,
    };

    final Cursor cursor = this.getContentResolver()
            .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
                    null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
      if (cursor.moveToFirst()) {
        final ImageView imageView = (ImageView) findViewById(R.id.pictureView);
        String imageLocation = cursor.getString(1);
        File imageFile = new File(imageLocation);

        if (imageFile.exists()) {
            options = new BitmapFactory.Options();
            options.inSampleSize = 2;

            try {
                    bm = BitmapFactory.decodeFile(imageLocation, options);
            } catch(Exception e) {
                    e.printStackTrace();
            }
        }

        imageView.setImageBitmap(bm);

        try {
            saveImage(bm,"NAME" );
        } catch (IOException e) {
                e.printStackTrace();
        }
    }

writeStoragePermissionGranted() function:

 public void writeStoragePermissionGranted() {
       if (Build.VERSION.SDK_INT >= 23) {
           if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                   == PackageManager.PERMISSION_GRANTED) {
            startPeriodicRequest();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Constants.REQUEST_CODE_WRITE_EXTERNAL_STORAGE_PERMISSION);
        }
    } else {
        return;
    }
}

and manifest permissions:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

I know there are many question about that. But no one worked on the android emulator version Q. On the other hand, this code works on android pie (API level 28)


问:
viewForSupplementaryElementOfKind is not getting called
i have declared collection view like below

```<code>lazy var collectionView:UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize  = UICollectionViewFlowLayout.automaticSize
        layout.minimumLineSpacing = 52
        layout.sectionInset = UIEdgeInsets(top: 25, left: 0, bottom: 30, right: 0)
        var collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(XXXCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        collectionView.register(XXXHeaderViewCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier)
        collectionView.delegate = self
        return collectionView
    }()
</code>```

and implemented below delegates , control comes only to referenceSizeForHeaderInSection method but not to viewForSupplementaryElementOfKind

```<code>public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath)
        return headerView
    }

public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        let size = CGSize(width: self.collectionView.bounds.width, height: 200)
        return size
    }
</code>```

Any help is really appreciated.

答:
I was facing the same issue and then figured out a solution.

try to add @objc (collectionView:viewForSupplementaryElementOfKind:atIndexPath:) just above your func collectionView(viewForSupplementaryElementOfKind:at:).

It seems that the obj-C and Swift have different names.
Look at the last param, on obj-C we have atIndexPath while on Swift we have just at.

Was that helpful?

Body:
i have declared collection view like below

lazy var collectionView:UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize  = UICollectionViewFlowLayout.automaticSize
        layout.minimumLineSpacing = 52
        layout.sectionInset = UIEdgeInsets(top: 25, left: 0, bottom: 30, right: 0)
        var collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(XXXCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        collectionView.register(XXXHeaderViewCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier)
        collectionView.delegate = self
        return collectionView
    }()

and implemented below delegates , control comes only to referenceSizeForHeaderInSection method but not to viewForSupplementaryElementOfKind

public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath)
        return headerView
    }

public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        let size = CGSize(width: self.collectionView.bounds.width, height: 200)
        return size
    }

Any help is really appreciated.


问:
WebStorm disable JS debugger content highlight
Title may be confusing because I don't know how to explain that in words. When we use JavaScript debugger in WebStorm and edit and html file, it colorizes the block when the cursor on it.

It is really confuses me specially when I change something about the design. Is there any way to turn of this feature completely. I'm digging the app, searching at google but nothing found yet

答:
Please try disabling Highlight current element in browser on caret change checkbox in Settings | Build, Execution, Deployment | Debugger | Live Edit

See https://www.jetbrains.com/help/webstorm/2020.1/live-editing.html


问:
How can I fix the error: can't mix packed and unpacked types?
I am trying to build a 4:1 multiplexer using 2:1 multiplexers that I've built. I am getting a few errors whenever I try typing the command vsim mux4_test.

Array connection type 'reg$[1:0]' is incompatible with 'wire[1:0]' for
  port (sel): can't mix packed and unpacked types.

Port size (1) does not match connection size (32) for port 'Z'. The
  port definition is at: NOT.sv(3).

Illegal output or inout port connection for port 'Z'.

And here's my attempt in doing it:

For 2:1 mux:

```<code>module mux2 (
    input logic d0,          // Data input 0
    input logic d1,          // Data input 1
    input logic sel,         // Select input
    output logic z           // Output
);

logic w1,w2,w3,w4,w5,w6,w7,w8;
NOT # (.Tpdlh(10), .Tpdhl(8)) g1(.Z(w1) , .A(d0));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g4(.Z(w5), .A(w1), .B(w4));
NOT # (.Tpdlh(10), .Tpdhl(8)) g2(.Z(w2) , .A(d1));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g5(.Z(w6), .A(w2), .B(w3));
NOT # (.Tpdlh(10), .Tpdhl(8)) g3(.Z(w3) , .A(w4));
NOT # (.Tpdlh(10), .Tpdhl(8)) g6(.Z(w7) , .A(w5));
NOT # (.Tpdlh(10), .Tpdhl(8)) g7(.Z(w8) , .A(w6));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g8(.Z(z) , .A(w7), .B(w8));

endmodule
</code>```

for 4:1 mux:

```<code>module mux4 (
    input logic d0,          // Data input 0
    input logic d1,          // Data input 1
    input logic d2,          // Data input 2
    input logic d3,          // Data input 3
    input logic [1:0] sel,   // Select input
    output logic z           // Output
);

logic w1,w2;

mux2 mux2a(
.d0(d0),
.d1(d1),
.sel(sel[0]),
.z(w1)
);

mux2 mux2b(
.d2(d0),
.d3(d1),
.sel(sel[0]),
.z(w2)
);

mux2 mux2c(
.d0(w1),
.d1(w2),
.sel(sel[1]),
.z(z)
);

endmodule
</code>```

and finally my testbench

```<code>module mux4_test;
logic d0,d1,d2,d3,sel[1:0], z;

mux4 m4a(
.d0(d0),
.d1(d1),
.d2(d2),
.d3(d3),
.sel(sel),
.z(z)
);

initial begin
d0=1'b0;
d1=1'b0;
d2=1'b0;
d3=1'b0;
sel[0]=1'b0;
sel[1]=1'b0;

#20
d0=1'b1;
d1=1'b0;
d2=1'b0;
d3=1'b0;
sel[0]=1'b0;
sel[1]=1'b0;

end

endmodule
</code>```

答:
This is a copy of the Answer I posted on electronics.stackexchange.com.  I saw the Question there before I realized it was also posted here.

The 1st compile error I get is related to the sel port.

In module mux4_test, change:

```<code>logic d0,d1,d2,d3,sel[1:0], z;
</code>```

to:

```<code>logic d0,d1,d2,d3, z;
logic [1:0] sel;
</code>```

sel[1:0] (unpacked) is not the same as [1:0] sel (packed).

The 2nd compile error I get is related to the mux2b instance.  Change:

```<code>mux2 mux2b(
.d2(d0),
.d3(d1),
.sel(sel[0]),
.z(w2)
);
</code>```

to:

```<code>mux2 mux2b(
.d0(d2),
.d1(d3),
.sel(sel[0]),
.z(w2)
);
</code>```

mux2 does not have d2 and d3 ports.

Your code compiles cleanly for me.  I do not see errors related to the Z port; here is the code on edaplayground

We concluded that the Z error was a bug in the user's simulator.  The OP updated to the latest version of ModelSim, and now all errors are gone.

Body:
I am trying to build a 4:1 multiplexer using 2:1 multiplexers that I've built. I am getting a few errors whenever I try typing the command vsim mux4_test.

Array connection type 'reg$[1:0]' is incompatible with 'wire[1:0]' for
  port (sel): can't mix packed and unpacked types.

Port size (1) does not match connection size (32) for port 'Z'. The
  port definition is at: NOT.sv(3).

Illegal output or inout port connection for port 'Z'.

And here's my attempt in doing it:

For 2:1 mux:

module mux2 (
    input logic d0,          // Data input 0
    input logic d1,          // Data input 1
    input logic sel,         // Select input
    output logic z           // Output
);

logic w1,w2,w3,w4,w5,w6,w7,w8;
NOT # (.Tpdlh(10), .Tpdhl(8)) g1(.Z(w1) , .A(d0));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g4(.Z(w5), .A(w1), .B(w4));
NOT # (.Tpdlh(10), .Tpdhl(8)) g2(.Z(w2) , .A(d1));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g5(.Z(w6), .A(w2), .B(w3));
NOT # (.Tpdlh(10), .Tpdhl(8)) g3(.Z(w3) , .A(w4));
NOT # (.Tpdlh(10), .Tpdhl(8)) g6(.Z(w7) , .A(w5));
NOT # (.Tpdlh(10), .Tpdhl(8)) g7(.Z(w8) , .A(w6));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g8(.Z(z) , .A(w7), .B(w8));

endmodule

for 4:1 mux:

module mux4 (
    input logic d0,          // Data input 0
    input logic d1,          // Data input 1
    input logic d2,          // Data input 2
    input logic d3,          // Data input 3
    input logic [1:0] sel,   // Select input
    output logic z           // Output
);

logic w1,w2;

mux2 mux2a(
.d0(d0),
.d1(d1),
.sel(sel[0]),
.z(w1)
);

mux2 mux2b(
.d2(d0),
.d3(d1),
.sel(sel[0]),
.z(w2)
);

mux2 mux2c(
.d0(w1),
.d1(w2),
.sel(sel[1]),
.z(z)
);

endmodule

and finally my testbench

module mux4_test;
logic d0,d1,d2,d3,sel[1:0], z;

mux4 m4a(
.d0(d0),
.d1(d1),
.d2(d2),
.d3(d3),
.sel(sel),
.z(z)
);

initial begin
d0=1'b0;
d1=1'b0;
d2=1'b0;
d3=1'b0;
sel[0]=1'b0;
sel[1]=1'b0;

#20
d0=1'b1;
d1=1'b0;
d2=1'b0;
d3=1'b0;
sel[0]=1'b0;
sel[1]=1'b0;

end

endmodule

Body:
This is a copy of the Answer I posted on electronics.stackexchange.com.  I saw the Question there before I realized it was also posted here.

The 1st compile error I get is related to the sel port.

In module mux4_test, change:

logic d0,d1,d2,d3,sel[1:0], z;

to:

logic d0,d1,d2,d3, z;
logic [1:0] sel;

sel[1:0] (unpacked) is not the same as [1:0] sel (packed).

The 2nd compile error I get is related to the mux2b instance.  Change:

mux2 mux2b(
.d2(d0),
.d3(d1),
.sel(sel[0]),
.z(w2)
);

to:

mux2 mux2b(
.d0(d2),
.d1(d3),
.sel(sel[0]),
.z(w2)
);

mux2 does not have d2 and d3 ports.

Your code compiles cleanly for me.  I do not see errors related to the Z port; here is the code on edaplayground

We concluded that the Z error was a bug in the user's simulator.  The OP updated to the latest version of ModelSim, and now all errors are gone.


问:
How to save Google Maps V3 distance result to MySQL database?
(and sorry in advance for this being such a basic question at its core)

I have a MySQL database with location info, and a PHP script that can put a new, user-submitted location into the database. I want to then (immediately) find the distances between the newly-submitted location and a subset of the existing locations in the database using a Google Maps directions request, and store these distances in the database.

I can select the locations subset via PHP and use JavaScript to fetch the distance data with Google Maps, but how do I then transfer these JavaScript variables to my database? -What's the best way to save a group of JavaScript variables as separate entries in a MySQL database?

Thanks for your help!

Carl

答:
I have a project where I encountered the same problem. If it is between two points A and B, you can refer to
  http://vikku.info/programming/google-maps-v3/draggable-directions/saving-draggable-directions-saving-waypoints-google-directions-google-maps-v3.htm

If the number of points

```<code>editroutes = JSON.parse(editroutes);
origin = editroutes.ag.origin;
destination = editroutes.ag.destination;
var ag = editroutes.ag.waypoints;

for(i=0;i<ag.length;i++){
    if(typeof ag[i].location == 'object'){
        waypoints.push({location:new google.maps.LatLng(ag[i].location.Ia, ag[i].location.Ja),stopover:ag[i].stopover});
    }else if(typeof ag[i].location == 'string'){
        waypoints.push({location:ag[i].location,stopover:ag[i].stopover});
    }
}

avoidHighways =  editroutes.ag.avoidHighways;
avoidTolls = editroutes.ag.avoidTolls;
var request = {
       origin: origin,
       destination: destination,
       waypoints: waypoints,
       travelMode: google.maps.DirectionsTravelMode.DRIVING,
       optimizeWaypoints: false,
       avoidHighways: avoidHighways,
       avoidTolls: avoidTolls
};
directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
    }
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a project where I encountered the same problem. If it is between two points A and B, you can refer to
  http://vikku.info/programming/google-maps-v3/draggable-directions/saving-draggable-directions-saving-waypoints-google-directions-google-maps-v3.htm

If the number of points

editroutes = JSON.parse(editroutes);
origin = editroutes.ag.origin;
destination = editroutes.ag.destination;
var ag = editroutes.ag.waypoints;

for(i=0;i<ag.length;i++){
    if(typeof ag[i].location == 'object'){
        waypoints.push({location:new google.maps.LatLng(ag[i].location.Ia, ag[i].location.Ja),stopover:ag[i].stopover});
    }else if(typeof ag[i].location == 'string'){
        waypoints.push({location:ag[i].location,stopover:ag[i].stopover});
    }
}

avoidHighways =  editroutes.ag.avoidHighways;
avoidTolls = editroutes.ag.avoidTolls;
var request = {
       origin: origin,
       destination: destination,
       waypoints: waypoints,
       travelMode: google.maps.DirectionsTravelMode.DRIVING,
       optimizeWaypoints: false,
       avoidHighways: avoidHighways,
       avoidTolls: avoidTolls
};
directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
    }
});

ContentLicense: CC BY-SA 3.0


问:
How can remove console.log in the production build of a React application created using create-react-app?
How can remove console.log in the production build of a React application created using create-react-app CRA?</p>

答:
The simple way is to create a new file in root named logger.js

In logger.js

```<code>var logger = function logger(...messages){
    if(process.env.NODE_ENV === 'development'){
        console.log(messages);
    }
}
exports.logger = logger;
</code>```

Now import this logger.js file to your components. For example my component file is demo.jsx

```<code>import React from 'react';
var logger = require('../logger.js').logger;

class Demo extends React.Component{
    constructor(props){
    }

    render(){
        return(
            <p>Hello i am demo component</p>
        );
    }

    componentDidMount(){
        logger('I am printing only in developmet')
    }
}
export default Demo;
</code>```

Body:
The simple way is to create a new file in root named logger.js

In logger.js

var logger = function logger(...messages){
    if(process.env.NODE_ENV === 'development'){
        console.log(messages);
    }
}
exports.logger = logger;

Now import this logger.js file to your components. For example my component file is demo.jsx

import React from 'react';
var logger = require('../logger.js').logger;

class Demo extends React.Component{
    constructor(props){
    }

    render(){
        return(
            <p>Hello i am demo component</p>
        );
    }

    componentDidMount(){
        logger('I am printing only in developmet')
    }
}
export default Demo;


问:
"Moving" a value from one row to another in MySQL
I'm pretty new to MySQL and I really don't know how to google this. Sorry if it's a dumb question.

I have a table that contains unique value pairs as the primary key (userID, somethingID) and a value. For example,

```<code>userID     somethingID    value
892        10             1
892        9              1
892        0              10
</code>```

If (userID, somethingID = 0) has a value greater than 0, the user should be able to decrement that value and increment the value of any other row. In the example above, userID 892 has a value of 10 in somethingID 0, so if he wants, he could take 1 from that value and move it to (892, 9):

```<code>userID     somethingID    value
892        10             1
892        9              2
892        0              9
</code>```

I need to add a check that ensures the value row of (userID, 0) is greater than zero before doing so. The value of (userID, 0) cannot be negative.

Any help would be appreciated.

Thank you all so much!

答:
It sounds like you need to write a procedure for this job, because you need to update multiple lines.

```<code>DELIMITER $$
CREATE PROCEDURE UpdateValue(
    IN  _userID INT,
    IN  _somethingID  INT
)
BEGIN
    UPDATE tableName SET value = value +1 where userID=_userID and somethingID= _somethingID  and userID in (
          select userID from tableName where userID=_userID and somethingID= 0 and value >0
        );
    UPDATE tableName SET value = value -1 where userID=_userID and somethingID= 0  and userID in (
          select userID from tableName where userID=_userID and somethingID= 0 and value >0
        );
END$$
DELIMITER ;
</code>```

You can call this procedure with desired User Id and and Something ID values.

```<code>CALL UpdateValue(892,9);
</code>```

If you need additional information about modified lines then you can add an OUT variable to procedure and return desired values. I hope this helps for you as an starting point for further searches.

Body:
I'm pretty new to MySQL and I really don't know how to google this. Sorry if it's a dumb question.

I have a table that contains unique value pairs as the primary key (userID, somethingID) and a value. For example,

userID     somethingID    value
892        10             1
892        9              1
892        0              10

If (userID, somethingID = 0) has a value greater than 0, the user should be able to decrement that value and increment the value of any other row. In the example above, userID 892 has a value of 10 in somethingID 0, so if he wants, he could take 1 from that value and move it to (892, 9):

userID     somethingID    value
892        10             1
892        9              2
892        0              9

I need to add a check that ensures the value row of (userID, 0) is greater than zero before doing so. The value of (userID, 0) cannot be negative.

Any help would be appreciated.

Thank you all so much!

Body:
It sounds like you need to write a procedure for this job, because you need to update multiple lines.

DELIMITER $$
CREATE PROCEDURE UpdateValue(
    IN  _userID INT,
    IN  _somethingID  INT
)
BEGIN
    UPDATE tableName SET value = value +1 where userID=_userID and somethingID= _somethingID  and userID in (
          select userID from tableName where userID=_userID and somethingID= 0 and value >0
        );
    UPDATE tableName SET value = value -1 where userID=_userID and somethingID= 0  and userID in (
          select userID from tableName where userID=_userID and somethingID= 0 and value >0
        );
END$$
DELIMITER ;

You can call this procedure with desired User Id and and Something ID values.

CALL UpdateValue(892,9);

If you need additional information about modified lines then you can add an OUT variable to procedure and return desired values. I hope this helps for you as an starting point for further searches.


问:
Adding a response header in an ExceptionFilterAttribute in ASP .Net Core
I'm trying to add a header to responses from a .Net core Web API when an exception occurs.

I'm using an ExceptionFilterAttribute...

```<code>public class ExceptionFilter : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {
        context.HttpContext.Response.Headers.Add("CorrelationId", "12345");
        base.OnException(context);
    }
}
</code>```

For some reason the header is not sent to the client. I'm guessing this is something to do with responses already being formed at this point so they can't be changed?

I've got a custom middleware that adds a correlation id to the request context and then outputs it into the response headers. This doesn't fire when an exception occurs though so I need another way of doing it hence trying to use the filter.

What should I change to get this to work?

答:
Try this,</p>

```<code>  public class ExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            var correlationId = "12345";

            // DO OTHER STUFF

            context.HttpContext.Response.OnStarting(() =>
            {
                context.HttpContext.Response.Headers.Add("CorrelationId", correlationId);
                return Task.CompletedTask;
            });
        }
    }
</code>```

Body:
I'm trying to add a header to responses from a .Net core Web API when an exception occurs.

I'm using an ExceptionFilterAttribute...

public class ExceptionFilter : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {
        context.HttpContext.Response.Headers.Add("CorrelationId", "12345");
        base.OnException(context);
    }
}

For some reason the header is not sent to the client. I'm guessing this is something to do with responses already being formed at this point so they can't be changed?

I've got a custom middleware that adds a correlation id to the request context and then outputs it into the response headers. This doesn't fire when an exception occurs though so I need another way of doing it hence trying to use the filter.

What should I change to get this to work?

Body:
Try this,

  public class ExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            var correlationId = "12345";

            // DO OTHER STUFF

            context.HttpContext.Response.OnStarting(() =>
            {
                context.HttpContext.Response.Headers.Add("CorrelationId", correlationId);
                return Task.CompletedTask;
            });
        }
    }


问:
how to add multiple attachment using thunderbird commandline?
I am stuck at this problem and not really aware of the syntax. How do I attach multiple not one?

This is for single attachment: thunderbird -compose attachment=/home/jj/test.docx

But I want to do something like this:
thunderbird -compose attachment=/home/jj/test.docx&/home/jj/test1.docx

thanks!

答:
By using the command

```<code> thunderbird -compose "attachment='/home/jj/first.txt,/home/jj/second.txt'"
</code>```

under Linux both files are attached. I think it should work for all operating system but I did not test it there.

Body:
By using the command

 thunderbird -compose "attachment='/home/jj/first.txt,/home/jj/second.txt'"

under Linux both files are attached. I think it should work for all operating system but I did not test it there.


问:
x.ToString() is not supported by the entity framework!
Entity framework doesn't recognize my ToString method that converts the route object to specifix string:

```<code>public IEnumerable<Route> GetRoutes(string prefix, string searchPattern, string code)
{
    return Routes.
        Where(x => code == null || x.Code == code).
        Where(x => searchPattern == null || x.ToString().Contains(searchPattern)).
        Where(x => prefix == null || x.ToString().StartsWith(prefix));
}
</code>```

Here is my Route entity:

```<code> public class Route : IDataEntity, ISoftDeletable
    {
        public virtual long Id { get; set; }
        public virtual string Code { get; set; }
        public virtual bool IsDeleted { get; set; }
        public virtual Guid CompanyId { get; set; }
        public virtual IList<LocationInRoute> Locations { get; set; }

        public override string ToString()
        {
            StringBuilder str = new StringBuilder();
            foreach (LocationInRoute loc in Locations)
            {
                if (str.Length > 0)
                {
                    str.Append(" > ");
                }
                str.Append(loc.ToString());
            }
            return str.ToString();
        }
    }
</code>```

All the x.ToString() throws an exception of not supported in linq to entities..
Any workaround?

答:
Entity framework doesn't recognize my ToString method that converts the route object to specifix string.

That's right.  Entity Framework can't convert the methods you write in c# into sql.

Entity Framework converts expressions to sql.  Sometimes those expressions represent calls to methods (such as Queryable.Where) and Entity Framework knows about those specific .net framework methods and how to translate them into sql.

How do you expect the database to new up a StringBuilder?

PS:  this or'ing of criteria in the query is a terrible way to go.  You shouldn't construct one query to rule them all.  Instead, conditionally construct the query:

```<code>IQueryable<Route> query = Routes

if (code != null)
{
  query = query.Where(x => x.Code == code)
}
if (searchPattern != null)
{
  query = query.Where(x => x.Locations.Any(loc => loc.Name.Contains(searchPattern)))
}
if (prefix != null)
{
  query = query.Where(x => x.Locations.First().Name.StartsWith(prefix));
}
</code>```

Body:
Entity framework doesn't recognize my ToString method that converts the route object to specifix string:

public IEnumerable<Route> GetRoutes(string prefix, string searchPattern, string code)
{
    return Routes.
        Where(x => code == null || x.Code == code).
        Where(x => searchPattern == null || x.ToString().Contains(searchPattern)).
        Where(x => prefix == null || x.ToString().StartsWith(prefix));
}

Here is my Route entity:

 public class Route : IDataEntity, ISoftDeletable
    {
        public virtual long Id { get; set; }
        public virtual string Code { get; set; }
        public virtual bool IsDeleted { get; set; }
        public virtual Guid CompanyId { get; set; }
        public virtual IList<LocationInRoute> Locations { get; set; }

        public override string ToString()
        {
            StringBuilder str = new StringBuilder();
            foreach (LocationInRoute loc in Locations)
            {
                if (str.Length > 0)
                {
                    str.Append(" > ");
                }
                str.Append(loc.ToString());
            }
            return str.ToString();
        }
    }

All the x.ToString() throws an exception of not supported in linq to entities..
Any workaround?

Body:
Entity framework doesn't recognize my ToString method that converts the route object to specifix string.

That's right.  Entity Framework can't convert the methods you write in c# into sql.

Entity Framework converts expressions to sql.  Sometimes those expressions represent calls to methods (such as Queryable.Where) and Entity Framework knows about those specific .net framework methods and how to translate them into sql.

How do you expect the database to new up a StringBuilder?

PS:  this or'ing of criteria in the query is a terrible way to go.  You shouldn't construct one query to rule them all.  Instead, conditionally construct the query:

IQueryable<Route> query = Routes

if (code != null)
{
  query = query.Where(x => x.Code == code)
}
if (searchPattern != null)
{
  query = query.Where(x => x.Locations.Any(loc => loc.Name.Contains(searchPattern)))
}
if (prefix != null)
{
  query = query.Where(x => x.Locations.First().Name.StartsWith(prefix));
}


问:
Copy input when click
I want to copy input when I click it, but I want make it like variable for use the same function for copy other input.

function copyToClipboard(here) {
  var textBox = document.getElementById(here);
  textBox.select();
  document.execCommand("copy");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" class="form-control" name="myvalue" id="myvalue" value="YEAH" readonly />
<button class="btn btn-primary btn-block" onclick="copyToClipboard(myvalue);">Copy myvalue</button></code>```

答:
You missed all the basic javascript fundamentals, you need to just change your javascript function.

Read some basic javascript properly

   function copyToClipboard(here) {
       var textBox = here;
       textBox.select();
       document.execCommand("copy");
   }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">

    <title>Document</title>
</head>
<body>
        <input type="text" class="form-control"  name="myvalue"  id="myvalue" value="YEAH" readonly  />
        <button class="btn btn-primary btn-block" onclick="copyToClipboard(myvalue);">Copy myvalue</button>

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

Title: Copy input when click

Body:
I want to copy input when I click it, but I want make it like variable for use the same function for copy other input.

function copyToClipboard(here) {
  var textBox = document.getElementById(here);
  textBox.select();
  document.execCommand("copy");
}

<input type="text" class="form-control" name="myvalue" id="myvalue" value="YEAH" readonly />
<button class="btn btn-primary btn-block" onclick="copyToClipboard(myvalue);">Copy myvalue</button>

Body:
You missed all the basic javascript fundamentals, you need to just change your javascript function.

Read some basic javascript properly

   function copyToClipboard(here) {
       var textBox = here;
       textBox.select();
       document.execCommand("copy");
   }

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">

    <title>Document</title>
</head>
<body>
        <input type="text" class="form-control"  name="myvalue"  id="myvalue" value="YEAH" readonly  />
        <button class="btn btn-primary btn-block" onclick="copyToClipboard(myvalue);">Copy myvalue</button>

</body>
</html>


问:
Meson: how to make find_library() works with an unusual path?
For my Meson project I have a dependency that is in an "unusual" place:

```<code>/opt/MyDependence/lib/libmyLib.so
/opt/MyDependence/include/myLib.hpp
</code>```

My meson file is:

```<code>project('Test', ['cpp'])

cpp = meson.get_compiler('cpp')
myLib_dep = cpp.find_library('myLib', required: true)
</code>```

Obviously Meson cannot find the library

```<code>Meson.build:5:0: ERROR: C++ library 'myLib' not found
</code>```

The problem is that I do not know the "canonical" way to add extra search paths so that Meson can found my lib. Any idea?

update: please note that even if I use:

```<code>meson --libdir=/opt/MyDepedence/lib build
</code>```

I get this error message:

```<code>meson.build:1:0: ERROR: The value of the 'libdir' option is '/opt/MyDepedence/lib' which must be a subdir of the prefix '/usr/local'.
Note that if you pass a relative path, it is assumed to be a subdir of prefix.
</code>```

答:
find_library now has an optional argument dirs (since 0.53.0) that indicates an extra list of absolute paths where to look for program names.

```<code>cpp = meson.get_compiler('cpp')
myLib_dep = cpp.find_library('myLib', dirs: '/opt/MyDepedence/lib', required: true)
</code>```

Body:
For my Meson project I have a dependency that is in an "unusual" place:

/opt/MyDependence/lib/libmyLib.so
/opt/MyDependence/include/myLib.hpp

My meson file is:

project('Test', ['cpp'])

cpp = meson.get_compiler('cpp')
myLib_dep = cpp.find_library('myLib', required: true)

Obviously Meson cannot find the library

Meson.build:5:0: ERROR: C++ library 'myLib' not found

The problem is that I do not know the "canonical" way to add extra search paths so that Meson can found my lib. Any idea?

update: please note that even if I use:

meson --libdir=/opt/MyDepedence/lib build

I get this error message:

meson.build:1:0: ERROR: The value of the 'libdir' option is '/opt/MyDepedence/lib' which must be a subdir of the prefix '/usr/local'.
Note that if you pass a relative path, it is assumed to be a subdir of prefix.

Body:
find_library now has an optional argument dirs (since 0.53.0) that indicates an extra list of absolute paths where to look for program names.

cpp = meson.get_compiler('cpp')
myLib_dep = cpp.find_library('myLib', dirs: '/opt/MyDepedence/lib', required: true)


问:
Trying to setup react but npm start command giving me ENOENT error

npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\Work\React_App\package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Work\React_App\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

C:\Work\React_App>npm -v
6.14.5

C:\Work\React_App>node -v
v12.16.1
```

答:
Ok it looks like NPM is using your .gitignore as a base for the .npmignore file, and thus ignores /lib. If you add a blank .npmignore file into the root of your application, everything should work.

[edit] - more info on this behaviour here: https://docs.npmjs.com/misc/developers#keeping-files-out-of-your-package


问:
STM32F303VCT6 external interrupt with PA0 button won't toggle LED
I want to use a button connected to PA0 as an external interrupt to toggle LED on PE14 on button press. However calling the configure_PA0 function doesn't seem to work.

I did a simple blinking instruction in while loop to test and it turns out when I call configure_PA0 the LED stays ON all the time.

Without calling it, the LED will blink just fine so I think it must be something wrong with this function.

#include "stm32f30x.h"

void delay(volatile uint32_t count){
    while(count > 0 )
        count--;
}

void init_LED(){ //init led on PE14
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOE, ENABLE);
        GPIO_InitTypeDef GPIO_InitStructure;
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
        GPIO_Init(GPIOE,&GPIO_InitStructure);
}
void configure_PA0(void) {

    GPIO_InitTypeDef GPIO_InitStruct;
    EXTI_InitTypeDef EXTI_InitStruct;
    NVIC_InitTypeDef NVIC_InitStruct;

    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
//PA0 as button init
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0;
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStruct);

//EXTI init
    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA, EXTI_PinSource0);
    EXTI_InitStruct.EXTI_Line = EXTI_Line0;
    EXTI_InitStruct.EXTI_LineCmd = ENABLE;
    EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt;
    EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Rising;
    EXTI_Init(&EXTI_InitStruct);

//NVIC init
    NVIC_InitStruct.NVIC_IRQChannel = EXTI0_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0x00;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0x00;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);
}

void toggle_PE14(){
    if(GPIO_ReadOutputDataBit(GPIOE,GPIO_Pin_14) == 0)
        GPIO_SetBits(GPIOE,GPIO_Pin_14);
    else
        GPIO_ResetBits(GPIOE,GPIO_Pin_14);
}

//handle pa0 interrupt
void EXTI0_IRQHandler(void) {
    if(EXTI_GetITStatus(EXTI_Line0) != RESET){
        toggle_PE14();

        EXTI_ClearITPendingBit(EXTI_Line0);
    }
}

int main(void) {

    init_LED();
    configure_PA0();

    while (1) {
        delay(400);
    }

    return 0;
}
```

UPDATE
I fixed it by putting handler definition into extern "C" { .. } brackets. Apparently you have to do that if you code in C++.

答:
UPDATE ...

First, thanks for letting other readers know!
Let me explain the causal relationship of these findings:

... I fixed it by putting handler definition into extern "C" { /* .. */ }
  brackets.
  Apparently you have to do that if you code in C++.

When programming in C++ (i.e., for those language features that are both valid in C and C++, when using a C++ compiler to build the program) there is a difference between C++ symbols and C symbols in the object code used by the linker.
In a nutshell, this is done because C++ identifiers must be extended by some type information in order to support polymorphism.
Details are explained
here.

Any C++ function which is defined without extern C qualifiers will get an extended ("mangled") symbol.
This also applies to "ambiguous" functions fed into the C++ compiler like in the present case.

Any extern C function (and any function translated by a C compiler, if one mixes compilers) will turn into a linker symbol with an unmangled name (usually only extended by some underscores, depending on the toolchain used).

The point is: Assembler functions behave mostly like C functions - function symbols referenced/defined in assembler code will be passed to the linker just as they are.
Usually (and in the present example), this is also the case for the definition of the STM32 interrupt vector table
(both following code snippets are taken from startup_stm32l476xx.s):

```<code>g_pfnVectors:
    .word   _estack
    .word   Reset_Handler
    .word   NMI_Handler
    .word   HardFault_Handler
    .word   MemManage_Handler
    .word   BusFault_Handler
    .word   UsageFault_Handler
    .word   0
    /*...*/
    .word   PendSV_Handler
    .word   SysTick_Handler
    /*...*/
    .word   EXTI0_IRQHandler
    .word   EXTI1_IRQHandler
    /*...*/
</code>```

and for the weak function definition linking to the DefaultHandler in default STM32CubeF3 / STM32CubeMX code

```<code>/*******************************************************************************
 *
 * Provide weak aliases for each Exception handler to the Default_Handler.
 * As they are weak aliases, any function with the same name will override
 * this definition.
 *
 *******************************************************************************/

.weak   NMI_Handler
.thumb_set NMI_Handler,Default_Handler

/*...*/

.weak   EXTI0_IRQHandler
.thumb_set EXTI0_IRQHandler,Default_Handler

.weak   EXTI1_IRQHandler
.thumb_set EXTI1_IRQHandler,Default_Handler

/*...*/
</code>```

This means that the linker found

a reference to C symbol EXTI0_IRQHandler in the vector table,

a (weak but unique) definition of C symbol EXTI0_IRQHandler

a (non-weak but mismatching) definition of a mangled C++ symbol based on EXTI0_IRQHandler.

It matched (1.) with (2.) and discarded (3.) for not being referenced, so the first interrupt produced at the external pin threw the MCU into the endless loop DefaultHandler and the LED stopped blinking.

Body:
I want to use a button connected to PA0 as an external interrupt to toggle LED on PE14 on button press. However calling the configure_PA0 function doesn't seem to work.

I did a simple blinking instruction in while loop to test and it turns out when I call configure_PA0 the LED stays ON all the time.

Without calling it, the LED will blink just fine so I think it must be something wrong with this function.

#include "stm32f30x.h"

void delay(volatile uint32_t count){
    while(count > 0 )
        count--;
}

void init_LED(){ //init led on PE14
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOE, ENABLE);
        GPIO_InitTypeDef GPIO_InitStructure;
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
        GPIO_Init(GPIOE,&GPIO_InitStructure);
}
void configure_PA0(void) {

    GPIO_InitTypeDef GPIO_InitStruct;
    EXTI_InitTypeDef EXTI_InitStruct;
    NVIC_InitTypeDef NVIC_InitStruct;

    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
//PA0 as button init
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0;
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStruct);

//EXTI init
    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA, EXTI_PinSource0);
    EXTI_InitStruct.EXTI_Line = EXTI_Line0;
    EXTI_InitStruct.EXTI_LineCmd = ENABLE;
    EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt;
    EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Rising;
    EXTI_Init(&EXTI_InitStruct);

//NVIC init
    NVIC_InitStruct.NVIC_IRQChannel = EXTI0_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0x00;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0x00;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);
}

void toggle_PE14(){
    if(GPIO_ReadOutputDataBit(GPIOE,GPIO_Pin_14) == 0)
        GPIO_SetBits(GPIOE,GPIO_Pin_14);
    else
        GPIO_ResetBits(GPIOE,GPIO_Pin_14);
}

//handle pa0 interrupt
void EXTI0_IRQHandler(void) {
    if(EXTI_GetITStatus(EXTI_Line0) != RESET){
        toggle_PE14();

        EXTI_ClearITPendingBit(EXTI_Line0);
    }
}

int main(void) {

    init_LED();
    configure_PA0();

    while (1) {
        delay(400);
    }

    return 0;
}

UPDATE
I fixed it by putting handler definition into extern "C" { .. } brackets. Apparently you have to do that if you code in C++.

Body:
UPDATE ...

First, thanks for letting other readers know!
Let me explain the causal relationship of these findings:

... I fixed it by putting handler definition into extern "C" { /* .. */ }
  brackets.
  Apparently you have to do that if you code in C++.

When programming in C++ (i.e., for those language features that are both valid in C and C++, when using a C++ compiler to build the program) there is a difference between C++ symbols and C symbols in the object code used by the linker.
In a nutshell, this is done because C++ identifiers must be extended by some type information in order to support polymorphism.
Details are explained
here.

Any C++ function which is defined without extern C qualifiers will get an extended ("mangled") symbol.
This also applies to "ambiguous" functions fed into the C++ compiler like in the present case.

Any extern C function (and any function translated by a C compiler, if one mixes compilers) will turn into a linker symbol with an unmangled name (usually only extended by some underscores, depending on the toolchain used).

The point is: Assembler functions behave mostly like C functions - function symbols referenced/defined in assembler code will be passed to the linker just as they are.
Usually (and in the present example), this is also the case for the definition of the STM32 interrupt vector table
(both following code snippets are taken from startup_stm32l476xx.s):

g_pfnVectors:
    .word   _estack
    .word   Reset_Handler
    .word   NMI_Handler
    .word   HardFault_Handler
    .word   MemManage_Handler
    .word   BusFault_Handler
    .word   UsageFault_Handler
    .word   0
    /*...*/
    .word   PendSV_Handler
    .word   SysTick_Handler
    /*...*/
    .word   EXTI0_IRQHandler
    .word   EXTI1_IRQHandler
    /*...*/

and for the weak function definition linking to the DefaultHandler in default STM32CubeF3 / STM32CubeMX code

/*******************************************************************************
 *
 * Provide weak aliases for each Exception handler to the Default_Handler.
 * As they are weak aliases, any function with the same name will override
 * this definition.
 *
 *******************************************************************************/

.weak   NMI_Handler
.thumb_set NMI_Handler,Default_Handler

/*...*/

.weak   EXTI0_IRQHandler
.thumb_set EXTI0_IRQHandler,Default_Handler

.weak   EXTI1_IRQHandler
.thumb_set EXTI1_IRQHandler,Default_Handler

/*...*/

This means that the linker found

a reference to C symbol EXTI0_IRQHandler in the vector table,

a (weak but unique) definition of C symbol EXTI0_IRQHandler

a (non-weak but mismatching) definition of a mangled C++ symbol based on EXTI0_IRQHandler.

It matched (1.) with (2.) and discarded (3.) for not being referenced, so the first interrupt produced at the external pin threw the MCU into the endless loop DefaultHandler and the LED stopped blinking.


问:
border-radius circle isn't sliding to the middle of the screen
I am unable to get the top circle to move to the middle, the bottom 3 circles are fine, just needed to adjust the text and the placement of the icons centred in the circles. And at the same time, it would adjust to any screen size from tablet/mobile/laptop, I've been trying to edit it in the navigation/container with top/right % but it won't do a thing, How can I resolve this?

.container1 {
    max-width: 1000px;
    width: 100%;

}
.circle1 p {
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle2 p{
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle3 p {
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.navigation  {
    position:relative;
    border: 2px solid rgb(211,211,211);
    width: 300px;
    border-radius: 100%;
    height: 300px;
    background: white;
}
.navigation ul {
    margin: 0;
    padding: 0;
    text-align: center;
    list-style-type: none;
}

.navigation li {
    font-weight: 100;
    letter-spacing: 2px;
    font-size: 35px;
    font-family: 'Roboto', sans-serif;
}

.circle1{
    margin: 0 auto;
    position: relative;
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);

}
.circle2{
    margin: 0 auto;
    position: relative;
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.circle3{
    margin: 0 auto;
    position: relative;
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.border-circle li{
    list-style-type: none;
    text-decoration: none;
}
.border-circle{
    min-width: 1349px;
    width: 100%;
    top: 70%;
    display: flex;
}

.fa-10x{
    opacity: 0.3;
    font-size:7em !important;
    position: relative;
    text-decoration: none;
    color: inherit;
}

.fa-9x{
    position: relative;
    font-size:7em !important;
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

.fa-8x{
    position: relative;
    font-size:7em !important;
    transform: translate(10rem, 10rem);
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

a {
    color: inherit;
}

.circle {
  display: flex;
  justify-content: center;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <jsp:include page="../head.html" />

     <body style="height: 130vh;">

        <!-- navigation bar -->
        <div class="container1">
            <nav class="navigation">
                <ul>
                    <li style="font-size:80px">Circle</li>
                    <li>in</li>
                </ul>
            </nav>
        </div>

        <div class="border-circle">
            <div class="circle1 circle">
                 <li><span class="fa fa-gamepad fa-9x"></span></li>
                <p> Circle1</p>
            </div>

            <div class="circle2 circle">
                 <li><span class= " fa fa-thumbs-up fa-10x"></span></li>
                <p> Circle2 </p>
            </div>

            <div class="circle3 circle">
                <li><span class="fa fa-gift fa-8x"></span></li>
                <p> Circle3 </p>
            </div>

        </div>

        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

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

答:
I try to add a flexbox. maybe it will help you

.container1 {
    max-width: 1000px;
    width: 100%;

}
.circle1 p {
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle2 p{
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle3 p {
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.navigation  {
    position:relative;
    border: 2px solid rgb(211,211,211);
    width: 300px;
    border-radius: 100%;
    height: 300px;
    background: white;
}
.navigation ul {
    margin: 0;
    padding: 0;
    text-align: center;
    list-style-type: none;
    display:flex;
    align-items:center;
    justify-content:center;
    flex-direction:column;
    height:100%;
}

.navigation li {
    font-weight: 100;
    letter-spacing: 2px;
    font-size: 35px;
    font-family: 'Roboto', sans-serif;
}

.circle1{
    margin: 0 auto;
    position: relative;
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);

}
.circle2{
    margin: 0 auto;
    position: relative;
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.circle3{
    margin: 0 auto;
    position: relative;
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.border-circle li{
    list-style-type: none;
    text-decoration: none;
}
.border-circle{
    min-width: 1349px;
    width: 100%;
    top: 70%;
    display: flex;
}

.fa-10x{
    opacity: 0.3;
    font-size:7em !important;
    position: relative;
    text-decoration: none;
    color: inherit;
}

.fa-9x{
    position: relative;
    font-size:7em !important;
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

.fa-8x{
    position: relative;
    font-size:7em !important;
    transform: translate(10rem, 10rem);
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

a {
    color: inherit;
}

.circle {
  display: flex;
  justify-content: center;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <jsp:include page="../head.html" />

     <body style="height: 130vh;">

        <!-- navigation bar -->
        <div class="container1">
            <nav class="navigation">
                <ul>
                    <li style="font-size:80px">Circle</li>
                    <li>in</li>
                </ul>
            </nav>
        </div>

        <div class="border-circle">
            <div class="circle1 circle">
                 <li><span class="fa fa-gamepad fa-9x"></span></li>
                <p> Circle1</p>
            </div>

            <div class="circle2 circle">
                 <li><span class= " fa fa-thumbs-up fa-10x"></span></li>
                <p> Circle2 </p>
            </div>

            <div class="circle3 circle">
                <li><span class="fa fa-gift fa-8x"></span></li>
                <p> Circle3 </p>
            </div>

        </div>

        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

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

Body:
I am unable to get the top circle to move to the middle, the bottom 3 circles are fine, just needed to adjust the text and the placement of the icons centred in the circles. And at the same time, it would adjust to any screen size from tablet/mobile/laptop, I've been trying to edit it in the navigation/container with top/right % but it won't do a thing, How can I resolve this?

.container1 {
    max-width: 1000px;
    width: 100%;

}
.circle1 p {
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle2 p{
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle3 p {
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.navigation  {
    position:relative;
    border: 2px solid rgb(211,211,211);
    width: 300px;
    border-radius: 100%;
    height: 300px;
    background: white;
}
.navigation ul {
    margin: 0;
    padding: 0;
    text-align: center;
    list-style-type: none;
}

.navigation li {
    font-weight: 100;
    letter-spacing: 2px;
    font-size: 35px;
    font-family: 'Roboto', sans-serif;
}

.circle1{
    margin: 0 auto;
    position: relative;
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);

}
.circle2{
    margin: 0 auto;
    position: relative;
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.circle3{
    margin: 0 auto;
    position: relative;
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.border-circle li{
    list-style-type: none;
    text-decoration: none;
}
.border-circle{
    min-width: 1349px;
    width: 100%;
    top: 70%;
    display: flex;
}

.fa-10x{
    opacity: 0.3;
    font-size:7em !important;
    position: relative;
    text-decoration: none;
    color: inherit;
}

.fa-9x{
    position: relative;
    font-size:7em !important;
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

.fa-8x{
    position: relative;
    font-size:7em !important;
    transform: translate(10rem, 10rem);
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

a {
    color: inherit;
}

.circle {
  display: flex;
  justify-content: center;
  align-items: center;
}

<!DOCTYPE html>

    <jsp:include page="../head.html" />

Circle

in

 Circle1

 Circle2

 Circle3

Body:
I try to add a flexbox. maybe it will help you

.container1 {
    max-width: 1000px;
    width: 100%;

}
.circle1 p {
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle2 p{
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle3 p {
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.navigation  {
    position:relative;
    border: 2px solid rgb(211,211,211);
    width: 300px;
    border-radius: 100%;
    height: 300px;
    background: white;
}
.navigation ul {
    margin: 0;
    padding: 0;
    text-align: center;
    list-style-type: none;
    display:flex;
    align-items:center;
    justify-content:center;
    flex-direction:column;
    height:100%;
}

.navigation li {
    font-weight: 100;
    letter-spacing: 2px;
    font-size: 35px;
    font-family: 'Roboto', sans-serif;
}

.circle1{
    margin: 0 auto;
    position: relative;
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);

}
.circle2{
    margin: 0 auto;
    position: relative;
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.circle3{
    margin: 0 auto;
    position: relative;
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.border-circle li{
    list-style-type: none;
    text-decoration: none;
}
.border-circle{
    min-width: 1349px;
    width: 100%;
    top: 70%;
    display: flex;
}

.fa-10x{
    opacity: 0.3;
    font-size:7em !important;
    position: relative;
    text-decoration: none;
    color: inherit;
}

.fa-9x{
    position: relative;
    font-size:7em !important;
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

.fa-8x{
    position: relative;
    font-size:7em !important;
    transform: translate(10rem, 10rem);
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

a {
    color: inherit;
}

.circle {
  display: flex;
  justify-content: center;
  align-items: center;
}

<!DOCTYPE html>
<html>
    <jsp:include page="../head.html" />

     <body style="height: 130vh;">

        <!-- navigation bar -->
        <div class="container1">
            <nav class="navigation">
                <ul>
                    <li style="font-size:80px">Circle</li>
                    <li>in</li>
                </ul>
            </nav>
        </div>

        <div class="border-circle">
            <div class="circle1 circle">
                <a href="#"> <li><span class="fa fa-gamepad fa-9x"></span></li> </a>
                <p> Circle1</p>
            </div>

            <div class="circle2 circle">
                <a href="#"> <li><span class= " fa fa-thumbs-up fa-10x"></span></li></a>
                <p> Circle2 </p>
            </div>

            <div class="circle3 circle">
                <a href="#"><li><span class="fa fa-gift fa-8x"></span></li></a>
                <p> Circle3 </p>
            </div>

        </div>

        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

    </body>
</html>


问:
How can I set a tkinter window to open only for the first time user runs the program and never open again?
I have been designing a Voice Assistant app using Python and tkinter. I want the user to set the default directories in which to search for songs, movies etc. This has to happen only for the first time the user runs the program and never again until he wishes to change the directories later which he would be able to do with a settings button. Is there any way to create a tkinter window that would display only for the first time the user runs the program by default and never display again until the user wishes to do so?</p>

答:
You need to store some sort of artifact on the filesystem to answer the question "has this program run before?". For example, it could create a file named ~/.myprogramrc. Next, just check for the existence of that file, and open up the GUI if the file doesn't exist.

```<code>class App(tk.Tk):

    def __init__(self):
        rc_file = Path.home() / ".myapprc"
        if not rc_file.exists():
            # a side effect of this should create the file .myapprc
            # in the home directory.
            config = self.prompt_for_config(rc_file)
        else:
            config = self.read_config(rc_file)
</code>```

Body:
You need to store some sort of artifact on the filesystem to answer the question "has this program run before?". For example, it could create a file named ~/.myprogramrc. Next, just check for the existence of that file, and open up the GUI if the file doesn't exist.

class App(tk.Tk):

    def __init__(self):
        rc_file = Path.home() / ".myapprc"
        if not rc_file.exists():
            # a side effect of this should create the file .myapprc
            # in the home directory.
            config = self.prompt_for_config(rc_file)
        else:
            config = self.read_config(rc_file)


问:
flutter TextField sticky, cursor jumps back to it when I finish with other items
On my new Job screen I have an About TextFormField widget, if I put some text into this, then go onto to interact with other Widgets, such as getting the time the job starts, once I've finished with those widgets, the cursor jump back to the TextFormField, Flutter assumes the user has unfinished business.

How do I tell Flutter not to reactivate TestField widgets?  To keep the cursor invisible, and focus elsewhere?

I've tried googling for the answer, doubtless, it's there, I just don't have the vocabulary, but it led me to think it has something to do with focus.  I tried setting autofocus: false, but that wasn't it.

```<code>      Column(children: <Widget>[
       TextFormField(
        style: Theme.of(context).textTheme.bodyText2,
        decoration: InputDecoration(
          labelStyle: Theme.of(context).textTheme.bodyText2,
          //errorText: _showValidationError ? 'Invalid number entered' : null,
          labelText: 'Comprehensive job description',
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(0.0),
          ),
        ),
        autofocus: false,
        keyboardType: TextInputType.multiline,
        onSaved: (String description) =>
            this.widget.job.description = description.trim(),
      ),
      RaisedButton(
        onPressed: () => _selectDate(context, startDate),
        child: Text('Select start date'),
      ),
      // TODO only show for certain categories
      CheckboxListTile(
        secondary: Icon(Icons.calendar_today),
        title: Text('To be completed the same day?'),
        subtitle: Text(showEndDatePicker == true
            ? "Must be completed same day."
            : "Could be completed in a few days."),
        value: showEndDatePicker ?? false,
        onChanged: (bool value) {
          setState(() {
            showEndDatePicker = value;
          });
        },
      ),
  Visibility(
    visible: !showEndDatePicker ?? false,
    child: RaisedButton(
      onPressed: () => _selectDate(context, endDate),
      child: Text('Select end date'),
    ),
  ),
   ]
);
</code>```

If I type some stuff in the TextFormField, then click the raised button it summons a Date picker.  Perfect.  But when that is completed, the focus jumps back to the TextFormField, popping up the keyboard.  The user has likely finished with this field.

Having the cursor jump back a few Widgets and the keyboard popup inexplicably is bad UX, help!

答: I had a similar problem and solved it with UnfocusDisposition. Try following this example: unfocus method.</p>

Body:
On my new Job screen I have an About TextFormField widget, if I put some text into this, then go onto to interact with other Widgets, such as getting the time the job starts, once I've finished with those widgets, the cursor jump back to the TextFormField, Flutter assumes the user has unfinished business.

How do I tell Flutter not to reactivate TestField widgets?  To keep the cursor invisible, and focus elsewhere?

I've tried googling for the answer, doubtless, it's there, I just don't have the vocabulary, but it led me to think it has something to do with focus.  I tried setting autofocus: false, but that wasn't it.

      Column(children: <Widget>[
       TextFormField(
        style: Theme.of(context).textTheme.bodyText2,
        decoration: InputDecoration(
          labelStyle: Theme.of(context).textTheme.bodyText2,
          //errorText: _showValidationError ? 'Invalid number entered' : null,
          labelText: 'Comprehensive job description',
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(0.0),
          ),
        ),
        autofocus: false,
        keyboardType: TextInputType.multiline,
        onSaved: (String description) =>
            this.widget.job.description = description.trim(),
      ),
      RaisedButton(
        onPressed: () => _selectDate(context, startDate),
        child: Text('Select start date'),
      ),
      // TODO only show for certain categories
      CheckboxListTile(
        secondary: Icon(Icons.calendar_today),
        title: Text('To be completed the same day?'),
        subtitle: Text(showEndDatePicker == true
            ? "Must be completed same day."
            : "Could be completed in a few days."),
        value: showEndDatePicker ?? false,
        onChanged: (bool value) {
          setState(() {
            showEndDatePicker = value;
          });
        },
      ),
  Visibility(
    visible: !showEndDatePicker ?? false,
    child: RaisedButton(
      onPressed: () => _selectDate(context, endDate),
      child: Text('Select end date'),
    ),
  ),
   ]
);

If I type some stuff in the TextFormField, then click the raised button it summons a Date picker.  Perfect.  But when that is completed, the focus jumps back to the TextFormField, popping up the keyboard.  The user has likely finished with this field.

Having the cursor jump back a few Widgets and the keyboard popup inexplicably is bad UX, help!


问:
Redirecting/Rendering different component upon validation ionic react
I'm fairly new Ionic React and trying to create an App using Ionic framework. I have a use case where I would like to redirect to another page upon a button press and validation from a function.

Here is the component I am working with

```<code>import React, { useState } from 'react';
import {
    IonContent,
    IonHeader,
    IonPage,
    IonTitle,
    IonToolbar,
    IonInput,
    IonButton,
    IonRow,
    IonCol,
    useIonViewWillEnter,
    useIonViewWillLeave,
    IonLabel
} from '@ionic/react';

import './LogIn.css'
import MainMenu from "../MainMenu";

const LogIn: React.FC<{register?: boolean; onClose?: any}> = () => {

    const [email, setEmail] = useState<string>();
    const [password, setPassword] = useState<string>();

    function handleLoginButtonPress() {
        if (validateEmail() && password !== undefined && password.trim() !== "") {
            // Network call here to check if a valid user
            console.log("valid email")
            return <MainMenu/>
        }
    }
    function validateEmail () {
        if (email !== undefined && email.trim() !== "") {
            const regexp = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return regexp.test(email);
        }
        return false;
    }

    useIonViewWillEnter(() => {
        console.log("Entering LogIn");
    });

    useIonViewWillLeave(() => {
        console.log("Exiting LogIn");
    });

    return (
        <IonPage id="loginIonPage">
            <IonHeader>
                <IonToolbar color="primary" mode="md">
                    <IonTitle class="ion-text-center">Login or Register</IonTitle>
                </IonToolbar>
            </IonHeader>

            <IonContent id="loginPage">
                <div id="loginDialog">
                    <form>
                        <IonLabel>Email</IonLabel>
                        <IonRow>
                            <IonCol id="userName">
                                <IonInput
                                    name="email"
                                    value={email}
                                    onIonChange={e => setEmail(e.detail.value!)}
                                    clearInput
                                    type="email"
                                    placeholder="Email"
                                    class="input"
                                    padding-horizontal
                                    clear-input="true"
                                    required/>
                            </IonCol>
                        </IonRow>
                        <IonLabel>Password</IonLabel>
                        <IonRow>
                            <IonCol id="password">
                                <IonInput
                                    clearInput
                                    name="password"
                                    value={password}
                                    onIonChange={e => setPassword(e.detail.value!)}
                                    type="password"
                                    placeholder="Password"
                                    class="input"
                                    padding-horizontal
                                    clear-input="true"
                                    required/>
                            </IonCol>
                        </IonRow>
                    </form>
                </div>
                <div id="buttons">
                        <IonButton
                            onClick={handleLoginButtonPress}
                            type="submit"
                            strong={true}
                            expand="full"
                            style={{ margin: 20 }}>
                            Log in
                        </IonButton>
                        <IonButton
                            routerLink="/registerUser"
                            type="submit"
                            strong={true}
                            expand="full"
                            style={{ margin: 20 }}>
                            Register
                        </IonButton>
                </div>
            </IonContent>
        </IonPage>
    );
};

export default LogIn;
</code>```

How can I redirect to another page from the function handleLoginButtonPress which is invoked upon clicking on Login button. I tried reading through ionic doc but that did not help as it redirects whenever there is button click or click on an IonElement like IonLabel.

答:
Thanks, @MUHAMMAD ILYAS and it would have worked for me. But I managed to leverage the react state as below, I have added as an answer as I could not format the code there,

```<code>const ValidateUser : React.FC = () => {

    const [login, setLogin] = useState(false);

    function isUserLoggedIn() {
        return login;
    }

    return(
        <IonReactRouter>
            <IonRouterOutlet>
                <Route path="/" render={() => isUserLoggedIn()
                    ? <MainMenu/>
                    : <LogIn setUserLoggedIn={() => {setLogin(true)}}/>} exact={true}/>
            </IonRouterOutlet>
        </IonReactRouter>
    );
};

</code>```

```<code>const LogIn: React.FC<{setUserLoggedIn?: any}> = ({setUserLoggedIn}) => {
    .
    .
    function onLoginButtonPress() {
       setUserLoggedIn();
    }
}
</code>```

Thanks

Body:
I'm fairly new Ionic React and trying to create an App using Ionic framework. I have a use case where I would like to redirect to another page upon a button press and validation from a function.

Here is the component I am working with

import React, { useState } from 'react';
import {
    IonContent,
    IonHeader,
    IonPage,
    IonTitle,
    IonToolbar,
    IonInput,
    IonButton,
    IonRow,
    IonCol,
    useIonViewWillEnter,
    useIonViewWillLeave,
    IonLabel
} from '@ionic/react';

import './LogIn.css'
import MainMenu from "../MainMenu";

const LogIn: React.FC<{register?: boolean; onClose?: any}> = () => {

    const [email, setEmail] = useState<string>();
    const [password, setPassword] = useState<string>();

    function handleLoginButtonPress() {
        if (validateEmail() && password !== undefined && password.trim() !== "") {
            // Network call here to check if a valid user
            console.log("valid email")
            return <MainMenu/>
        }
    }
    function validateEmail () {
        if (email !== undefined && email.trim() !== "") {
            const regexp = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return regexp.test(email);
        }
        return false;
    }

    useIonViewWillEnter(() => {
        console.log("Entering LogIn");
    });

    useIonViewWillLeave(() => {
        console.log("Exiting LogIn");
    });

    return (
        <IonPage id="loginIonPage">
            <IonHeader>
                <IonToolbar color="primary" mode="md">
                    <IonTitle class="ion-text-center">Login or Register</IonTitle>
                </IonToolbar>
            </IonHeader>

            <IonContent id="loginPage">

                    <form>
                        <IonLabel>Email</IonLabel>
                        <IonRow>
                            <IonCol id="userName">
                                <IonInput
                                    name="email"
                                    value={email}
                                    onIonChange={e => setEmail(e.detail.value!)}
                                    clearInput
                                    type="email"
                                    placeholder="Email"
                                    class="input"
                                    padding-horizontal
                                    clear-input="true"
                                    required/>
                            </IonCol>
                        </IonRow>
                        <IonLabel>Password</IonLabel>
                        <IonRow>
                            <IonCol id="password">
                                <IonInput
                                    clearInput
                                    name="password"
                                    value={password}
                                    onIonChange={e => setPassword(e.detail.value!)}
                                    type="password"
                                    placeholder="Password"
                                    class="input"
                                    padding-horizontal
                                    clear-input="true"
                                    required/>
                            </IonCol>
                        </IonRow>
                    </form>

                        <IonButton
                            onClick={handleLoginButtonPress}
                            type="submit"
                            strong={true}
                            expand="full"
                            style={{ margin: 20 }}>
                            Log in
                        </IonButton>
                        <IonButton
                            routerLink="/registerUser"
                            type="submit"
                            strong={true}
                            expand="full"
                            style={{ margin: 20 }}>
                            Register
                        </IonButton>

            </IonContent>
        </IonPage>
    );
};

export default LogIn;

How can I redirect to another page from the function handleLoginButtonPress which is invoked upon clicking on Login button. I tried reading through ionic doc but that did not help as it redirects whenever there is button click or click on an IonElement like IonLabel.

Body:
Thanks, @MUHAMMAD ILYAS and it would have worked for me. But I managed to leverage the react state as below, I have added as an answer as I could not format the code there,

const ValidateUser : React.FC = () => {

    const [login, setLogin] = useState(false);

    function isUserLoggedIn() {
        return login;
    }

    return(
        <IonReactRouter>
            <IonRouterOutlet>
                <Route path="/" render={() => isUserLoggedIn()
                    ? <MainMenu/>
                    : <LogIn setUserLoggedIn={() => {setLogin(true)}}/>} exact={true}/>
            </IonRouterOutlet>
        </IonReactRouter>
    );
};

const LogIn: React.FC<{setUserLoggedIn?: any}> = ({setUserLoggedIn}) => {
    .
    .
    function onLoginButtonPress() {
       setUserLoggedIn();
    }
}

Thanks