问:
.NET Core in Docker, expired SSL CA certificate
I have a Docker image, based on the microsoft/dotnet:2.1-runtime image (Linux).

However, since 1/6, the .NET code (and other code) in the container is not able to connect to certain sites that use a COMODO CA certificate.

E.g. the following fails inside the container, due to the expired certificate:
curl https://code.jquery.com

Result:
curl: (60) SSL certificate problem: certificate has expired

I have tried calling update-ca-certificates inside the container, but that does not change anything.

My desktop browsers somehow have updated the CA certs themselves, but the docker have not.

I don't really need curl to work (that was just a test to show the issue), but I do need my own .NET code to work (which causes similar error). Any ideas how I can force the container to update the CA certs, or make this work somehow? I obviously do not want to skip certificate validation!

答:
Not sure if this is the answer. After you update the certificate, updating the docker container image itself. the pseudo commands look like below:

```<code>$ docker run -p <port>:<port> <image> bash --name <image name>
root@xxxx <ca-cert folder>: update-ca-certificates
</code>```

Don't exit out of the container.
On the host machine:

```<code>$ docker commit <image name>
</code>```

docker commit will create a new image from the running container.

Theory

Probably you are running update-ca-certificates after you start a container instance.
using some steps shared in these answers

This will probably work one time if your docker run commands look something like below

$ docker run -p 8000:80 <image name> bash

and inside the bash, you updated the certificate.
This will only run for the lifetime of this container. When this container dies and a new one is created it's created with the same old image (with expired cert).

Body:
Not sure if this is the answer. After you update the certificate, updating the docker container image itself. the pseudo commands look like below:

$ docker run -p <port>:<port> <image> bash --name <image name>
root@xxxx <ca-cert folder>: update-ca-certificates

Don't exit out of the container.
On the host machine:

$ docker commit <image name>

docker commit will create a new image from the running container.

Theory

Probably you are running update-ca-certificates after you start a container instance.
using some steps shared in these answers

This will probably work one time if your docker run commands look something like below

$ docker run -p 8000:80 <image name> bash

and inside the bash, you updated the certificate.
This will only run for the lifetime of this container. When this container dies and a new one is created it's created with the same old image (with expired cert).


来源: stackexchange

问:
How to use Git credential store on WSL (Ubuntu on Windows)?
I've tried following these instructions: https://stackoverflow.com/a/40312117/21728 which basically do this:

```<code>sudo apt-get install libsecret-1-0 libsecret-1-dev
cd /usr/share/doc/git/contrib/credential/libsecret
sudo make
git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret
</code>```

But when I do any network operation, I get this error:

```<code>** (process:7902): CRITICAL **: could not connect to Secret Service: Cannot autolaunch D-Bus without X11 $DISPLAY
</code>```

That's logical I guess as there is indeed no X11 display.

How to make Git credentials caching work on Ubuntu on Windows (WSL)?

答:
I have just recently updated to WSL2 and in my case the following wasn't working:

"/mnt/c/Program\\ Files/Git/mingw64/libexec/git-core/git-credential-manager.exe"

What worked was the following:
git config --global credential.helper "/c/Program\\ Files/Git/mingw64/libexec/git-core/git-credential-manager.exe"

Until I've removed /mnt/ from the path I was getting a "not found" error.

From what I've investigated there's an issue with mounting windows drives in WSL2 after a clean Windows startup, more details here:
https://github.com/microsoft/WSL/issues/4122
And that was the most probable cause in my case.

Another reason for this can be a misconfiguration of root directory in /etc/wsl.conf

ContentLicense: CC BY-SA 3.0

Body:
I've tried following these instructions: https://stackoverflow.com/a/40312117/21728 which basically do this:

sudo apt-get install libsecret-1-0 libsecret-1-dev
cd /usr/share/doc/git/contrib/credential/libsecret
sudo make
git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret

But when I do any network operation, I get this error:

** (process:7902): CRITICAL **: could not connect to Secret Service: Cannot autolaunch D-Bus without X11 $DISPLAY

That's logical I guess as there is indeed no X11 display.

How to make Git credentials caching work on Ubuntu on Windows (WSL)?

ContentLicense: CC BY-SA 4.0


问:
How to make statistic of changes in column,that are string, grouped by other column
```<code>df = pd.DataFrame({
    'RB': [2335] * 4 +  [3567] * 4 + [1245] * 4,
    'time': months[:4] * 3,
    'value': ['good day'] * 2 + ['may be'] * 2 + ['what'] * 4 + ['sure'] * 3 + ['no']
})
</code>```

I would like to see how many RB made changes from good to maybe, from what to sure, sure to no, maybe to good etc.(all combinations)  Since there are a lot of combinations I would like to see if some are appearing more often. (Also maybe to good and good to maybe are two combination for example )

答:
Here's a solution, assuming 'months' in an integer: </p>

```<code>months = list(range(12))
df = pd.DataFrame({
    'RB': [2335] * 4 +  [3567] * 4 + [1245] * 4,
    'time': months[:4] * 3,
    'value': ['good day'] * 2 + ['may be'] * 2 + ['what'] * 4 + ['sure'] * 3 + ['no']
})

df = df.assign(next_val = df.groupby("RB").transform("shift", -1)["value"])
df["change"] = ((df.value != df.next_val) & df.next_val.notna()).map({False: 0, True:1})
df = df.groupby(["value", "next_val"]).sum()[["change"]]
df[df.change>0]
</code>```

<p>The result is: </p>

```<code>                   change
value    next_val
good day may be         1
sure     no             1
</code>```

Body:
df = pd.DataFrame({
    'RB': [2335] * 4 +  [3567] * 4 + [1245] * 4,
    'time': months[:4] * 3,
    'value': ['good day'] * 2 + ['may be'] * 2 + ['what'] * 4 + ['sure'] * 3 + ['no']
})

I would like to see how many RB made changes from good to maybe, from what to sure, sure to no, maybe to good etc.(all combinations)  Since there are a lot of combinations I would like to see if some are appearing more often. (Also maybe to good and good to maybe are two combination for example )

Body:
Here's a solution, assuming 'months' in an integer:

months = list(range(12))
df = pd.DataFrame({
    'RB': [2335] * 4 +  [3567] * 4 + [1245] * 4,
    'time': months[:4] * 3,
    'value': ['good day'] * 2 + ['may be'] * 2 + ['what'] * 4 + ['sure'] * 3 + ['no']
})

df = df.assign(next_val = df.groupby("RB").transform("shift", -1)["value"])
df["change"] = ((df.value != df.next_val) & df.next_val.notna()).map({False: 0, True:1})
df = df.groupby(["value", "next_val"]).sum()[["change"]]
df[df.change>0]

The result is:

                   change
value    next_val
good day may be         1
sure     no             1


问:
Spring JPA Save Method - Performance Issue
I have one performance problem in JPA save() method. I Have "CustomerHistory" Table it's like a log table I'm not even use this table data in my application. (I'm not perform any get query operations in the table). But If I save the "CustomerHistory" Model using JPA Save Method Means it's every time return the CustomerHistory Model After saving the data. So I need to know if it's play the big role in performance?</p>

```<code> public CustomerHistory saveCustomerHistoryLog(CustomerHistory  customerHistory ){
    return customerHistoryRepository.save(customerHistory );
}
</code>```

答:
If the CustomerHistory does not have any relationship to other entities , it should be okay.

But even if it has relationship to other entities , and if you are following the best practice that do not enable eager fetching when mapping the related entities , it should not affect the performance since they are lazy loaded and no unnecessary SQL will be triggered to load them if you do not access them.

Body:
I have one performance problem in JPA save() method. I Have "CustomerHistory" Table it's like a log table I'm not even use this table data in my application. (I'm not perform any get query operations in the table). But If I save the "CustomerHistory" Model using JPA Save Method Means it's every time return the CustomerHistory Model After saving the data. So I need to know if it's play the big role in performance?

 public CustomerHistory saveCustomerHistoryLog(CustomerHistory  customerHistory ){
    return customerHistoryRepository.save(customerHistory );
}


问:
Timeline Progress bar for AVPlayer
AVPlayer is fully customizable, unfortunately there are convenient methods in AVPlayer for showing the time line progress bar.

```<code>AVPlayer *player = [AVPlayer playerWithURL:URL];
AVPlayerLayer *playerLayer = [[AVPlayerLayer playerLayerWithPlayer:avPlayer] retain];[self.view.layer addSubLayer:playerLayer];
</code>```

I have an progress bar that indicates the how video has been played, and how much remained just as like MPMoviePlayer.

So how to get the timeline of video from AVPlayer and how to update the progress bar

Suggest me.

答:
I know it's an old question, but someone may find it useful. It's only Swift version:</p>

```<code> //set the timer, which will update your progress bar. You can use whatever time interval you want

 private func setupProgressTimer() {
    timer = Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true, block: { [weak self] (completion) in
        guard let self = self else { return }
        self.updateProgress()
    })
}

//update progression of video, based on it's own data

private func updateProgress() {
    guard let duration = player?.currentItem?.duration.seconds,
        let currentMoment = player?.currentItem?.currentTime().seconds else { return }

    progressBar.progress = Float(currentMoment / duration)
}
</code>```

Title: Timeline Progress bar for AVPlayer

Body:
AVPlayer is fully customizable, unfortunately there are convenient methods in AVPlayer for showing the time line progress bar.

AVPlayer *player = [AVPlayer playerWithURL:URL];
AVPlayerLayer *playerLayer = [[AVPlayerLayer playerLayerWithPlayer:avPlayer] retain];[self.view.layer addSubLayer:playerLayer];

I have an progress bar that indicates the how video has been played, and how much remained just as like MPMoviePlayer.

So how to get the timeline of video from AVPlayer and how to update the progress bar

Suggest me.

Body:
I know it's an old question, but someone may find it useful. It's only Swift version:

 //set the timer, which will update your progress bar. You can use whatever time interval you want

 private func setupProgressTimer() {
    timer = Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true, block: { [weak self] (completion) in
        guard let self = self else { return }
        self.updateProgress()
    })
}

//update progression of video, based on it's own data

private func updateProgress() {
    guard let duration = player?.currentItem?.duration.seconds,
        let currentMoment = player?.currentItem?.currentTime().seconds else { return }

    progressBar.progress = Float(currentMoment / duration)
}


问:
Pytest does not find pyYAML in Travis CI tests that have PyPI and conda package dependencies
I am trying to set up automatic testing for my Python package using Travis CI. My Python package depends on Iris as well as other packages such as PyYAML, numpy, etc. It also depends on a PyPI package (ScriptEngine). Now, I would like to set up a Travis CI environment using conda (to install Iris) and pip (to install the PyPI package as well as checking the requirements for PyYAML and numpy). I would then like to install my package using pip install ..

To test if this works, I have written one simple Pytest test that imports PyYAML.

I am currently trying to do this using this .travis.yml file:

language: python
python:
  - "3.6"
  - "3.7"
  - "3.8"
# command to install dependencies
install:
  - sudo apt-get update
  - wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh
  - bash miniconda.sh -b -p $HOME/miniconda
  - source "$HOME/miniconda/etc/profile.d/conda.sh"
  - hash -r
  - conda config --set always_yes yes --set changeps1 no
  - conda update -q conda
  # Useful for debugging any issues with conda
  - conda info -a
  - conda env create -f tests/test-environment.yml python=$TRAVIS_PYTHON_VERSION
  - conda activate test-environment
  - conda install pip
  - conda install -c conda-forge iris
  - pip install -r requirements.txt
  - pip install .
# command to run tests
script: pytest
```

<p>Note: This is the first time for me to really work with Travis CI. This script is a mixture of examples from the Conda docs as well as the Travis CI docs.</p>

<p>Pytest then fails to import PyYAML (although it gets installed because of the requirements.txt as well as the Iris dependencies):
Here is the confirmation from the logs that it got installed:</p>

```Requirement already satisfied: pyYAML>=5.1 in /home/travis/miniconda/envs/test-environment/lib/python3.8/site-packages (from ece-4-monitoring==0.1.0) (5.3.1)
```

<p>And this is the Error from Pytest:</p>

```$ pytest

============================= test session starts ==============================

platform linux -- Python 3.7.1, pytest-4.3.1, py-1.7.0, pluggy-0.8.0

rootdir: /home/travis/build/valentinaschueller/ece-4-monitoring, inifile:

collected 1 item / 1 errors

==================================== ERRORS ====================================

_________________ ERROR collecting tests/test_file_handling.py _________________

ImportError while importing test module '/home/travis/build/valentinaschueller/sciptengine-tasks-ecearth/tests/test_file_handling.py'.

Hint: make sure your test modules/packages have valid Python names.

Traceback:

tests/test_file_handling.py:3: in <module>

    import helpers.file_handling as file_handling

helpers/file_handling.py:1: in <module>

    import yaml

E   ModuleNotFoundError: No module named 'yaml'

!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!

=========================== 1 error in 0.12 seconds ============================

The command "pytest" exited with 2.
```

If I try this exact setup using a conda virtual environment locally on my computer, I do not get this problem. Why does this not work on the Travis CI virtual machine?

答:
As cel suggested in their comment: I could fix the problem by explicitly requiring pytest in the requirements.txt.

It is not necessary to activate test-environment in the script part. However, a very helpful tip was to use echo $(which pytest) && pytest instead of just pytest to check if pytest is installed at /home/travis/miniconda/envs/test-environment/bin/pytest.

Body:
I am trying to set up automatic testing for my Python package using Travis CI. My Python package depends on Iris as well as other packages such as PyYAML, numpy, etc. It also depends on a PyPI package (ScriptEngine). Now, I would like to set up a Travis CI environment using conda (to install Iris) and pip (to install the PyPI package as well as checking the requirements for PyYAML and numpy). I would then like to install my package using pip install ..

To test if this works, I have written one simple Pytest test that imports PyYAML.

I am currently trying to do this using this .travis.yml file:

language: python
python:
  - "3.6"
  - "3.7"
  - "3.8"
# command to install dependencies
install:
  - sudo apt-get update
  - wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh
  - bash miniconda.sh -b -p $HOME/miniconda
  - source "$HOME/miniconda/etc/profile.d/conda.sh"
  - hash -r
  - conda config --set always_yes yes --set changeps1 no
  - conda update -q conda
  # Useful for debugging any issues with conda
  - conda info -a
  - conda env create -f tests/test-environment.yml python=$TRAVIS_PYTHON_VERSION
  - conda activate test-environment
  - conda install pip
  - conda install -c conda-forge iris
  - pip install -r requirements.txt
  - pip install .
# command to run tests
script: pytest

Note: This is the first time for me to really work with Travis CI. This script is a mixture of examples from the Conda docs as well as the Travis CI docs.

Pytest then fails to import PyYAML (although it gets installed because of the requirements.txt as well as the Iris dependencies):
Here is the confirmation from the logs that it got installed:

Requirement already satisfied: pyYAML>=5.1 in /home/travis/miniconda/envs/test-environment/lib/python3.8/site-packages (from ece-4-monitoring==0.1.0) (5.3.1)

And this is the Error from Pytest:

$ pytest

============================= test session starts ==============================

platform linux -- Python 3.7.1, pytest-4.3.1, py-1.7.0, pluggy-0.8.0

rootdir: /home/travis/build/valentinaschueller/ece-4-monitoring, inifile:

collected 1 item / 1 errors

==================================== ERRORS ====================================

_________________ ERROR collecting tests/test_file_handling.py _________________

ImportError while importing test module '/home/travis/build/valentinaschueller/sciptengine-tasks-ecearth/tests/test_file_handling.py'.

Hint: make sure your test modules/packages have valid Python names.

Traceback:

tests/test_file_handling.py:3: in <module>

    import helpers.file_handling as file_handling

helpers/file_handling.py:1: in <module>

    import yaml

E   ModuleNotFoundError: No module named 'yaml'

!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!

=========================== 1 error in 0.12 seconds ============================

The command "pytest" exited with 2.

If I try this exact setup using a conda virtual environment locally on my computer, I do not get this problem. Why does this not work on the Travis CI virtual machine?


问:
fullcalendar failing jquery call
Please forgive my lack of Js/jquery knowledge - hopefully this will be a simple question to answer.  I think I must be missing a script or something somewhere

So when the calendar renders

```<code>Calendar.prototype.initialRender = function () {
   var _this = this;
   var el = this.el;
   el.addClass('fc');  !fails here

</code>```

The console tell me 'this' is the fullcalendar correctly

```<code>Calendar {loadingLevel: 0, ignoreUpdateViewSize: 0, freezeContentHeightDepth: 0, el: div#calendar, viewsByType: {…}, …}
constraints: Constraints {eventManager: EventManager, _calendar: Calendar}
currentDate: Moment {_isAMomentObject: true, _isUTC: true, _pf: {…}, _locale: Locale, _d: Tue Jun 02 2020 17:03:57 GMT+0100 (British Summer Time), …}
defaultAllDayEventDuration: Duration {_isValid: true, _milliseconds: 0, _days: 1, _months: 0, _data: {…}, …}
defaultTimedEventDuration: Duration {_isValid: true, _milliseconds: 7200000, _days: 0, _months: 0, _data: {…}, …}
el: div#calendar
eventManager: EventManager {calendar: Calendar, stickySource: ArrayEventSource, otherSources: Array(0), jQuery1124013653863441134595: {…}}
freezeContentHeightDepth: 0
ignoreUpdateViewSize: 0
loadingLevel: 0
localeData: Locale {_fullCalendar_weekCalc: "local"}
optionsManager: OptionsManager {_watchers: {…}, _props: {…}, _calendar: Calendar, overrides: {…}, dynamicOverrides: {…}, …}
viewSpecManager: ViewSpecManager {optionsManager: OptionsManager, _calendar: Calendar, viewSpecCache: {…}}
viewsByType: {}
__proto__: Object
</code>```

but shows 'el' is not a jquery object as needed in order for addClass to work

```<code>>el
div#calendar

</code>```

And trying to call addClass fails

```<code>el.addClass('fc')
VM14452:1 Uncaught TypeError: el.addClass is not a function
    at eval (eval at Calendar.initialRender (fullcalendar.self-e9ae1b2c551f2f852ffbb704ecc1e434ee9bbc2cda72ea67fa3631cdace57650.js?body=1:9501), <anonymous>:1:4)
    at Calendar.initialRender (fullcalendar.self-e9ae1b2c551f2f852ffbb704ecc1e434ee9bbc2cda72ea67fa3631cdace57650.js?body=1:9501)
    at Calendar.render (fullcalendar.self-e9ae1b2c551f2f852ffbb704ecc1e434ee9bbc2cda72ea67fa3631cdace57650.js?body=1:9490)
    at HTMLDocument.<anonymous> (calendar.self-38bc6bd2dda3534fb8abc461acd3125490aec51a3e037753ae5812dac1925814.js?body=1:4)
    at Object.t.dispatch (turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6)
    at r.notifyApplicationAfterPageLoad (turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6)
    at r.pageLoaded (turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6)
    at turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6

</code>```

Why isnt the el attribute a JQuery obect and why can it not call addClass.  If I do it manually it is fine

```<code>>$('div #calendar').addClass('fc')

jQuery.fn.init [div#calendar.fc, prevObject: jQuery.fn.init(1), context: document, selector: "div #calendar"]
</code>```

答:
It turns out the example on the full calendar page is wrong - I'm so impressed.

initialise globals

The example supplies a DOM element to FullCalendar when you need to supply a jQuery element

```<code>document.addEventListener('DOMContentLoaded', function() {
  var calendarEl = document.getElementById('calendar');
  -- **this needs to be calendarEl = $('#calendar')**

  var calendar = new FullCalendar.Calendar(calendarEl, {plugins: [ 'dayGrid' ]});

  calendar.render();
});
</code>```

Title: fullcalendar failing jquery call

Body:
Please forgive my lack of Js/jquery knowledge - hopefully this will be a simple question to answer.  I think I must be missing a script or something somewhere

So when the calendar renders

Calendar.prototype.initialRender = function () {
   var _this = this;
   var el = this.el;
   el.addClass('fc');  !fails here

The console tell me 'this' is the fullcalendar correctly

Calendar {loadingLevel: 0, ignoreUpdateViewSize: 0, freezeContentHeightDepth: 0, el: div#calendar, viewsByType: {…}, …}
constraints: Constraints {eventManager: EventManager, _calendar: Calendar}
currentDate: Moment {_isAMomentObject: true, _isUTC: true, _pf: {…}, _locale: Locale, _d: Tue Jun 02 2020 17:03:57 GMT+0100 (British Summer Time), …}
defaultAllDayEventDuration: Duration {_isValid: true, _milliseconds: 0, _days: 1, _months: 0, _data: {…}, …}
defaultTimedEventDuration: Duration {_isValid: true, _milliseconds: 7200000, _days: 0, _months: 0, _data: {…}, …}
el: div#calendar
eventManager: EventManager {calendar: Calendar, stickySource: ArrayEventSource, otherSources: Array(0), jQuery1124013653863441134595: {…}}
freezeContentHeightDepth: 0
ignoreUpdateViewSize: 0
loadingLevel: 0
localeData: Locale {_fullCalendar_weekCalc: "local"}
optionsManager: OptionsManager {_watchers: {…}, _props: {…}, _calendar: Calendar, overrides: {…}, dynamicOverrides: {…}, …}
viewSpecManager: ViewSpecManager {optionsManager: OptionsManager, _calendar: Calendar, viewSpecCache: {…}}
viewsByType: {}
__proto__: Object

but shows 'el' is not a jquery object as needed in order for addClass to work

>el
div#calendar

And trying to call addClass fails

el.addClass('fc')
VM14452:1 Uncaught TypeError: el.addClass is not a function
    at eval (eval at Calendar.initialRender (fullcalendar.self-e9ae1b2c551f2f852ffbb704ecc1e434ee9bbc2cda72ea67fa3631cdace57650.js?body=1:9501), <anonymous>:1:4)
    at Calendar.initialRender (fullcalendar.self-e9ae1b2c551f2f852ffbb704ecc1e434ee9bbc2cda72ea67fa3631cdace57650.js?body=1:9501)
    at Calendar.render (fullcalendar.self-e9ae1b2c551f2f852ffbb704ecc1e434ee9bbc2cda72ea67fa3631cdace57650.js?body=1:9490)
    at HTMLDocument.<anonymous> (calendar.self-38bc6bd2dda3534fb8abc461acd3125490aec51a3e037753ae5812dac1925814.js?body=1:4)
    at Object.t.dispatch (turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6)
    at r.notifyApplicationAfterPageLoad (turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6)
    at r.pageLoaded (turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6)
    at turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6

Why isnt the el attribute a JQuery obect and why can it not call addClass.  If I do it manually it is fine

>$('div #calendar').addClass('fc')

jQuery.fn.init [div#calendar.fc, prevObject: jQuery.fn.init(1), context: document, selector: "div #calendar"]

Body:
It turns out the example on the full calendar page is wrong - I'm so impressed.

initialise globals

The example supplies a DOM element to FullCalendar when you need to supply a jQuery element

document.addEventListener('DOMContentLoaded', function() {
  var calendarEl = document.getElementById('calendar');
  -- **this needs to be calendarEl = $('#calendar')**

  var calendar = new FullCalendar.Calendar(calendarEl, {plugins: [ 'dayGrid' ]});

  calendar.render();
});


问:
npm install hangs on loadIdealTree:loadAllDepsIntoIdealTree: sill install loadIdealTree
I have a Node.js application. When I try to run npm install it hangs with this:

```<code>loadIdealTree:loadAllDepsIntoIdealTree: sill install loadIdealTree
</code>```

npm install --verbose gives me a little extra info:

```<code>npm info it worked if it ends with ok
npm verb cli [ '/usr/local/bin/node',
npm verb cli   '/usr/local/bin/npm',
npm verb cli   'install',
npm verb cli   '--verbose',
npm verb cli   'aws-sdk-js' ]
npm info using npm@5.8.0
npm info using node@v8.9.2
npm verb npm-session ea38310110279de7
npm http fetch GET 404 https://registry.npmjs.org/aws-sdk-js 2211ms
npm verb stack Error: 404 Not Found: aws-sdk-js@latest
npm verb stack     at fetch.then.res (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/fetch.js:42:19)
npm verb stack     at tryCatcher (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
npm verb stack     at Promise._settlePromiseFromHandler (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:512:31)
npm verb stack     at Promise._settlePromise (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:569:18)
npm verb stack     at Promise._settlePromise0 (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:614:10)
npm verb stack     at Promise._settlePromises (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:693:18)
npm verb stack     at Async._drainQueue (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:133:16)
npm verb stack     at Async._drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:143:10)
npm verb stack     at Immediate.Async.drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:17:14)
npm verb stack     at runCallback (timers.js:789:20)
npm verb stack     at tryOnImmediate (timers.js:751:5)
npm verb stack     at processImmediate [as _immediateCallback] (timers.js:722:5)
npm verb cwd /Users/me/git/aws-sdk-js-perf
npm verb Darwin 17.5.0
npm verb argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "--verbose" "aws-sdk-js"
npm verb node v8.9.2
npm verb npm  v5.8.0
npm ERR! code E404
npm ERR! 404 Not Found: aws-sdk-js@latest
npm verb exit [ 1, true ]

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/me/.npm/_logs/2018-05-24T10_30_55_688Z-debug.log
</code>```

I came across instances where other people experienced this but the below seemed to resolve their issue. It doesn't fix mine:

```<code>npm set registry http://registry.npmjs.org/
</code>```

Does anybody know what might be wrong?

答:
I also faced the same issue. In my case git:// port was blocked and npm install took too long to time out. (longer than normal it waits before concluding that the process hung.)

A solution was to auto-rewrite all git:// URLs to https://:

Run the following command in your terminal

```<code>
git config --global url."https://".insteadOf git://

npm install

</code>```

Hope this helps!!

Body:
I have a Node.js application. When I try to run npm install it hangs with this:

loadIdealTree:loadAllDepsIntoIdealTree: sill install loadIdealTree

npm install --verbose gives me a little extra info:

npm info it worked if it ends with ok
npm verb cli [ '/usr/local/bin/node',
npm verb cli   '/usr/local/bin/npm',
npm verb cli   'install',
npm verb cli   '--verbose',
npm verb cli   'aws-sdk-js' ]
npm info using npm@5.8.0
npm info using node@v8.9.2
npm verb npm-session ea38310110279de7
npm http fetch GET 404 https://registry.npmjs.org/aws-sdk-js 2211ms
npm verb stack Error: 404 Not Found: aws-sdk-js@latest
npm verb stack     at fetch.then.res (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/fetch.js:42:19)
npm verb stack     at tryCatcher (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
npm verb stack     at Promise._settlePromiseFromHandler (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:512:31)
npm verb stack     at Promise._settlePromise (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:569:18)
npm verb stack     at Promise._settlePromise0 (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:614:10)
npm verb stack     at Promise._settlePromises (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:693:18)
npm verb stack     at Async._drainQueue (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:133:16)
npm verb stack     at Async._drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:143:10)
npm verb stack     at Immediate.Async.drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:17:14)
npm verb stack     at runCallback (timers.js:789:20)
npm verb stack     at tryOnImmediate (timers.js:751:5)
npm verb stack     at processImmediate [as _immediateCallback] (timers.js:722:5)
npm verb cwd /Users/me/git/aws-sdk-js-perf
npm verb Darwin 17.5.0
npm verb argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "--verbose" "aws-sdk-js"
npm verb node v8.9.2
npm verb npm  v5.8.0
npm ERR! code E404
npm ERR! 404 Not Found: aws-sdk-js@latest
npm verb exit [ 1, true ]

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/me/.npm/_logs/2018-05-24T10_30_55_688Z-debug.log

I came across instances where other people experienced this but the below seemed to resolve their issue. It doesn't fix mine:

npm set registry http://registry.npmjs.org/

Does anybody know what might be wrong?

Body:
I also faced the same issue. In my case git:// port was blocked and npm install took too long to time out. (longer than normal it waits before concluding that the process hung.)

A solution was to auto-rewrite all git:// URLs to https://:

Run the following command in your terminal

git config --global url."https://".insteadOf git://

npm install

Hope this helps!!


问:
Pandas - Read only first few lines of each rows
I have a large CSV file with about 10000 rows of text information and each row of my dataset consists of a number of lines. However I just want to read say first 20 lines of each of the rows of my CSV file.

I came across n_rows parameter in pandas read_csv method which helps us in limiting the number of rows of the dataset that we would like to load. Is there also a way where we could only read first 20 lines of data from each of the rows in pandas?

答: You can read in the csv with df = pd.read_csv('path\file.csv') and than just select the first 20 rows by df_new = df.head(20). Is that what you where thinking of?


问:
Graph API for C#: 401 - Unauthorized: Access is denied due to invalid credentials. on /planner/plans
I am working with Graph API. I don´t have too much experience with this. I am creating an application to add a plan into an existing group.

So, I have registered an application with this permissions (You can see that these are Delegated permissions) :

Then, I have written this code to Add a new Planner (You will see that I am using a token) using this endpoint /planner/plans .

```<code>var configAuthority = "https://login.microsoftonline.com/8318d89e-e4db-471e-85da-b34ae833813f";
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                  .Create(ConfigurationParameters.ClientID)
                                  .WithTenantId(ConfigurationParameters.TenantID)
                                  .WithClientSecret(ConfigurationParameters.ClientSecret)
                                  .WithAuthority(new Uri(configAuthority))
                                  .Build();
            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
            AuthenticationResult accessToken = confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync().Result;
            GraphServiceClient graphClient = new GraphServiceClient(authProvider);
            List<HeaderOption> requestHeaders = new List<HeaderOption>() {
                            new HeaderOption("Authorization", "Bearer " + accessToken.AccessToken)
                };
            var existingsplanners = graphClient
                                        .Groups[createPlannerForGroupRequest.GroupId.ToString()]
                                        .Planner
                                        .Plans.
                                        Request(requestHeaders)
                                        .GetAsync()
                                        .Result;
            var planner = graphClient
                        .Groups[createPlannerForGroupRequest.GroupId.ToString()]
                        .Planner
                        .Plans
                        .Request(requestHeaders)
                        .AddAsync(new PlannerPlan {
                            Title = createPlannerForGroupRequest.Name,
                            Owner = createPlannerForGroupRequest.GroupId.ToString(),
                            ODataType = null,
                        }).Result;
</code>```

The result for both requests are the same.

```<code>Code: UnknownError
Message: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>401 - Unauthorized: Access is denied due to invalid credentials.</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;}
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;}
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;}
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
background-color:#555555;}
#content{margin:0 0 0 2%;;}
.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
 <div class="content-container"><fieldset>
  <h2>401 - Unauthorized: Access is denied due to invalid credentials.</h2>
  <h3>You do not have permission to view this directory or page using the credentials that you supplied.</h3>
 </fieldset></div>
</div>
</body>
</html>

Inner error:
    AdditionalData:
    request-id: 19c09b10-1694-4201-85a9-ba3639e1dba5
    date: 2020-06-03T07:29:59
ClientRequestId: 19c09b10-1694-4201-85a9-ba3639e1dba5
</code>```

As you can see, there is a permissions issue even if it is a delegated permissions on Azure AD. Should I wait 24 hours? Should I change the token requester method instead of use AcquireTokenForClient?

The same method works on Graph Explorer. Creation of Team instance for an existing group works fine.

Thank you!

答:
It seems you use client credential grant flow in your code, but the graph api just support delegated permissions. So we need to use authorization code grant flow or username/password grant flow. (By the way, we recommend authorization code flow rather than username/password flow)

For authorization code flow, please refer to this tutorial with the code sample in it.

```<code>IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithRedirectUri(redirectUri)
    .WithClientSecret(clientSecret) // or .WithCertificate(certificate)
    .Build();

AuthorizationCodeProvider authProvider = new AuthorizationCodeProvider(confidentialClientApplication, scopes);
</code>```

For username/password flow, you can refer to this tutorial with the code sample in it.

```<code>IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
            .Create(clientId)
            .WithTenantId(tenantID)
            .Build();

UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);

GraphServiceClient graphClient = new GraphServiceClient(authProvider);

User me = await graphClient.Me.Request()
                .WithUsernamePassword(email, password)
                .GetAsync();
</code>```

Update:

You can do some changes by following the steps below, then you don't need to provide the client_secret in your code and it also will not show the error message The request body must contain the following parameter: 'client_assertion' or 'client_secret'.

Go to your app registered in azure ad and click "Authentication" --> "Add a platform" --> "Mobile and desktop applications".

Choose the first one as the "Redirect URIs".

Scroll down and check if this configuration is "yes"(if "no", please change it to "yes"), then click "Save".

Body:
I am working with Graph API. I don´t have too much experience with this. I am creating an application to add a plan into an existing group.

So, I have registered an application with this permissions (You can see that these are Delegated permissions) :

Then, I have written this code to Add a new Planner (You will see that I am using a token) using this endpoint /planner/plans .

var configAuthority = "https://login.microsoftonline.com/8318d89e-e4db-471e-85da-b34ae833813f";
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                  .Create(ConfigurationParameters.ClientID)
                                  .WithTenantId(ConfigurationParameters.TenantID)
                                  .WithClientSecret(ConfigurationParameters.ClientSecret)
                                  .WithAuthority(new Uri(configAuthority))
                                  .Build();
            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
            AuthenticationResult accessToken = confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync().Result;
            GraphServiceClient graphClient = new GraphServiceClient(authProvider);
            List<HeaderOption> requestHeaders = new List<HeaderOption>() {
                            new HeaderOption("Authorization", "Bearer " + accessToken.AccessToken)
                };
            var existingsplanners = graphClient
                                        .Groups[createPlannerForGroupRequest.GroupId.ToString()]
                                        .Planner
                                        .Plans.
                                        Request(requestHeaders)
                                        .GetAsync()
                                        .Result;
            var planner = graphClient
                        .Groups[createPlannerForGroupRequest.GroupId.ToString()]
                        .Planner
                        .Plans
                        .Request(requestHeaders)
                        .AddAsync(new PlannerPlan {
                            Title = createPlannerForGroupRequest.Name,
                            Owner = createPlannerForGroupRequest.GroupId.ToString(),
                            ODataType = null,
                        }).Result;

The result for both requests are the same.

Code: UnknownError
Message: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>401 - Unauthorized: Access is denied due to invalid credentials.</title>

Server Error

<fieldset>

401 - Unauthorized: Access is denied due to invalid credentials.

You do not have permission to view this directory or page using the credentials that you supplied.

 </fieldset>

Inner error:
    AdditionalData:
    request-id: 19c09b10-1694-4201-85a9-ba3639e1dba5
    date: 2020-06-03T07:29:59
ClientRequestId: 19c09b10-1694-4201-85a9-ba3639e1dba5

As you can see, there is a permissions issue even if it is a delegated permissions on Azure AD. Should I wait 24 hours? Should I change the token requester method instead of use AcquireTokenForClient?

The same method works on Graph Explorer. Creation of Team instance for an existing group works fine.

Thank you!

Body:
It seems you use client credential grant flow in your code, but the graph api just support delegated permissions. So we need to use authorization code grant flow or username/password grant flow. (By the way, we recommend authorization code flow rather than username/password flow)

For authorization code flow, please refer to this tutorial with the code sample in it.

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithRedirectUri(redirectUri)
    .WithClientSecret(clientSecret) // or .WithCertificate(certificate)
    .Build();

AuthorizationCodeProvider authProvider = new AuthorizationCodeProvider(confidentialClientApplication, scopes);

For username/password flow, you can refer to this tutorial with the code sample in it.

IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
            .Create(clientId)
            .WithTenantId(tenantID)
            .Build();

UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);

GraphServiceClient graphClient = new GraphServiceClient(authProvider);

User me = await graphClient.Me.Request()
                .WithUsernamePassword(email, password)
                .GetAsync();

Update:

You can do some changes by following the steps below, then you don't need to provide the client_secret in your code and it also will not show the error message The request body must contain the following parameter: 'client_assertion' or 'client_secret'.

Go to your app registered in azure ad and click "Authentication" --> "Add a platform" --> "Mobile and desktop applications".

Choose the first one as the "Redirect URIs".

Scroll down and check if this configuration is "yes"(if "no", please change it to "yes"), then click "Save".


问:
Ruby Undefined Local Variable
The following is code from an ERB tutorial. When I tried to execute the code, the compiler complained saying "(erb):16: undefined local variable or method `priority' for main:Object (NameError)". I cannot figure out the reason. Could someone please help me out?</p>

```<code>require "erb"

# Create template.
template = %q{
  From:  James Edward Gray II <james@grayproductions.net>
  To:  <%= to %>
  Subject:  Addressing Needs

  <%= to[/\w+/] %>:

  Just wanted to send a quick note assuring that your needs are being
  addressed.

  I want you to know that my team will keep working on the issues,
  especially:

  <%# ignore numerous minor requests -- focus on priorities %>
  % priorities.each do |priority|
    * <%= priority %>
  % end

  Thanks for your patience.

  James Edward Gray II
}.gsub(/^  /, '')

message = ERB.new(template, 0, "%<>")

# Set up template data.
to = "Community Spokesman <spokesman@ruby_community.org>"
priorities = [ "Run Ruby Quiz",
               "Document Modules",
               "Answer Questions on Ruby Talk" ]

# Produce result.
email = message.result
puts email
</code>```

答:
That ERB template looks mangled, a problem caused by your indentation. You just need to fix the middle:

```<code>  <% priorities.each do |priority| %>
    * <%= priority %>
  <% end %>
</code>```

The alternate syntax is to have a % at the very beginning of the line. In your case you have inadvertently added some spaces which are rendering that part of the ERB invalid.

Title: Ruby Undefined Local Variable

Body:
The following is code from an ERB tutorial. When I tried to execute the code, the compiler complained saying "(erb):16: undefined local variable or method `priority' for main:Object (NameError)". I cannot figure out the reason. Could someone please help me out?

require "erb"

# Create template.
template = %q{
  From:  James Edward Gray II <james@grayproductions.net>
  To:  <%= to %>
  Subject:  Addressing Needs

  <%= to[/\w+/] %>:

  Just wanted to send a quick note assuring that your needs are being
  addressed.

  I want you to know that my team will keep working on the issues,
  especially:

  <%# ignore numerous minor requests -- focus on priorities %>
  % priorities.each do |priority|
    * <%= priority %>
  % end

  Thanks for your patience.

  James Edward Gray II
}.gsub(/^  /, '')

message = ERB.new(template, 0, "%<>")

# Set up template data.
to = "Community Spokesman <spokesman@ruby_community.org>"
priorities = [ "Run Ruby Quiz",
               "Document Modules",
               "Answer Questions on Ruby Talk" ]

# Produce result.
email = message.result
puts email

Body:
That ERB template looks mangled, a problem caused by your indentation. You just need to fix the middle:

  <% priorities.each do |priority| %>
    * <%= priority %>
  <% end %>

The alternate syntax is to have a % at the very beginning of the line. In your case you have inadvertently added some spaces which are rendering that part of the ERB invalid.


问:
How to hide source code tab from user in github?
I have a repo in GitHub (private), all my source code is there.

I recently hire a QA to test the system and find some bugs. I want from him to open bugs and issues on github so my developer will fix them and update statuses.

The problem is I don't want QA to able to see the source code.

I think to open different repo just for QA to put the bugs there, but now my developer is working on two repo which the same.

Is there a nice solution for this problem?  maybe some configuration that allow me to hide the source for the user? or website that show the issue and allow to manage them?

答:
No, there is not a clean solution (as in having a single repo). As stated in GitHub own docs:

GitHub does not provide issues-only access permissions, but you can
  accomplish this using a second repository which contains only the
  issues.

However, please read the last paragraph:

For example, if you pushed a commit to the private repository's
  default branch with a message that read Fixes organization/public-repo#12
  , the issue would be closed, but only users
  with the proper permissions would see the cross-repository reference
  indicating the commit that closed the issue. Without the permissions,
  a reference still appears, but the details are omitted.

More on how to link a pull request to an issue and/or automatically closing issues with keywords in commit message.


问:
Py.test No module named *
I have a folder structure like this

```<code>App
--App
  --app.py
--Docs
--Tests
  --test_app.py
</code>```

In my test_app.py file, I have a line to import my app module. When I run py.test on the root folder, I get this error about no module named app. How should I configure this?

答:
I got the similar issue. And after trying multiple things including installing pytest on virtual environment and adding/removing __init__.py file from the package, none worked for me.

Solution that worked for me is(windows solution):
Added Project folder(not package folder) to python path(set PYTHONPATH=%PYTHONPATH%;%CD%)

Ran my script from Project Folder and boom, it worked.

Title: Py.test No module named *

Body:
I have a folder structure like this

App
--App
  --app.py
--Docs
--Tests
  --test_app.py

In my test_app.py file, I have a line to import my app module. When I run py.test on the root folder, I get this error about no module named app. How should I configure this?


问:
Seaborn Catplot is throwing error: truth value is ambiguous
I am trying to do a catplot using seaborn library for all the categorical  variables in my dataframe but I ma getting error for ambiguous truth value. It generally happens with "&" value but I am unable to get the root cause here. My target is continuous variable.

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

target = df[target_col]
features = df[df.columns.difference([target_col])]

cat_cols = features.select_dtypes(include=['object']).columns.to_list()

fig, axes = plt.subplots(round(len(cat_cols) / 3), 3, figsize=(15, 15))
for i, ax in enumerate(fig.axes):
        if i < len(cat_cols):
           sns.catplot(x=cat_cols[i], y=target, kind='bar',data=df, ax = ax)

</code>```

But I am getting the below error. Which part is causing this value error?

```<code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

答:
sns.catplot is a grid level plot, so you should not slot it into a subplot. You can use a facetgrid with barplot:

For example this is your data:

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({'y':np.random.uniform(0,1,50),'A':np.random.choice(['a1','a2'],50),
                  'B':np.random.choice(['b1','b2'],50),'C':np.random.randint(0,10,50),
                  'D':np.random.choice(['d1','d2'],50),'E':np.random.choice(['e1','e2'],50)})
target_col = "y"
cat_cols = df.columns[df.dtypes==object]
</code>```

seaborn works better with long format, so you can pivot your data long like this:

```<code>df.melt(id_vars=target_col,value_vars=cat_cols)

    y      variable value
0   0.606734    A   a1
1   0.603324    A   a2
2   0.938280    A   a2
3   0.718703    A   a1
4   0.808013    A   a1
</code>```

The column variable now defines the facet to plot and the x-axis is your value. We call this directly:

```<code>g = sns.FacetGrid(df.melt(id_vars=target_col,value_vars=cat_cols),
col='variable', sharex=False,col_wrap=3)
g.map_dataframe(sns.barplot, x="value", y="y")
</code>```

Body:
I am trying to do a catplot using seaborn library for all the categorical  variables in my dataframe but I ma getting error for ambiguous truth value. It generally happens with "&" value but I am unable to get the root cause here. My target is continuous variable.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

target = df[target_col]
features = df[df.columns.difference([target_col])]

cat_cols = features.select_dtypes(include=['object']).columns.to_list()

fig, axes = plt.subplots(round(len(cat_cols) / 3), 3, figsize=(15, 15))
for i, ax in enumerate(fig.axes):
        if i < len(cat_cols):
           sns.catplot(x=cat_cols[i], y=target, kind='bar',data=df, ax = ax)

But I am getting the below error. Which part is causing this value error?

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Body:
sns.catplot is a grid level plot, so you should not slot it into a subplot. You can use a facetgrid with barplot:

For example this is your data:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({'y':np.random.uniform(0,1,50),'A':np.random.choice(['a1','a2'],50),
                  'B':np.random.choice(['b1','b2'],50),'C':np.random.randint(0,10,50),
                  'D':np.random.choice(['d1','d2'],50),'E':np.random.choice(['e1','e2'],50)})
target_col = "y"
cat_cols = df.columns[df.dtypes==object]

seaborn works better with long format, so you can pivot your data long like this:

df.melt(id_vars=target_col,value_vars=cat_cols)

    y      variable value
0   0.606734    A   a1
1   0.603324    A   a2
2   0.938280    A   a2
3   0.718703    A   a1
4   0.808013    A   a1

The column variable now defines the facet to plot and the x-axis is your value. We call this directly:

g = sns.FacetGrid(df.melt(id_vars=target_col,value_vars=cat_cols),
col='variable', sharex=False,col_wrap=3)
g.map_dataframe(sns.barplot, x="value", y="y")


问:
How to hide tippy js tooltip after some seconds onclick?
Is there any default method to hide tooltip after a few seconds on click?
I want to show it on click for 2 sec and then close it. how should i do this?</p>

答:
You need to set a timeout when the tooltip is first shown. I also like to add hideOnClick: false so that it doesn't disappear when they click somewhere else.

Here's a complete example for you:

```<code>tippy('#button', {
  trigger: 'click',
  hideOnClick: false,
  onShow(instance) {
    setTimeout(() => {
      instance.hide();
    }, 2000);
  }
});
</code>```

Body:
You need to set a timeout when the tooltip is first shown. I also like to add hideOnClick: false so that it doesn't disappear when they click somewhere else.

Here's a complete example for you:

tippy('#button', {
  trigger: 'click',
  hideOnClick: false,
  onShow(instance) {
    setTimeout(() => {
      instance.hide();
    }, 2000);
  }
});


问:
Why i'm getting 'QuerySyntaxException'?
```<code>@Query("SELECT new com.ethihas.v1.blog.dto.PostDto(p.title, p.image, p.content, p.location,p.city, p.state, p.country) FROM Post p order by id desc limit 10")
List<PostDto> getAllPosts(@Param("from") Integer from, @Param("to") Integer to);
</code>```

above is my query and below is constructor of PostDto

```<code>    public PostDto(String title, Integer image, String content, String location, String city, String state, String country) {
    this.title = title;
    this.image = image;
    this.content = content;
    this.location = location;
    this.city = city;
    this.state = state;
    this.country = country;
}
</code>```

everything looks fine only for me but its causing below exception

```<code>Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: limit near line 1, column 167 [SELECT new com.ethihas.v1.blog.dto.PostDto(p.title, p.image, p.content, p.location,p.city, p.state, p.country) FROM com.ethihas.v1.blog.model.Post p order by id desc limit 10]
</code>```

答:
Limit will not work JPQL, we can use Pageable to get records based on order

```<code>    Pageable firstPageWithTwoElements = PageRequest.of(0, 2, Sort.by("id").descending());
    Page<Post> pagedResult = postRepository.findAll(firstPageWithTwoElements);
    List<Post> postList = pagedResult.getContent();
</code>```

above code will be give recent 2 entries sorted based on ID,

Title: Why i'm getting 'QuerySyntaxException'?

Body:
@Query("SELECT new com.ethihas.v1.blog.dto.PostDto(p.title, p.image, p.content, p.location,p.city, p.state, p.country) FROM Post p order by id desc limit 10")
List<PostDto> getAllPosts(@Param("from") Integer from, @Param("to") Integer to);

above is my query and below is constructor of PostDto

    public PostDto(String title, Integer image, String content, String location, String city, String state, String country) {
    this.title = title;
    this.image = image;
    this.content = content;
    this.location = location;
    this.city = city;
    this.state = state;
    this.country = country;
}

everything looks fine only for me but its causing below exception

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: limit near line 1, column 167 [SELECT new com.ethihas.v1.blog.dto.PostDto(p.title, p.image, p.content, p.location,p.city, p.state, p.country) FROM com.ethihas.v1.blog.model.Post p order by id desc limit 10]

Body:
Limit will not work JPQL, we can use Pageable to get records based on order

    Pageable firstPageWithTwoElements = PageRequest.of(0, 2, Sort.by("id").descending());
    Page<Post> pagedResult = postRepository.findAll(firstPageWithTwoElements);
    List<Post> postList = pagedResult.getContent();

above code will be give recent 2 entries sorted based on ID,


问:
Usage of @TestCaseName with @FileParameters in JUnitParams
I use JUnit4 with JUnitParams for testing and I want to know more about the usage of the @TestCaseName annotation. I understand the usage of @TestCaseName with the @Parameters annotation, but I want to know about how to use @TestCaseName with the @FileParmeters annotation.

答:
@TestCaseName allows you to modify how the name of the test case is presented in reports (eg. in your IDE or in the Maven Surefire report). The default naming is {method}({params}) [{index}]. You can use placeholders to create your own test case names. See Javadoc of junitparams.naming.TestCaseName#value:

A template of the individual test case name. This template can contain
  macros, which will be substituted by their actual values at runtime.

 Supported macros are:

{index} - index of
  parameters set (starts from zero). Hint: use it to avoid names
  duplication.

{params} - parameters set joined by
  comma.

{method} - testing method name.

      {0}, {1}, {2} - single parameter by index in current parameters set.
      If there is no parameter with such index, it will use empty string.

 Lets assume, that we are testing Fibonacci
  sequence generator. We have a test with the following signature

```<code>@Parameters({ "0,1", "8,34" })
public void testFibonacci(int indexInSequence, int expectedNumber) { ... }
</code>```

Here are some examples, that can be used as a test name template:

{method}({params}) => testFibonacci(0, 1), testFibonacci(8, 34)

fibonacci({0}) = {1} => fibonacci(0) = 1, fibonacci(8) = 34

{0} element should be {1} => 0 element should be 1, 8 element should be 34

Fibonacci sequence test #{index} => Fibonacci sequence test #0, Fibonacci sequence test #1

@FileParameters does not have any relation to @TestCaseName - it's simply a way to provide parameters to a test method from a file. Using the example above, instead of @Parameters you could use @FileParameters("/path/to/file.txt") and have a /path/to/file.txt with content

```<code>0,1
8,34
</code>```

to achieve the same results.

Body:
@TestCaseName allows you to modify how the name of the test case is presented in reports (eg. in your IDE or in the Maven Surefire report). The default naming is {method}({params}) [{index}]. You can use placeholders to create your own test case names. See Javadoc of junitparams.naming.TestCaseName#value:

A template of the individual test case name. This template can contain
  macros, which will be substituted by their actual values at runtime.

 Supported macros are:

{index} - index of
  parameters set (starts from zero). Hint: use it to avoid names
  duplication.

{params} - parameters set joined by
  comma.

{method} - testing method name.

      {0}, {1}, {2} - single parameter by index in current parameters set.
      If there is no parameter with such index, it will use empty string.

 Lets assume, that we are testing Fibonacci
  sequence generator. We have a test with the following signature

@Parameters({ "0,1", "8,34" })
public void testFibonacci(int indexInSequence, int expectedNumber) { ... }

Here are some examples, that can be used as a test name template:

{method}({params}) => testFibonacci(0, 1), testFibonacci(8, 34)

fibonacci({0}) = {1} => fibonacci(0) = 1, fibonacci(8) = 34

{0} element should be {1} => 0 element should be 1, 8 element should be 34

Fibonacci sequence test #{index} => Fibonacci sequence test #0, Fibonacci sequence test #1

@FileParameters does not have any relation to @TestCaseName - it's simply a way to provide parameters to a test method from a file. Using the example above, instead of @Parameters you could use @FileParameters("/path/to/file.txt") and have a /path/to/file.txt with content

0,1
8,34

to achieve the same results.


问:
how to fetch resouceID of azure resource
Can you please help to fetch resourceid in azure to call below restapi

$URL = "https://graph.microsoft.com/beta/privilegedAccess/azureResources/resources/****xxxxxxxxxxxx****/roleDefinitions?$filter=displayName eq 'Contributors'"

```<code>$Result = Invoke-RestMethod -Uri $URL -Headers $Headers -Method Get
</code>```

答:
You can get the resource id you need by requesting the list.

```<code>> GET https://graph.microsoft.com/beta/privilegedAccess/azureResources/resources
</code>```

please check:here

Body:
Can you please help to fetch resourceid in azure to call below restapi

$URL = "https://graph.microsoft.com/beta/privilegedAccess/azureResources/resources/****xxxxxxxxxxxx****/roleDefinitions?$filter=displayName eq 'Contributors'"

$Result = Invoke-RestMethod -Uri $URL -Headers $Headers -Method Get

Body:
You can get the resource id you need by requesting the list.

> GET https://graph.microsoft.com/beta/privilegedAccess/azureResources/resources

please check:here


问:
read property file using embed angular project inside spring boot app
I have an angular embedded in spring boot project. With using angular 6 and spring boot. All are fine. My angular index.html file is in resources of spring boot app. I want to read spring boot properties in angular html file. Please help me.</p>

答:
The angular application doesn't have access to the spring boot properties, because the angular application runs in the users' browser, and the spring boot app runs on the server.

Your only chance is to manually create REST services, which return the properties, and you can call those services from the angular app.


问:
spark sql date conversion and performing calculation
I have created a data frame from CSV (as per the below screenshot) and registered as a table (createOrReplaceTempView), later I am trying to performing some calculations on DOB columns fo find the employees whose age is more than 30. And I am trying to run the below query, but getting error. Please correct or advise me. Thanks!

```<code>spark.sql(date_format(to_date(DOB, 'yyyy-dd-mm'), 'dd-MMM-yy') as new_dob).show()
</code>```

答:
Your DOB has multiple date format
Try-

```<code>spark.sql("select coalesce(to_date(DOB, 'MM/dd/yyyy'), to_date(DOB, 'dd-mm-yyyy')) as new_dob from <view_name>").show()
</code>```

Body:
I have created a data frame from CSV (as per the below screenshot) and registered as a table (createOrReplaceTempView), later I am trying to performing some calculations on DOB columns fo find the employees whose age is more than 30. And I am trying to run the below query, but getting error. Please correct or advise me. Thanks!

spark.sql(date_format(to_date(DOB, 'yyyy-dd-mm'), 'dd-MMM-yy') as new_dob).show()

Body:
Your DOB has multiple date format
Try-

spark.sql("select coalesce(to_date(DOB, 'MM/dd/yyyy'), to_date(DOB, 'dd-mm-yyyy')) as new_dob from <view_name>").show()


问:
Filter R Shiny Data Frame based on Slider range and display result in Data Table
I'm new to R and R Shiny.  I'm currently trying to create an R Shiny app to display individual annual Mean Sea Level values in a Data Table over a selected period for a selected location.  The period is determined by the user selecting a start year and end year from a range slider, while the location is selected by the user from a drop down box.

Currently I'm just getting a bunch of html along side the drop down box and slider instead of a two column table showing the data for the selected period and location. See screenshot.  The period shown in the table should include the start year and end year selected by the user as well as the years in between, with their corresponding Mean Sea Level values shown in the adjacent column.

I realise it's probably an easy fix but being a novice I'm struggling.  I eventually want to also show a graph/plot for the selected data and also a trendline.  But for now I just want to get the filtered data showing in a table so I can expand the table to show some statistical information.

See my below code attempt.

Much appreciated

Bryan.

```<code>library(shiny)

Year <- c(2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010)
Auckland <- c(1760, 1549, 1388, 1967, 1326, 1765, 1814, 1693, 1502, 1751)
Wellington <- c(2176, 3154, 1138, 1196, 2132, 3176, 4181, 5169, 3150, 4175)
Lyttelton <- c(2176, 3154, 1138, 1196, 2132, 3176, 4181, 5169, 3150, 4175)
my_data <- as.data.frame(cbind(Year,Auckland,Wellington, Lyttelton))

ui <- fluidPage(
  titlePanel("New Zealand Annual Mean Sea Level (MSL) Summary"),

  sidebarLayout(
    sidebarPanel(
      helpText("Annual Mean Sea Level Summary for various locations around NZ."),

      selectInput("var",
                  label = "Choose a Location",
                  choices = c("Auckland",
                              "Lyttelton",
                              "Wellington"),
                  selected = "Auckland"),

      sliderInput("range",
                  label = "Choose a start and end year:",
                  min = min(my_data$Year), max = max(my_data$Year), value = c(2003, 2008),sep = "",)
    ),

    mainPanel(
      textOutput("DataTable")
    )
  )
)
server <- function(input, output) {

  output$DataTable <- renderTable({
    MSL <- my_data[input$range[1]:input$range[2],]
    MSL},include.rownames=FALSE)

}
shinyApp(ui, server)
</code>```

答:
This should do, renderTable in the server with tableOutput in the ui. you can also filter by the Year as in my_data[my_data$Year >= input$range[1] & my_data$Year <= input$range[2],]

```<code>library(shiny)

Year <- c(2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010)
Auckland <- c(1760, 1549, 1388, 1967, 1326, 1765, 1814, 1693, 1502, 1751)
Wellington <- c(2176, 3154, 1138, 1196, 2132, 3176, 4181, 5169, 3150, 4175)
Lyttelton <- c(2176, 3154, 1138, 1196, 2132, 3176, 4181, 5169, 3150, 4175)
my_data <- as.data.frame(cbind(Year,Auckland,Wellington, Lyttelton))

ui <- fluidPage(
    titlePanel("New Zealand Annual Mean Sea Level (MSL) Summary"),

    sidebarLayout(
        sidebarPanel(
            helpText("Annual Mean Sea Level Summary for various locations around NZ."),

            selectInput("var",
                        label = "Choose a Location",
                        choices = c("Auckland",
                                    "Lyttelton",
                                    "Wellington"),
                        selected = "Auckland"),

            sliderInput("range",
                        label = "Choose a start and end year:",
                        min = min(my_data$Year), max = max(my_data$Year), value = c(2003, 2008),sep = "",)
        ),

        mainPanel(
            tableOutput("DataTable")
        )
    )
)
server <- function(input, output) {

    output$DataTable <- renderTable({
        dt <- my_data[my_data$Year >= input$range[1] & my_data$Year <= input$range[2],]
        dt[,c("Year",input$var)]
    },include.rownames=FALSE)

}
shinyApp(ui, server)
</code>```

Body:
I'm new to R and R Shiny.  I'm currently trying to create an R Shiny app to display individual annual Mean Sea Level values in a Data Table over a selected period for a selected location.  The period is determined by the user selecting a start year and end year from a range slider, while the location is selected by the user from a drop down box.

Currently I'm just getting a bunch of html along side the drop down box and slider instead of a two column table showing the data for the selected period and location. See screenshot.  The period shown in the table should include the start year and end year selected by the user as well as the years in between, with their corresponding Mean Sea Level values shown in the adjacent column.

I realise it's probably an easy fix but being a novice I'm struggling.  I eventually want to also show a graph/plot for the selected data and also a trendline.  But for now I just want to get the filtered data showing in a table so I can expand the table to show some statistical information.

See my below code attempt.

Much appreciated

Bryan.

library(shiny)

Year <- c(2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010)
Auckland <- c(1760, 1549, 1388, 1967, 1326, 1765, 1814, 1693, 1502, 1751)
Wellington <- c(2176, 3154, 1138, 1196, 2132, 3176, 4181, 5169, 3150, 4175)
Lyttelton <- c(2176, 3154, 1138, 1196, 2132, 3176, 4181, 5169, 3150, 4175)
my_data <- as.data.frame(cbind(Year,Auckland,Wellington, Lyttelton))

ui <- fluidPage(
  titlePanel("New Zealand Annual Mean Sea Level (MSL) Summary"),

  sidebarLayout(
    sidebarPanel(
      helpText("Annual Mean Sea Level Summary for various locations around NZ."),

      selectInput("var",
                  label = "Choose a Location",
                  choices = c("Auckland",
                              "Lyttelton",
                              "Wellington"),
                  selected = "Auckland"),

      sliderInput("range",
                  label = "Choose a start and end year:",
                  min = min(my_data$Year), max = max(my_data$Year), value = c(2003, 2008),sep = "",)
    ),

    mainPanel(
      textOutput("DataTable")
    )
  )
)
server <- function(input, output) {

  output$DataTable <- renderTable({
    MSL <- my_data[input$range[1]:input$range[2],]
    MSL},include.rownames=FALSE)

}
shinyApp(ui, server)

Body:
This should do, renderTable in the server with tableOutput in the ui. you can also filter by the Year as in my_data[my_data$Year >= input$range[1] & my_data$Year <= input$range[2],]

library(shiny)

Year <- c(2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010)
Auckland <- c(1760, 1549, 1388, 1967, 1326, 1765, 1814, 1693, 1502, 1751)
Wellington <- c(2176, 3154, 1138, 1196, 2132, 3176, 4181, 5169, 3150, 4175)
Lyttelton <- c(2176, 3154, 1138, 1196, 2132, 3176, 4181, 5169, 3150, 4175)
my_data <- as.data.frame(cbind(Year,Auckland,Wellington, Lyttelton))

ui <- fluidPage(
    titlePanel("New Zealand Annual Mean Sea Level (MSL) Summary"),

    sidebarLayout(
        sidebarPanel(
            helpText("Annual Mean Sea Level Summary for various locations around NZ."),

            selectInput("var",
                        label = "Choose a Location",
                        choices = c("Auckland",
                                    "Lyttelton",
                                    "Wellington"),
                        selected = "Auckland"),

            sliderInput("range",
                        label = "Choose a start and end year:",
                        min = min(my_data$Year), max = max(my_data$Year), value = c(2003, 2008),sep = "",)
        ),

        mainPanel(
            tableOutput("DataTable")
        )
    )
)
server <- function(input, output) {

    output$DataTable <- renderTable({
        dt <- my_data[my_data$Year >= input$range[1] & my_data$Year <= input$range[2],]
        dt[,c("Year",input$var)]
    },include.rownames=FALSE)

}
shinyApp(ui, server)


问:
SharePoint 2010 Claims Auth/FBA - Reset password not working
I have a SP site with Claims Authentication and FBA setup. Dual auth Win/Forms is working perfectly.

I have a asp:PasswordRecovery control on app page.
It appears to lookup the account correctly - returning 'not found' messages if the username is not found. However, it fails to reset the password with the following execption:

```<code>Exception information:
   Exception type: NotImplementedException
   Exception message: The method or operation is not implemented.

Thread information:
Thread ID: 10
Thread account name: SERVER01\SPS_Farm
Is impersonating: False
Stack trace:    at    Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider.GetUser(String name, Boolean userIsOnline)
at System.Web.Security.MembershipProvider.GetUser(String username, Boolean userIsOnline, Boolean throwOnError)
at System.Web.UI.WebControls.PasswordRecovery.AttemptSendPasswordUserNameView()
at System.Web.UI.WebControls.PasswordRecovery.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
</code>```

Thanks in advance.

Update:

I added:

    enablePasswordReset="true"

to the app web.config AND the token-service web.config

Wrote some some code to do a manual test, and still got this when my code tried to 'reset' the password:

    This provider is not configured to allow password resets. To enable password reset, set     enablePasswordReset to "true" in the configuration file.

答:
This may not help since you seem to be looking up the user properly... but if you aren't doing this I know you can run into not implemented issues:

Make sure to get an instance of the user using the appropriate Membership Provider.

e.g.

```<code>MembershipUser myUser = Membership.Providers["aspMembership"].GetUser(userName, false);
</code>```

Hope this helps.

Body:
I have a SP site with Claims Authentication and FBA setup. Dual auth Win/Forms is working perfectly.

I have a asp:PasswordRecovery control on app page.
It appears to lookup the account correctly - returning 'not found' messages if the username is not found. However, it fails to reset the password with the following execption:

Exception information:
   Exception type: NotImplementedException
   Exception message: The method or operation is not implemented.

Thread information:
Thread ID: 10
Thread account name: SERVER01\SPS_Farm
Is impersonating: False
Stack trace:    at    Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider.GetUser(String name, Boolean userIsOnline)
at System.Web.Security.MembershipProvider.GetUser(String username, Boolean userIsOnline, Boolean throwOnError)
at System.Web.UI.WebControls.PasswordRecovery.AttemptSendPasswordUserNameView()
at System.Web.UI.WebControls.PasswordRecovery.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

Thanks in advance.

Update:

I added:

    enablePasswordReset="true"

to the app web.config AND the token-service web.config

Wrote some some code to do a manual test, and still got this when my code tried to 'reset' the password:

    This provider is not configured to allow password resets. To enable password reset, set     enablePasswordReset to "true" in the configuration file.

Body:
This may not help since you seem to be looking up the user properly... but if you aren't doing this I know you can run into not implemented issues:

Make sure to get an instance of the user using the appropriate Membership Provider.

e.g.

MembershipUser myUser = Membership.Providers["aspMembership"].GetUser(userName, false);

Hope this helps.


问:
How do I control the amount of times something is added to a list?
I have a list, and I am trying to add a certain amount of variables to it:

```<code>newList = ["Andrew", "Ben", "Happy"]
SecondList = [2,3,1]
BestList = []
for g in range(0,3):
    BestList.append((newList[g])*(int(SecondList[g])))
print (len(BestList))
print (BestList)
</code>```

The problem is I want the "Andrew" variable to be appended to the list 2 times, but instead, it is appended to the list only once, but as "AndrewAndrew". How do I fix my code in a way where instead of multiplying "Andrew" twice and adding it to the list as that one variable, it is added to the list twice. My end goal is for the length of BestList to be 6.

Thanks in advance.

答:
You missed to use the proper loops.

Code:

```<code>names_list = ["Andrew", "Ben", "Happy"]
counts_list = [2,3,1]
final_list = []

for i in range(len(names_list)):
  [final_list.append(names_list[i]) for j in range(counts_list[i])]

print(final_list)
</code>```

Output:

```<code>["Andrew", "Andrew", "Ben", "Ben", "Ben", "Happy"]
</code>```

Body:
I have a list, and I am trying to add a certain amount of variables to it:

newList = ["Andrew", "Ben", "Happy"]
SecondList = [2,3,1]
BestList = []
for g in range(0,3):
    BestList.append((newList[g])*(int(SecondList[g])))
print (len(BestList))
print (BestList)

The problem is I want the "Andrew" variable to be appended to the list 2 times, but instead, it is appended to the list only once, but as "AndrewAndrew". How do I fix my code in a way where instead of multiplying "Andrew" twice and adding it to the list as that one variable, it is added to the list twice. My end goal is for the length of BestList to be 6.

Thanks in advance.

Body:
You missed to use the proper loops.

Code:

names_list = ["Andrew", "Ben", "Happy"]
counts_list = [2,3,1]
final_list = []

for i in range(len(names_list)):
  [final_list.append(names_list[i]) for j in range(counts_list[i])]

print(final_list)

Output:

["Andrew", "Andrew", "Ben", "Ben", "Ben", "Happy"]


问:
IntelliJ Idea showing percentages next to classes - how do I disable this?
This screenshot says it all ... I don't know why these percentages just started showing up, and I don't know how to get rid of them... anyone know?

答:
The percentage is the test coverage.
https://www.jetbrains.com/help/idea/running-test-with-coverage.html#read-coverage%20report

You need to open coverage window and close it.


问:
How to Covert a @XmlType to Json string?
I want to convert a an entity which is @XmlType to a Json string in java. I searched for such question but all I have found is to convert a XML string to Json string .  </p>

答:
I would recommend to use the Jackson library for this job. This works with any Java class as long it's structure is somehow compatible to JSON:

```<code>ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
</code>```

The "withDefaultPrettyPrinter" part is optional.

Body:
I would recommend to use the Jackson library for this job. This works with any Java class as long it's structure is somehow compatible to JSON:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);

The "withDefaultPrettyPrinter" part is optional.


问:
Android Studio-Kotlin : Value <br of type java.lang.String cannot be converted to JSONObject
This is my php file :
I want to Insert data into detaildonasi based on last id in donasi table

```<code><?php

$conn = new mysqli("localhost","root","","donasiku");
$sql = "SELECT * FROM donasi ORDER BY id DESC LIMIT = 1";
$result = $conn->query($sql);

if($result === TRUE)
{
    $id = $result->fetch_assoc();
    $jumlah = $_POST['jumlah'];
    $kebutuhanid = $_POST['kebutuhanid'];

    $sql2 = "INSERT INTO detaildonasi VALUES('','$jumlah','$id','$kebutuhanid')"
    $result2 = $conn->query($sql2);

    if($result2 === TRUE)
    {
        $arr = array('hasil' => 'success');
    }
    else
    {
        $arr = array('hasil' => $conn->error);
    }
}
else
{
    $arr = array('hasil' => $conn->error);
}

echo json_encode($arr);
$conn->close();

?>
</code>```

This is the Volley of my Fragment file :

```<code>val q2 = Volley.newRequestQueue(this.context)
val url2 = "http://10.0.2.2/donasiku/detaildonasi.php"
val sr2 = object:StringRequest(Request.Method.POST,url2,Response.Listener {
      response -> try{
      val obj2 = JSONObject(response)
      Toast.makeText(this.context,obj2.getString("hasil"), Toast.LENGTH_SHORT).show()
      }catch (e:JSONException){Toast.makeText(this.context, e.message.toString(), Toast.LENGTH_SHORT).show()}
      },Response.ErrorListener {  })
      {
        override fun getParams(): Map<String, String> {
        val params2 = HashMap<String, String>()
        for(donasi in daftarDonasiUser)
         {
            params2.put("jumlah",donasi.jumlahbarang.toString())
            params2.put("kebutuhanid",donasi.idbarang.toString())
         }
            return params2

            }
         }

         q2.add(sr2)
</code>```

The code goes into catch JSONException and Toast Value br of type java.lang.String cannot be converted to JSONObject.

答: <br is html. Your api is erroring in some way and so html of some kind (instead of the Json you are expecting) is being written to the page.Try making the same request in Postman and viewing the response.

Body:
This is my php file :
I want to Insert data into detaildonasi based on last id in donasi table

<?php

$conn = new mysqli("localhost","root","","donasiku");
$sql = "SELECT * FROM donasi ORDER BY id DESC LIMIT = 1";
$result = $conn->query($sql);

if($result === TRUE)
{
    $id = $result->fetch_assoc();
    $jumlah = $_POST['jumlah'];
    $kebutuhanid = $_POST['kebutuhanid'];

    $sql2 = "INSERT INTO detaildonasi VALUES('','$jumlah','$id','$kebutuhanid')"
    $result2 = $conn->query($sql2);

    if($result2 === TRUE)
    {
        $arr = array('hasil' => 'success');
    }
    else
    {
        $arr = array('hasil' => $conn->error);
    }
}
else
{
    $arr = array('hasil' => $conn->error);
}

echo json_encode($arr);
$conn->close();

?>

This is the Volley of my Fragment file :

val q2 = Volley.newRequestQueue(this.context)
val url2 = "http://10.0.2.2/donasiku/detaildonasi.php"
val sr2 = object:StringRequest(Request.Method.POST,url2,Response.Listener {
      response -> try{
      val obj2 = JSONObject(response)
      Toast.makeText(this.context,obj2.getString("hasil"), Toast.LENGTH_SHORT).show()
      }catch (e:JSONException){Toast.makeText(this.context, e.message.toString(), Toast.LENGTH_SHORT).show()}
      },Response.ErrorListener {  })
      {
        override fun getParams(): Map<String, String> {
        val params2 = HashMap<String, String>()
        for(donasi in daftarDonasiUser)
         {
            params2.put("jumlah",donasi.jumlahbarang.toString())
            params2.put("kebutuhanid",donasi.idbarang.toString())
         }
            return params2

            }
         }

         q2.add(sr2)

The code goes into catch JSONException and Toast Value br of type java.lang.String cannot be converted to JSONObject.


问:
r: Error: replacement argument is zero length
I try to add the values of a vector by initializing as soon as there is a 0

ex: I have (0,1,1,1,1,0,1,1) and I am looking for that (0,1,2,3,4,0,1,2)

I extracted the column of my data.frame with my 0 and my 1

```<code>x <-as.numeric (as.array (base1 $ taring))
</code>```

I then apply the function to it:

```<code>for (i in 1: 3334) {
  if (x [i]! = 0)
    x [i] <- x [i] + x [i-1]
}
</code>```

But it returns the error to me:

```<code>Error in x [i] <- x [i] + x [i - 1]:
  replacement argument is zero length
</code>```

Please someone can tell me where this error came from, thank you.

答:
Assuming your input is

```<code>x <- c(0,1,1,1,1,0,1,1)
</code>```

You can get the output using ave as :

```<code>ave(x, cumsum(x == 0), FUN = cumsum)
#[1] 0 1 2 3 4 0 1 2
</code>```

Body:
I try to add the values of a vector by initializing as soon as there is a 0

ex: I have (0,1,1,1,1,0,1,1) and I am looking for that (0,1,2,3,4,0,1,2)

I extracted the column of my data.frame with my 0 and my 1

x <-as.numeric (as.array (base1 $ taring))

I then apply the function to it:

for (i in 1: 3334) {
  if (x [i]! = 0)
    x [i] <- x [i] + x [i-1]
}

But it returns the error to me:

Error in x [i] <- x [i] + x [i - 1]:
  replacement argument is zero length

Please someone can tell me where this error came from, thank you.

Body:
Assuming your input is

x <- c(0,1,1,1,1,0,1,1)

You can get the output using ave as :

ave(x, cumsum(x == 0), FUN = cumsum)
#[1] 0 1 2 3 4 0 1 2


问:
efficient way to implement paging
Should I use LINQ's Skip() and Take() method for paging, or implement my own paging with a SQL query?

Which is most efficient? Why would I choose one over the other?

I'm using SQL Server 2008, ASP.NET MVC and LINQ.

答:
The approach that I am giving is the fastest pagination that SQL server can achieve. I have tested this on 5 million records. This approach is far better than "OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY" provided by SQL Server.</p>

```<code>-- The below given code computes the page numbers and the max row of previous page
-- Replace <<>> with the correct table data.
-- Eg. <<IdentityColumn of Table>> can be EmployeeId and <<Table>> will be dbo.Employees

DECLARE @PageNumber int=1; --1st/2nd/nth page. In stored proc take this as input param.
DECLARE @NoOfRecordsPerPage int=1000;

 DECLARE @PageDetails TABLE
       (
        <<IdentityColumn of Table>> int,
        rownum int,
        [PageNumber] int
       )
       INSERT INTO @PageDetails values(0, 0, 0)
       ;WITH CTE AS
       (
       SELECT <<IdentityColumn of Table>>, ROW_NUMBER() OVER(ORDER BY <<IdentityColumn of Table>>) rownum FROM <<Table>>
       )
       Insert into @PageDetails
       SELECT <<IdentityColumn of Table>>, CTE.rownum, ROW_NUMBER() OVER (ORDER BY rownum) as [PageNumber] FROM CTE WHERE CTE.rownum%@NoOfRecordsPerPage=0

--SELECT * FROM @PageDetails

-- Actual pagination
SELECT TOP (@NoOfRecordsPerPage)
FROM <<Table>> AS <<Table>>
WHERE <<IdentityColumn of Table>> > (SELECT <<IdentityColumn of Table>> FROM
@PageDetails WHERE PageNumber=@PageNumber)
ORDER BY <<Identity Column of Table>>
</code>```

OwnerDisplayName: StoneHeart

ContentLicense: CC BY-SA 2.5

Title: efficient way to implement paging

Body:
The approach that I am giving is the fastest pagination that SQL server can achieve. I have tested this on 5 million records. This approach is far better than "OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY" provided by SQL Server.

-- The below given code computes the page numbers and the max row of previous page
-- Replace <<>> with the correct table data.
-- Eg. <<IdentityColumn of Table>> can be EmployeeId and <<Table>> will be dbo.Employees

DECLARE @PageNumber int=1; --1st/2nd/nth page. In stored proc take this as input param.
DECLARE @NoOfRecordsPerPage int=1000;

 DECLARE @PageDetails TABLE
       (
        <<IdentityColumn of Table>> int,
        rownum int,
        [PageNumber] int
       )
       INSERT INTO @PageDetails values(0, 0, 0)
       ;WITH CTE AS
       (
       SELECT <<IdentityColumn of Table>>, ROW_NUMBER() OVER(ORDER BY <<IdentityColumn of Table>>) rownum FROM <<Table>>
       )
       Insert into @PageDetails
       SELECT <<IdentityColumn of Table>>, CTE.rownum, ROW_NUMBER() OVER (ORDER BY rownum) as [PageNumber] FROM CTE WHERE CTE.rownum%@NoOfRecordsPerPage=0

--SELECT * FROM @PageDetails

-- Actual pagination
SELECT TOP (@NoOfRecordsPerPage)
FROM <<Table>> AS <<Table>>
WHERE <<IdentityColumn of Table>> > (SELECT <<IdentityColumn of Table>> FROM
@PageDetails WHERE PageNumber=@PageNumber)
ORDER BY <<Identity Column of Table>>


问:
Need to type https:// awlays after adding SSL certificate
I bought a SSL certificate from some company and i have installed it on my Windows 2016 server IIS 10.and it's bind like below image.

When i type https://example.com it works fine... BUT when i type just example.com then it goes to IIS default site. as well as when i type https://www.example.com it works fine but when i type just www.example.com then it goes to Default IIS site.

This means when i type https:// then it works fine... But normally users type example.com or www.example.com ..
So how can i configure thisone for the above requirement ?

答:
When you type in example.com or www.example.com in web browser, the client will just send a request over http instead of https like http://example.com.

Since you need https for your website so Require SSL will be checked. You can't host both http and https binding under the same site. Otherwise, Require SSL handshake will corrupt URL redirect rule.

Please install URL rewrite module and put this rule under your Default Website.

```<code> <rule name="HTTPS force" enabled="true" stopProcessing="true">
 <match url="(.*)" />
 <conditions>
 <add input="{HTTPS}" pattern="^OFF$" />
 </conditions>
 <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
 </rule>
</code>```

Body:
When you type in example.com or www.example.com in web browser, the client will just send a request over http instead of https like http://example.com.

Since you need https for your website so Require SSL will be checked. You can't host both http and https binding under the same site. Otherwise, Require SSL handshake will corrupt URL redirect rule.

Please install URL rewrite module and put this rule under your Default Website.

 <rule name="HTTPS force" enabled="true" stopProcessing="true">
 <match url="(.*)" />
 <conditions>
 <add input="{HTTPS}" pattern="^OFF$" />
 </conditions>
 <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
 </rule>


问:
Code getting into infinite loop in javascript
My code is getting into infinite loop even if I input "yes" or "yeah".

Below is my code:

```<code>var answer = prompt("Are we there yet?");
while(answer != "yes" || answer != "yeah" ){
    var answer = prompt("Are we there yet?");
}
alert("YAY! We made it!!");
</code>```

答:
Change || to &&.

You are asking: If your answer is not "yes" or it is not "yeah". If you answer with "yes", the answer is not "yeah". If you answer with "yeah" your answer is not "yes". That's why you haven an infinite loop.

Check out De Morgan's laws for more details. Negotiation of !(answer == "yes" || answer == "yeah")  results also in changing the or operator.

var answer = prompt("Are we there yet?");

while(answer != "yes" && answer != "yeah" ){
    answer = prompt("Are we there yet?");
}

alert("YAY! We made it!!"); ```

Body:
My code is getting into infinite loop even if I input "yes" or "yeah".

Below is my code:

var answer = prompt("Are we there yet?");
while(answer != "yes" || answer != "yeah" ){
    var answer = prompt("Are we there yet?");
}
alert("YAY! We made it!!");


问:
Does Mono/Flux have operators like Peek / IfPresent from the Stream / Optional API?
As title says, was wondering if, when working with Mono/Flux, are there any equivalent (or similar) operators to peek and ifPresent from the Java Stream API.</p>

答:
Flux#hasElement:

Emit a single boolean true if any of the elements of this Flux sequence is equal to the provided value. The implementation uses short-circuit logic and completes with true if an element matches the value.

```<code>Mono<Boolean> ifPresent = Flux.<Ob>just(...)
        .hasElement(value); // similar to ifPresent
</code>```

Flux#doOnNext:

Add behavior (side-effect) triggered when the Flux emits an item.

```<code>Flux<Ob> flux = Flux.<Ob>just()
        .doOnNext(i -> {}); // similar to peek
</code>```

Body:
Flux#hasElement:

Emit a single boolean true if any of the elements of this Flux sequence is equal to the provided value. The implementation uses short-circuit logic and completes with true if an element matches the value.

Mono<Boolean> ifPresent = Flux.<Ob>just(...)
        .hasElement(value); // similar to ifPresent

Flux#doOnNext:

Add behavior (side-effect) triggered when the Flux emits an item.

Flux<Ob> flux = Flux.<Ob>just()
        .doOnNext(i -> {}); // similar to peek


问:
Showing up collapsible table exactly in center of the table header
I want to show my table header in the center of the web browser page. On pressing the + button the data is shown but it is aligned exactly below the table header. I want the collapsible table to be shown exactly in center of the table header. I tried changing in CSS but its not working out. Can anyone kindly help me out?

$('.header').click(function() {
  $(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table,
tr,
td,
th {
  border: 1px solid black;
  border-collapse: collapse;
}

tr.header {
  cursor: pointer;
}

.header .sign:after {
  content: "+";
  display: inline-block;
}

.header.expand .sign:after {
  content: "-";
}

table {
  margin-left: 30px;
}</code>```

    Header Header Header Header

    data
    data
    data
    data
    data
    data
    data
    data
    data
    data
    data

```

答:
EDIT 1

Look at the new live demo (based on comments and question change):

https://stackblitz.com/edit/js-e9cazg

```<code>    <table border="0" style="width: 96%; margin: 0 auto;">
        <tr class="header expand">
            <th>My Table Header Centered <span class="sign"></span></th>
        </tr>
        <tr>
            <td>
                <table style="width: 96%; margin: 0 auto;">
                    <tr>
                        <th>Col 1</th>
                        <th>Col 2</th>
                        <th>Col 3</th>
                        <th>Col 4</th>
                        <th>Col 5</th>
                        <th>Col 6</th>
                        <th>Col 7</th>
                        <th>Col 8</th>
                        <th>Col 9</th>
                        <th>Col 10</th>
                        <th>Col 11</th>
                    </tr>
                    <tr>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</code>```

I changed the style in the html table, take a look at this live demo: https://stackblitz.com/edit/js-n8yy6k

```<code><table border="0" style="width: 96%; margin: 0 auto;">
    <tr class="header expand">
        <th colspan="11">Header <span class="sign"></span></th>
    </tr>
    <tr>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
    </tr>
</table>
</code>```

I hope it's helpful.

Body:
I want to show my table header in the center of the web browser page. On pressing the + button the data is shown but it is aligned exactly below the table header. I want the collapsible table to be shown exactly in center of the table header. I tried changing in CSS but its not working out. Can anyone kindly help me out?

$('.header').click(function() {
  $(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);
});

table,
tr,
td,
th {
  border: 1px solid black;
  border-collapse: collapse;
}

tr.header {
  cursor: pointer;
}

.header .sign:after {
  content: "+";
  display: inline-block;
}

.header.expand .sign:after {
  content: "-";
}

table {
  margin-left: 30px;
}

    Header Header Header Header

    data
    data
    data
    data
    data
    data
    data
    data
    data
    data
    data

Body:
EDIT 1

Look at the new live demo (based on comments and question change):

https://stackblitz.com/edit/js-e9cazg

    <table border="0" style="width: 96%; margin: 0 auto;">
        <tr class="header expand">
            <th>My Table Header Centered <span class="sign"></span></th>
        </tr>
        <tr>
            <td>
                <table style="width: 96%; margin: 0 auto;">
                    <tr>
                        <th>Col 1</th>
                        <th>Col 2</th>
                        <th>Col 3</th>
                        <th>Col 4</th>
                        <th>Col 5</th>
                        <th>Col 6</th>
                        <th>Col 7</th>
                        <th>Col 8</th>
                        <th>Col 9</th>
                        <th>Col 10</th>
                        <th>Col 11</th>
                    </tr>
                    <tr>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                        <td>data</td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>

I changed the style in the html table, take a look at this live demo: https://stackblitz.com/edit/js-n8yy6k

<table border="0" style="width: 96%; margin: 0 auto;">
    <tr class="header expand">
        <th colspan="11">Header <span class="sign"></span></th>
    </tr>
    <tr>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
    </tr>
</table>

I hope it's helpful.