问:
How do i pre load all the sounds that I need in a Pygame game, dynamically in a trie structure?
Pygame cannot open files

I tried to open files 'with open as', with wave.open as' open single file without creating a dictionary. like sound = Pygame.mixer.Sound('sounds/example.wav') after the Pygame.mixer.init()

spy_vs_spy.py

```<code>import pygame
import settings
import game_functions as gf
import resources
import sounds
from spy_white import Spy_white
from spy_black import Spy_black
from settings import Settings

def run_game():

    # Initialize pygame, settings, and screen object.
    pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096)
    pygame.init() #turn all of pygame on.
    pygame.mixer.init()
    print(pygame.mixer.get_init())
    ai_settings = Settings()
    screen = pygame.display.set_mode(
            (ai_settings.screen_width, ai_settings.screen_height),
            pygame.HWSURFACE|pygame.DOUBLEBUF)
    pygame.display.set_caption("Spy vs Spy 2019")
    resources.load_images(ai_settings, screen)
    resources.load_sounds()

    # Make Spy white.
    spy_white = Spy_white(ai_settings, screen)

    # Make Spy black.
    spy_black = Spy_black(ai_settings, screen)

    # Start music
    sounds.play_music()

    # Start the main loop for the game.
    while True:
        gf.check_events(spy_white, spy_black)
        spy_white.update()
        spy_black.update()
        gf.update_screen(ai_settings, screen, spy_white, spy_black)

run_game()
</code>```

resources.py

```<code>sound_library = {}

def load_sounds():

    global sound_library

    """Load all sounds from subdirectories in a dictionary"""
    for dirpath, dirnames, filenames in os.walk('sounds'):
        for name in filenames:
            if name.endswith('.wav'):
                key = name[:-4]
                snd = pygame.mixer.Sound(os.path.join(dirpath, name))
                sound_library[key] = snd

    for sound in sound_library:
        print(sound)

    print(sound_library)
</code>```

I intended to pre load all wav files as a sound in a dictionary, so I can call the sound by event just by giving the key in the sound library dictionary. and then execute resources.sound_library['sound_to_play'].play()

Traceback (most recent call last): File "/Users/ruudkooistra/Desktop/project_folder/spy_vs_spy_2019/spy_vs_spy.py", line 42, in  run_game() File "/Users/ruudkooistra/Desktop/project_folder/spy_vs_spy_2019/spy_vs_spy.py", line 24, in run_game resources.load_sounds() File "/Users/ruudkooistra/Desktop/project_folder/spy_vs_spy_2019/resources.py", line 36, in load_sounds snd = pygame.mixer.Sound(os.path.join(dirpath, name)) pygame.error: Unable to open file 'sounds/spy_fly.wav' [Finished in 1.3s with exit code 1]

[cmd: ['/usr/local/bin/python3', '-u', '/Users/ruudkooistra/Desktop/project_folder/spy_vs_spy_2019/spy_vs_spy.py']] [dir: /Users/ruudkooistra/Desktop/project_folder/spy_vs_spy_2019] [path: /Library/Frameworks/Python.framework/Versions/3.7/bin:/Users/ruudkooistra/anaconda3/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin]

when i change the code as below, the pygame.mixer.music.load(file) and .play() works but Pygame.mixer.Sound(file) still does not. By the way there are links to the file stored in dictionary when I do it this way and I want to store the data dynamically in the heap in a trie structure. But I am a newbie and maybe there are better ways to handle sounds in a game with Pygame. It works fine with images.

def load_sounds():

```<code>global sound_library

"""Load all sounds from subdirectories in a dictionary"""
for dirpath, dirnames, filenames in os.walk('sounds'):
    for name in filenames:
        if name.endswith('.wav'):
            key = name[:-4]
            snd = os.path.join(dirpath, name)
            sound_library[key] = snd

for sound in sound_library:
    print(sound)

print(sound_library)
</code>```

spy_fly
electrified
time_bomb_countdown
wave_stick
search_01
time_bomb_explode
beat
timer_01
pistol_trap_set
pistol_trapped
hit
bomb_explode
walking
spy_vs_spy_theme
found_item
trap_set
lift_off
door
spy_angel
{'spy_fly': 'sounds/spy_fly.wav', 'electrified': 'sounds/electrified.wav', 'time_bomb_countdown': 'sounds/time_bomb_countdown.wav', 'wave_stick': 'sounds/wave_stick.wav', 'search_01': 'sounds/search_01.wav', 'time_bomb_explode': 'sounds/time_bomb_explode.wav', 'beat': 'sounds/beat.wav', 'timer_01': 'sounds/timer_01.wav', 'pistol_trap_set': 'sounds/pistol_trap_set.wav', 'pistol_trapped': 'sounds/pistol_trapped.wav', 'hit': 'sounds/hit.wav', 'bomb_explode': 'sounds/bomb_explode.wav', 'walking': 'sounds/walking.wav', 'spy_vs_spy_theme': 'sounds/spy_vs_spy_theme.wav', 'found_item': 'sounds/found_item.wav', 'trap_set': 'sounds/trap_set.wav', 'lift_off': 'sounds/lift_off.wav', 'door': 'sounds/door.wav', 'spy_angel': 'sounds/spy_angel.wav'}

答:
Yes I found da way, now everything works as it should and I can use pygame.mixer.Sound().play() or pygame.mixer.music.load().play() wherever I want:

resources.py
import os
import pygame as pg

sound_library = {}

def load_sounds():

```<code>global sound_library

"""Load all sounds from subdirectories in a dictionary"""
for dirpath, dirnames, filenames in os.walk('sounds'):
    for name in filenames:
        if name.endswith('.wav'):
            key = name[:-4]
            with open(os.path.join(dirpath, name), "rb") as file:
                buffer = file.read()
                sound_library[key] = buffer

for sound in sound_library:
    print(sound)
</code>```

Body:
Pygame cannot open files

I tried to open files 'with open as', with wave.open as' open single file without creating a dictionary. like sound = Pygame.mixer.Sound('sounds/example.wav') after the Pygame.mixer.init()

spy_vs_spy.py

import pygame
import settings
import game_functions as gf
import resources
import sounds
from spy_white import Spy_white
from spy_black import Spy_black
from settings import Settings

def run_game():

    # Initialize pygame, settings, and screen object.
    pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096)
    pygame.init() #turn all of pygame on.
    pygame.mixer.init()
    print(pygame.mixer.get_init())
    ai_settings = Settings()
    screen = pygame.display.set_mode(
            (ai_settings.screen_width, ai_settings.screen_height),
            pygame.HWSURFACE|pygame.DOUBLEBUF)
    pygame.display.set_caption("Spy vs Spy 2019")
    resources.load_images(ai_settings, screen)
    resources.load_sounds()

    # Make Spy white.
    spy_white = Spy_white(ai_settings, screen)

    # Make Spy black.
    spy_black = Spy_black(ai_settings, screen)

    # Start music
    sounds.play_music()

    # Start the main loop for the game.
    while True:
        gf.check_events(spy_white, spy_black)
        spy_white.update()
        spy_black.update()
        gf.update_screen(ai_settings, screen, spy_white, spy_black)

run_game()

resources.py

sound_library = {}

def load_sounds():

    global sound_library

    """Load all sounds from subdirectories in a dictionary"""
    for dirpath, dirnames, filenames in os.walk('sounds'):
        for name in filenames:
            if name.endswith('.wav'):
                key = name[:-4]
                snd = pygame.mixer.Sound(os.path.join(dirpath, name))
                sound_library[key] = snd

    for sound in sound_library:
        print(sound)

    print(sound_library)

I intended to pre load all wav files as a sound in a dictionary, so I can call the sound by event just by giving the key in the sound library dictionary. and then execute resources.sound_library['sound_to_play'].play()

Traceback (most recent call last): File "/Users/ruudkooistra/Desktop/project_folder/spy_vs_spy_2019/spy_vs_spy.py", line 42, in  run_game() File "/Users/ruudkooistra/Desktop/project_folder/spy_vs_spy_2019/spy_vs_spy.py", line 24, in run_game resources.load_sounds() File "/Users/ruudkooistra/Desktop/project_folder/spy_vs_spy_2019/resources.py", line 36, in load_sounds snd = pygame.mixer.Sound(os.path.join(dirpath, name)) pygame.error: Unable to open file 'sounds/spy_fly.wav' [Finished in 1.3s with exit code 1]

[cmd: ['/usr/local/bin/python3', '-u', '/Users/ruudkooistra/Desktop/project_folder/spy_vs_spy_2019/spy_vs_spy.py']] [dir: /Users/ruudkooistra/Desktop/project_folder/spy_vs_spy_2019] [path: /Library/Frameworks/Python.framework/Versions/3.7/bin:/Users/ruudkooistra/anaconda3/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin]

when i change the code as below, the pygame.mixer.music.load(file) and .play() works but Pygame.mixer.Sound(file) still does not. By the way there are links to the file stored in dictionary when I do it this way and I want to store the data dynamically in the heap in a trie structure. But I am a newbie and maybe there are better ways to handle sounds in a game with Pygame. It works fine with images.

def load_sounds():

global sound_library

"""Load all sounds from subdirectories in a dictionary"""
for dirpath, dirnames, filenames in os.walk('sounds'):
    for name in filenames:
        if name.endswith('.wav'):
            key = name[:-4]
            snd = os.path.join(dirpath, name)
            sound_library[key] = snd

for sound in sound_library:
    print(sound)

print(sound_library)

spy_fly
electrified
time_bomb_countdown
wave_stick
search_01
time_bomb_explode
beat
timer_01
pistol_trap_set
pistol_trapped
hit
bomb_explode
walking
spy_vs_spy_theme
found_item
trap_set
lift_off
door
spy_angel
{'spy_fly': 'sounds/spy_fly.wav', 'electrified': 'sounds/electrified.wav', 'time_bomb_countdown': 'sounds/time_bomb_countdown.wav', 'wave_stick': 'sounds/wave_stick.wav', 'search_01': 'sounds/search_01.wav', 'time_bomb_explode': 'sounds/time_bomb_explode.wav', 'beat': 'sounds/beat.wav', 'timer_01': 'sounds/timer_01.wav', 'pistol_trap_set': 'sounds/pistol_trap_set.wav', 'pistol_trapped': 'sounds/pistol_trapped.wav', 'hit': 'sounds/hit.wav', 'bomb_explode': 'sounds/bomb_explode.wav', 'walking': 'sounds/walking.wav', 'spy_vs_spy_theme': 'sounds/spy_vs_spy_theme.wav', 'found_item': 'sounds/found_item.wav', 'trap_set': 'sounds/trap_set.wav', 'lift_off': 'sounds/lift_off.wav', 'door': 'sounds/door.wav', 'spy_angel': 'sounds/spy_angel.wav'}

Body:
Yes I found da way, now everything works as it should and I can use pygame.mixer.Sound().play() or pygame.mixer.music.load().play() wherever I want:

resources.py
import os
import pygame as pg

sound_library = {}

def load_sounds():

global sound_library

"""Load all sounds from subdirectories in a dictionary"""
for dirpath, dirnames, filenames in os.walk('sounds'):
    for name in filenames:
        if name.endswith('.wav'):
            key = name[:-4]
            with open(os.path.join(dirpath, name), "rb") as file:
                buffer = file.read()
                sound_library[key] = buffer

for sound in sound_library:
    print(sound)


来源: stackexchange

答:
With org.json ,

```<code>  JSONArray jSONArray = new JSONArray("your input array");
  int length = jSONArray.length();
  for (int i = 0; i < length; i++) {
        JSONObject jSONObject= jSONArray.getJSONObject(i);
        System.out.println(jSONObject.get("docmanId"));
        System.out.println(jSONObject.get("dz"));
    }
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to get each value from JSON string

Body:
I have this JSON String and I need to get each docmanId and each dz so,I could loop through them and work with them.

I have tried using gson library to do that,but I dont seem to figure it out.

JSON Array :

[{"docmanId":1,"dz":"CR"},
{"docmanId":1,"dz":"EU"},
{"docmanId":1,"dz":"JD"},
{"docmanId":1,"dz":"LT"},
{"docmanId":10,"dz":"CR"},
{"docmanId":10,"dz":"EU"},
{"docmanId":10,"dz":"LT"},
{"docmanId":100,"dz":"CR"},
{"docmanId":100,"dz":"EU"},
{"docmanId":100,"dz":"JD"},
{"docmanId":100,"dz":"LT"},
{"docmanId":1000,"dz":"CR"},
{"docmanId":1000,"dz":"EU"},
{"docmanId":1000,"dz":"JD"},
{"docmanId":1000,"dz":"LT"},
{"docmanId":10000,"dz":"ES"},
{"docmanId":10000,"dz":"EU"},
{"docmanId":10000,"dz":"JD"},
{"docmanId":100000,"dz":"CR"},
{"docmanId":100000,"dz":"EU"},
{"docmanId":100000,"dz":"JD"},
{"docmanId":100000,"dz":"LT"},
{"docmanId":100001,"dz":"CR"},
{"docmanId":100001,"dz":"EU"},
{"docmanId":100001,"dz":"LT"},
{"docmanId":100002,"dz":"CR"},
{"docmanId":100002,"dz":"EU"},
{"docmanId":100002,"dz":"JD"},
{"docmanId":100003,"dz":"CR"},
{"docmanId":100003,"dz":"EU"},
{"docmanId":100003,"dz":"JD"},
{"docmanId":100003,"dz":"LT"},
{"docmanId":100004,"dz":"CR"},
{"docmanId":100004,"dz":"EU"},
{"docmanId":100004,"dz":"JD"},
{"docmanId":100005,"dz":"CR"},
{"docmanId":100005,"dz":"EU"},
{"docmanId":100005,"dz":"JD"},
{"docmanId":100005,"dz":"LT"},
{"docmanId":100006,"dz":"CR"},
{"docmanId":100006,"dz":"EU"},
{"docmanId":100006,"dz":"JD"},
{"docmanId":100006,"dz":"LT"},
{"docmanId":100007,"dz":"CR"},
{"docmanId":100007,"dz":"EU"},
{"docmanId":100007,"dz":"JD"}]

Body:
With org.json ,

  JSONArray jSONArray = new JSONArray("your input array");
  int length = jSONArray.length();
  for (int i = 0; i < length; i++) {
        JSONObject jSONObject= jSONArray.getJSONObject(i);
        System.out.println(jSONObject.get("docmanId"));
        System.out.println(jSONObject.get("dz"));
    }


问:
Install4j running Executable not using environment variables
I am trying to run a groovy script using Install4j. I have laid down the files for groovy and added to an environment variable "Groovy_Home". Then I added that to the Path Environment Variable. When I open the command window I am able to run "Groovy buildenv.groovy". It works! Almost magically! However when I use Install4j to create the .bat file that has a working dir of the .groovy file and runs this script:

```<code>@echo on

groovy buildenv.groovy > buildenv.output.log
</code>```

It doesn't seem to work! it complains that it has no idea where the groovy is at. I have added the "Specific environment variables" to "PATH=${PATH}". But that doesn't seem to work either... Any help is greatly appreciated.

答:
The solution for me was to use Specific environment variables as you told, but not setting PATH=${PATH} (what it does if path is already set?).

Instead in the installer process I add a step of Directory selection type to let user choose the directory where groovy is installed, and use the user entry to set a installer variable. Then I use this variable in the Specific environment variables property of the Run executable or batch file action to set something like PATH=${installer:userGroovyHome}, where userGroovyHome is the Variable name for selection property of Directory selection

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run a groovy script using Install4j. I have laid down the files for groovy and added to an environment variable "Groovy_Home". Then I added that to the Path Environment Variable. When I open the command window I am able to run "Groovy buildenv.groovy". It works! Almost magically! However when I use Install4j to create the .bat file that has a working dir of the .groovy file and runs this script:

@echo on

groovy buildenv.groovy > buildenv.output.log

It doesn't seem to work! it complains that it has no idea where the groovy is at. I have added the "Specific environment variables" to "PATH=${PATH}". But that doesn't seem to work either... Any help is greatly appreciated.


问:
How to update text element after property change in Polymer 3?
So I'm using a data table which has an active element. When that active elment changes I store the name of the active element in a property of my polymer element. Then I display this String property in a div.
Now I know for certain that the property change works, because I console.log it after a change, the div displaying the property doesn't update and continually displays the default value I have set.

```<code>export class ProjectsOverview extends PolymerElement {
  static get template() {
      return html`
         ...
         <div>{{currentProject}}</div>
         ...
      `
  }

  static get properties() {
      return {
        currentProject: {
          type: String,
          value: "placeholder",
          notify: true,
          reflectToAttribute: true
        }
      };
  }

  connectedCallback() {
      super.connectedCallback();

      const grid = this.shadowRoot.querySelector('vaadin-grid');

      grid.addEventListener('active-item-changed', function(event) {
        const item = event.detail.value;

        grid.selectedItems = [item];
        if (item) {
          this.set('currentProject', item.name);
        } else {
          this.set('currentProject', '');
        }
        console.log(this.currentProject);
      });
  }
}
</code>```

My expected result would be that every time the currentProject property is updated, the div displaying the property updates as well.

答:
Your scope is wrong. You're using an anonymous function so when you try to set currentProject, you do that when your this is your anonymous function. Use .bind(this) to fix your problem.

```<code>grid.addEventListener('active-item-changed', function(event) {
        const item = event.detail.value;

        grid.selectedItems = [item];
        if (item) {
          this.set('currentProject', item.name);
        } else {
          this.set('currentProject', '');
        }
        console.log(this.currentProject);
      }.bind(this));
</code>```

Body:
So I'm using a data table which has an active element. When that active elment changes I store the name of the active element in a property of my polymer element. Then I display this String property in a div.
Now I know for certain that the property change works, because I console.log it after a change, the div displaying the property doesn't update and continually displays the default value I have set.

export class ProjectsOverview extends PolymerElement {
  static get template() {
      return html`
         ...

{{currentProject}}

         ...
      `
  }

  static get properties() {
      return {
        currentProject: {
          type: String,
          value: "placeholder",
          notify: true,
          reflectToAttribute: true
        }
      };
  }

  connectedCallback() {
      super.connectedCallback();

      const grid = this.shadowRoot.querySelector('vaadin-grid');

      grid.addEventListener('active-item-changed', function(event) {
        const item = event.detail.value;

        grid.selectedItems = [item];
        if (item) {
          this.set('currentProject', item.name);
        } else {
          this.set('currentProject', '');
        }
        console.log(this.currentProject);
      });
  }
}

My expected result would be that every time the currentProject property is updated, the div displaying the property updates as well.

Body:
Your scope is wrong. You're using an anonymous function so when you try to set currentProject, you do that when your this is your anonymous function. Use .bind(this) to fix your problem.

grid.addEventListener('active-item-changed', function(event) {
        const item = event.detail.value;

        grid.selectedItems = [item];
        if (item) {
          this.set('currentProject', item.name);
        } else {
          this.set('currentProject', '');
        }
        console.log(this.currentProject);
      }.bind(this));


问:
Why is my CSS selector not working with beautifulsoup but works fine as a chrome console query?
I have a css selector that works fine when executing it in the chrome JS Console, but does not work when running it through beautifulsoup on one example, yet works on another (I'm unable to discern the difference between the two).

```<code>url_1 = 'https://www.amazon.com/s?k=bacopa&page=1'
url_2 = 'https://www.amazon.com/s?k=acorus+calamus&page=1'
</code>```

The following query works fine on both when executing it in the chrome console.

```<code>document.querySelectorAll('div.s-result-item')
</code>```

Then running the two urls through beautifulsoup, this is the output I get.

url_1 (works)

```<code>headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
r = requests.get(url_1, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
listings = soup .select('div.s-result-item')
print(len(listings))
</code>```

output: 53 (correct)

url_2 (does not work)

```<code>headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
r = requests.get(url_2, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
listings = soup.select('div.s-result-item')
print(len(listings))
</code>```

output: 0 (incorrect - expected: 49)

Does anyone know what might be going on here and how I can get the css selector to work with beautifulsoup?

答:
Try selenium library to download the webpage

```<code>from selenium import webdriver
from bs4 import BeautifulSoup

url_1 = 'https://www.amazon.com/s?k=bacopa&page=1'
url_2 = 'https://www.amazon.com/s?k=acorus+calamus&page=1'

#set chrome webdriver path
driver = webdriver.Chrome('/usr/bin/chromedriver')

#download webpage
driver.get(url_2)

soup = BeautifulSoup(driver.page_source, 'html.parser')
listings = soup.find_all('div',{'class':'s-result-item'})

print(len(listings))
</code>```

O/P:

```<code>url_1: 50

url_2 : 48
</code>```

Body:
I have a css selector that works fine when executing it in the chrome JS Console, but does not work when running it through beautifulsoup on one example, yet works on another (I'm unable to discern the difference between the two).

url_1 = 'https://www.amazon.com/s?k=bacopa&page=1'
url_2 = 'https://www.amazon.com/s?k=acorus+calamus&page=1'

The following query works fine on both when executing it in the chrome console.

document.querySelectorAll('div.s-result-item')

Then running the two urls through beautifulsoup, this is the output I get.

url_1 (works)

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
r = requests.get(url_1, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
listings = soup .select('div.s-result-item')
print(len(listings))

output: 53 (correct)

url_2 (does not work)

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
r = requests.get(url_2, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
listings = soup.select('div.s-result-item')
print(len(listings))

output: 0 (incorrect - expected: 49)

Does anyone know what might be going on here and how I can get the css selector to work with beautifulsoup?

Body:
Try selenium library to download the webpage

from selenium import webdriver
from bs4 import BeautifulSoup

url_1 = 'https://www.amazon.com/s?k=bacopa&page=1'
url_2 = 'https://www.amazon.com/s?k=acorus+calamus&page=1'

#set chrome webdriver path
driver = webdriver.Chrome('/usr/bin/chromedriver')

#download webpage
driver.get(url_2)

soup = BeautifulSoup(driver.page_source, 'html.parser')
listings = soup.find_all('div',{'class':'s-result-item'})

print(len(listings))

O/P:

url_1: 50

url_2 : 48


问:
Changing admin password on wso2 api manager results in errors when calling the published APIs
I have a simple setup of WSO2 APIM with MYSQL and have published APIs using the admin user.

On changing the default admin password for API manager I am able to login using the new password on Publisher/Store but not use the published apis.

Have followed the WSO2 documentation on changing the password. Restarted the WSO2 APIM

On calling the published API, I see the following response:

```<code>{"fault":{"code":900900,"message":"Unclassified Authentication Failure","description":"Error while accessing backend services for API key validation"}}
</code>```

Below is the stacktrace of the error observed in wso2-apigw-errors.log:

```<code>org.wso2.carbon.databridge.agent.exception.DataEndpointLoginException: Cannot borrow client for ssl://10.93.16.127:9711.
    at org.wso2.carbon.databridge.agent.endpoint.DataEndpointConnectionWorker.connect(DataEndpointConnectionWorker.java:134)
    at org.wso2.carbon.databridge.agent.endpoint.DataEndpointConnectionWorker.run(DataEndpointConnectionWorker.java:59)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.wso2.carbon.databridge.agent.exception.DataEndpointLoginException: Error while trying to login to data receiver :/10.93.16.127:9711
    at org.wso2.carbon.databridge.agent.endpoint.binary.BinaryDataEndpoint.login(BinaryDataEndpoint.java:50)
    at org.wso2.carbon.databridge.agent.endpoint.DataEndpointConnectionWorker.connect(DataEndpointConnectionWorker.java:128)
    ... 6 more
Caused by: org.wso2.carbon.databridge.commons.exception.AuthenticationException: wrong userName or password
    at sun.reflect.GeneratedConstructorAccessor194.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.wso2.carbon.databridge.agent.endpoint.binary.BinaryEventSender.processResponse(BinaryEventSender.java:163)
    at org.wso2.carbon.databridge.agent.endpoint.binary.BinaryDataEndpoint.login(BinaryDataEndpoint.java:44)
    ... 7 more
</code>```

This error goes away as soon as I change the password back to the default "admin".

答:
Please check if you have correct password here.</p>

```<code><ThrottlingConfigurations>
    <EnableAdvanceThrottling>true</EnableAdvanceThrottling>
    <TrafficManager>
        <Type>Binary</Type>
        <ReceiverUrlGroup>tcp://${carbon.local.ip}:${receiver.url.port}</ReceiverUrlGroup>
        <AuthUrlGroup>ssl://${carbon.local.ip}:${auth.url.port}</AuthUrlGroup>
        <Username>admin</Username>
        <Password>admin</Password>
    </TrafficManager>
</code>```

Body:
I have a simple setup of WSO2 APIM with MYSQL and have published APIs using the admin user.

On changing the default admin password for API manager I am able to login using the new password on Publisher/Store but not use the published apis.

Have followed the WSO2 documentation on changing the password. Restarted the WSO2 APIM

On calling the published API, I see the following response:

{"fault":{"code":900900,"message":"Unclassified Authentication Failure","description":"Error while accessing backend services for API key validation"}}

Below is the stacktrace of the error observed in wso2-apigw-errors.log:

org.wso2.carbon.databridge.agent.exception.DataEndpointLoginException: Cannot borrow client for ssl://10.93.16.127:9711.
    at org.wso2.carbon.databridge.agent.endpoint.DataEndpointConnectionWorker.connect(DataEndpointConnectionWorker.java:134)
    at org.wso2.carbon.databridge.agent.endpoint.DataEndpointConnectionWorker.run(DataEndpointConnectionWorker.java:59)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.wso2.carbon.databridge.agent.exception.DataEndpointLoginException: Error while trying to login to data receiver :/10.93.16.127:9711
    at org.wso2.carbon.databridge.agent.endpoint.binary.BinaryDataEndpoint.login(BinaryDataEndpoint.java:50)
    at org.wso2.carbon.databridge.agent.endpoint.DataEndpointConnectionWorker.connect(DataEndpointConnectionWorker.java:128)
    ... 6 more
Caused by: org.wso2.carbon.databridge.commons.exception.AuthenticationException: wrong userName or password
    at sun.reflect.GeneratedConstructorAccessor194.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.wso2.carbon.databridge.agent.endpoint.binary.BinaryEventSender.processResponse(BinaryEventSender.java:163)
    at org.wso2.carbon.databridge.agent.endpoint.binary.BinaryDataEndpoint.login(BinaryDataEndpoint.java:44)
    ... 7 more

This error goes away as soon as I change the password back to the default "admin".

Body:
Please check if you have correct password here.

<ThrottlingConfigurations>
    <EnableAdvanceThrottling>true</EnableAdvanceThrottling>
    <TrafficManager>
        <Type>Binary</Type>
        <ReceiverUrlGroup>tcp://${carbon.local.ip}:${receiver.url.port}</ReceiverUrlGroup>
        <AuthUrlGroup>ssl://${carbon.local.ip}:${auth.url.port}</AuthUrlGroup>
        <Username>admin</Username>
        <Password>admin</Password>
    </TrafficManager>


问:
Java ClassNotFound Exception
My application tries to execute the following line of code

```
<code>
JMFSecurity jmfSecurity = JMFSecurityManager.getJMFSecurity();
</code>
```

That line throws the following exception. Here is a stack trace:

```
<code>
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/media/JMFSecurityManager
        at com.compunetix.vsd.stix.main.JMFUtilities.Registry.(Registry.java:71)
        at com.compunetix.vsd.stix.main.JMFUtilities.JMFRunner.getJMFPropertiesFileLocation(JMFRunner.java:129)
        at com.compunetix.vsd.stix.main.Main.setUpJMF(Main.java:274)
        at com.compunetix.vsd.stix.main.Main.main(Main.java:166)
Caused by: java.lang.ClassNotFoundException: com.sun.media.JMFSecurityManager
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
        ... 4 more
</code>
```

Any ideas why this might be throwing an exception. This used to work fine. I didn't make any changes to this file. Any ideas?

答: As the stack trace states, the class com.sun.media.JMFSecurityManager is not found. It's presumably missing from your classpath, so check this.

Title: Java ClassNotFound Exception

Body:
My application tries to execute the following line of code

JMFSecurity jmfSecurity = JMFSecurityManager.getJMFSecurity();

That line throws the following exception. Here is a stack trace:

Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/media/JMFSecurityManager
        at com.compunetix.vsd.stix.main.JMFUtilities.Registry.(Registry.java:71)
        at com.compunetix.vsd.stix.main.JMFUtilities.JMFRunner.getJMFPropertiesFileLocation(JMFRunner.java:129)
        at com.compunetix.vsd.stix.main.Main.setUpJMF(Main.java:274)
        at com.compunetix.vsd.stix.main.Main.main(Main.java:166)
Caused by: java.lang.ClassNotFoundException: com.sun.media.JMFSecurityManager
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
        ... 4 more

Any ideas why this might be throwing an exception. This used to work fine. I didn't make any changes to this file. Any ideas?


问:
Assigning a function call to a variable in Kotlin
Does assigning a variable to a function call actually call the function then or just store it (so it's ready to be called)?

For example does:

```<code>val userData = GraphRequest.newMeRequest(
    accessToken,
    object : GraphRequest.GraphJSONObjectCallback {
        override fun onCompleted(`object`: JSONObject?, response: GraphResponse?) {
            Log.d(TAG, `object`.toString())
        }

    }
)
</code>```

actually call GraphRequest.newMeRequest()?

答:
Yes, that will call the GraphRequest.newMeRequest(..) method and assign the result to userData immediately. If you want the field to be initialized at a later time, but only when the field is first accessed, use a lazy delegate.

```<code>val userData by lazy { /* call method */ }
</code>```

Body:
Does assigning a variable to a function call actually call the function then or just store it (so it's ready to be called)?

For example does:

val userData = GraphRequest.newMeRequest(
    accessToken,
    object : GraphRequest.GraphJSONObjectCallback {
        override fun onCompleted(`object`: JSONObject?, response: GraphResponse?) {
            Log.d(TAG, `object`.toString())
        }

    }
)

actually call GraphRequest.newMeRequest()?

Body:
Yes, that will call the GraphRequest.newMeRequest(..) method and assign the result to userData immediately. If you want the field to be initialized at a later time, but only when the field is first accessed, use a lazy delegate.

val userData by lazy { /* call method */ }


问:
Can't interact with window during a Method is working C#
If I start a Method which needs 5s until it is finished. It works perfectly. BUT, During this Time I can't interact with the Window.

For example:
You want a user of this program to start a Method which opens with Selenium a Webside and search 100 websites which include the name "Code".. and this needs 100s. But during this time you can't interact with the user-Interface, you can't close it.

Window:

For Example :

```<code>driver.Navigate().GoToUrl(url);
().Window.Maximize();
Thread.Sleep(3000);
</code>```

Thank you

答:
You application runs currently in a single thread. That means it can work on  one thing at the same time. In this case, handle interactions with your Window or execute your long running code.

One possible option, would be to execute your long running code on a separate thread. More info in this article.

C# has a perfect solution for executing work in background - Tasks. I recommend you using Tasks instead of Threads for small tasks. Tasks class lets you create tasks and run them asynchronously. A task is an object that represents some work that should be done. The task can tell you if the work is completed and if the operation returns a result, the task gives you the result.

To create a task and run it, you simply pass your Action as argument to StartNew method:

```<code>Task.Factory.StartNew(() => {
    driver.Navigate().GoToUrl(url);
    driver.Manage().Window.Maximize();
    Thread.Sleep(3000);
});
</code>```

Other ways of starting a Task here.

You can read more about Tasks in this msdn article

Body:
If I start a Method which needs 5s until it is finished. It works perfectly. BUT, During this Time I can't interact with the Window.

For example:
You want a user of this program to start a Method which opens with Selenium a Webside and search 100 websites which include the name "Code".. and this needs 100s. But during this time you can't interact with the user-Interface, you can't close it.

Window:

For Example :

driver.Navigate().GoToUrl(url);
().Window.Maximize();
Thread.Sleep(3000);

Thank you

Body:
You application runs currently in a single thread. That means it can work on  one thing at the same time. In this case, handle interactions with your Window or execute your long running code.

One possible option, would be to execute your long running code on a separate thread. More info in this article.

C# has a perfect solution for executing work in background - Tasks. I recommend you using Tasks instead of Threads for small tasks. Tasks class lets you create tasks and run them asynchronously. A task is an object that represents some work that should be done. The task can tell you if the work is completed and if the operation returns a result, the task gives you the result.

To create a task and run it, you simply pass your Action as argument to StartNew method:

Task.Factory.StartNew(() => {
    driver.Navigate().GoToUrl(url);
    driver.Manage().Window.Maximize();
    Thread.Sleep(3000);
});

Other ways of starting a Task here.

You can read more about Tasks in this msdn article


问:
Custom filter for table from two different calls
My current situation is that I make 2 get calls via Axios and I receive two different files. First call is complete json file that builds the table and second is only categories (Why? Complicated app is complicated. It is slowly getting upgraded from old framework). I create two dropdowns - first one is populated with years which also builds the table. Second dropdown is populated with categories. When application loads, table is loaded for current year.

My question: How should I create my custom computed filter that would filter the table and show only rows with the selected category(from the second dropdown). So If I select 2019 from first dropdown all the tables are loaded. And after that if I select let's say "Name" in category dropdown, table updates and shows only rows which have "Name" in them. I tried different options but I cannot wrap my head around this one.

My current code:

```<code>data() {
 return {
  year:[],
  category:[] ,
  tableData:[],
 }
},

computed: {
 axiosParams(){
  const params = new URLSearchParams();
  params.append('year', this.year);
  return params;
 },

methods: {
 getYears: function(){
  axios.get('myUrl', {
    params: this.axiosParams
     }).then((response) => {
    this.year = response.data;
    console.log(response.data)
    this.tableData = response.data.result;
   })
   .catch((err) => {
    console.log(err);
  });
 },

 getCategory: function(){
   let category = [];
   axios.get('mySecondUrl').then((response, i) => {
    this.category = response.data
    for (var i = 0; i < category.length; i++) {
     let catType = i
     this.catType = response.data[i].name;
     console.log(catType);
    }
  })
  .catch((err) => {
    console.log(err);
  })
 }
}
created: {
 this.getYears();
 this.getCategory();
}
</code>```

My HTML:

```<code><select v-model="selectedYear" @change="yearSelected">
 <option v-for="year in years" :key="year"> {{year}} </option>
</select>

<select v-model="selectedCat" >
 <option v-for="(item, index) in category" :item="item"
 :key="index" :value="item.name"> {{ item.name }} </option>
</select>
</code>```

答:
So, your tableData is an array of objects like this:

```<code>[
  {
    "category":"Name",
    "year":2019,
    "username":"test",
    "otherValues":[
      {
        "someVal":30,
        "otherVal":20
      },
    ]
  },
]
</code>```

and you need to filter the items in the array based on the selected category name. Fortunately javascript can do this quite easily for us. There are several methods you can use to deal with arrays but in this case I think the filter() method should serve quite well. There is some more info about it here.

Basically you need a new array that will display the selected data, or if nothing is selected, show the whole tableData array. This should be a computed property.

```<code>computed: {
  filteredTableData() {
    if (this.selectedCat !== null) {
      const filtered = this.tableData.filter(d => d.category === this.selectedCat)
      return filtered
    }
    return this.tableData
  },
}
</code>```

This is assuming when you initialise selectedCat in data you set it to null. Therefore when someone selects a category it will meet the 'if' condition and our const 'filtered' will be a new array of all the 'tableData' elements that meet our condition. If nothing is selected the whole tableData array is returned.

When you are accessing the 'tableData' in your template, presumably with a v-for="data in tableData" you will now have to use v-for="data in filteredTableData".

Body:
My current situation is that I make 2 get calls via Axios and I receive two different files. First call is complete json file that builds the table and second is only categories (Why? Complicated app is complicated. It is slowly getting upgraded from old framework). I create two dropdowns - first one is populated with years which also builds the table. Second dropdown is populated with categories. When application loads, table is loaded for current year.

My question: How should I create my custom computed filter that would filter the table and show only rows with the selected category(from the second dropdown). So If I select 2019 from first dropdown all the tables are loaded. And after that if I select let's say "Name" in category dropdown, table updates and shows only rows which have "Name" in them. I tried different options but I cannot wrap my head around this one.

My current code:

data() {
 return {
  year:[],
  category:[] ,
  tableData:[],
 }
},

computed: {
 axiosParams(){
  const params = new URLSearchParams();
  params.append('year', this.year);
  return params;
 },

methods: {
 getYears: function(){
  axios.get('myUrl', {
    params: this.axiosParams
     }).then((response) => {
    this.year = response.data;
    console.log(response.data)
    this.tableData = response.data.result;
   })
   .catch((err) => {
    console.log(err);
  });
 },

 getCategory: function(){
   let category = [];
   axios.get('mySecondUrl').then((response, i) => {
    this.category = response.data
    for (var i = 0; i < category.length; i++) {
     let catType = i
     this.catType = response.data[i].name;
     console.log(catType);
    }
  })
  .catch((err) => {
    console.log(err);
  })
 }
}
created: {
 this.getYears();
 this.getCategory();
}

My HTML:

<select v-model="selectedYear" @change="yearSelected">
 <option v-for="year in years" :key="year"> {{year}} </option>
</select>

<select v-model="selectedCat" >
 <option v-for="(item, index) in category" :item="item"
 :key="index" :value="item.name"> {{ item.name }} </option>
</select>

Body:
So, your tableData is an array of objects like this:

[
  {
    "category":"Name",
    "year":2019,
    "username":"test",
    "otherValues":[
      {
        "someVal":30,
        "otherVal":20
      },
    ]
  },
]

and you need to filter the items in the array based on the selected category name. Fortunately javascript can do this quite easily for us. There are several methods you can use to deal with arrays but in this case I think the filter() method should serve quite well. There is some more info about it here.

Basically you need a new array that will display the selected data, or if nothing is selected, show the whole tableData array. This should be a computed property.

computed: {
  filteredTableData() {
    if (this.selectedCat !== null) {
      const filtered = this.tableData.filter(d => d.category === this.selectedCat)
      return filtered
    }
    return this.tableData
  },
}

This is assuming when you initialise selectedCat in data you set it to null. Therefore when someone selects a category it will meet the 'if' condition and our const 'filtered' will be a new array of all the 'tableData' elements that meet our condition. If nothing is selected the whole tableData array is returned.

When you are accessing the 'tableData' in your template, presumably with a v-for="data in tableData" you will now have to use v-for="data in filteredTableData".


问:
How to read the mask of an image using opencv in python
I am working on this challenge called Carvana Segmentation in kaggle. The dataset consists of 5088 images, for each image there is a mask. For eg, the below is a single image (.jpg file) and its corresponding mask (.gif file).

I was able to read .jpg files using cv2, but not the .gif files. The syntax i used to read .gif file is

```<code> >>> image = cv2.imread('filename.gif',cv2.IMREAD_GRAYSCALE)
</code>```

When I try to print the image, returns None

```<code> >>> print(image) -> None
</code>```

Can someone suggest any other method, please

答:
Following this repo:
https://github.com/asharma327/Read_Gif_OpenCV_Python/blob/master/gif_to_pic.py

you can do the following to read the image

```<code>import cv2
import os

def convert_gif_to_frames(gif):

    # Initialize the frame number and create empty frame list
    frame_num = 0
    frame_list = []

    # Loop until there are frames left
    while True:
        try:
            # Try to read a frame. Okay is a BOOL if there are frames or not
            okay, frame = gif.read()
            # Append to empty frame list
            frame_list.append(frame)
            # Break if there are no other frames to read
            if not okay:
                break
            # Increment value of the frame number by 1
            frame_num += 1
        except KeyboardInterrupt:  # press ^C to quit
            break

    return frame_list

def output_frames_as_pics(frame_list):

    # Reduce the list of frames by half to make the list more managable
    frame_list_reduce = frame_list[0::2]
    # Get the path of the current working directory
    path = os.getcwd()
    # Set then name of your folder
    '''Replace this name with what you want your folder name to be'''
    folder_name = 'Picturebook_Pics_Kiss'
    # If the folder does not exist, then make it
    if not os.path.exists(path + '/' + folder_name):
        os.makedirs(path + '/' + folder_name)

    for frames_idx in range(len(frame_list_reduce)):
        cv2.imwrite(os.path.join(path + '/' + folder_name, str(frames_idx+1) + '.png'), frame_list_reduce[frames_idx])

    return

gif = cv2.VideoCapture('/home/ahmedramzy/Documents/gif/giphy.gif')
# here you can get the frames and work on it
xx = convert_gif_to_frames(gif_kiss)
# here if you want to write it on hard disk using imwrite
output_frames_as_pics(xx)
</code>```

Body:
I am working on this challenge called Carvana Segmentation in kaggle. The dataset consists of 5088 images, for each image there is a mask. For eg, the below is a single image (.jpg file) and its corresponding mask (.gif file).

I was able to read .jpg files using cv2, but not the .gif files. The syntax i used to read .gif file is

 >>> image = cv2.imread('filename.gif',cv2.IMREAD_GRAYSCALE)

When I try to print the image, returns None

 >>> print(image) -> None

Can someone suggest any other method, please

Body:
Following this repo:
https://github.com/asharma327/Read_Gif_OpenCV_Python/blob/master/gif_to_pic.py

you can do the following to read the image

import cv2
import os

def convert_gif_to_frames(gif):

    # Initialize the frame number and create empty frame list
    frame_num = 0
    frame_list = []

    # Loop until there are frames left
    while True:
        try:
            # Try to read a frame. Okay is a BOOL if there are frames or not
            okay, frame = gif.read()
            # Append to empty frame list
            frame_list.append(frame)
            # Break if there are no other frames to read
            if not okay:
                break
            # Increment value of the frame number by 1
            frame_num += 1
        except KeyboardInterrupt:  # press ^C to quit
            break

    return frame_list

def output_frames_as_pics(frame_list):

    # Reduce the list of frames by half to make the list more managable
    frame_list_reduce = frame_list[0::2]
    # Get the path of the current working directory
    path = os.getcwd()
    # Set then name of your folder
    '''Replace this name with what you want your folder name to be'''
    folder_name = 'Picturebook_Pics_Kiss'
    # If the folder does not exist, then make it
    if not os.path.exists(path + '/' + folder_name):
        os.makedirs(path + '/' + folder_name)

    for frames_idx in range(len(frame_list_reduce)):
        cv2.imwrite(os.path.join(path + '/' + folder_name, str(frames_idx+1) + '.png'), frame_list_reduce[frames_idx])

    return

gif = cv2.VideoCapture('/home/ahmedramzy/Documents/gif/giphy.gif')
# here you can get the frames and work on it
xx = convert_gif_to_frames(gif_kiss)
# here if you want to write it on hard disk using imwrite
output_frames_as_pics(xx)


问:
problem with function template parameter pack
Why does the following fail to compile?

```<code>inline Obj init_output_string() { return open_output_string(); }

template<typename... Args>
Obj init_output_string(Args... prev, int last)
{
    Obj port(init_output_string(prev...));
    write_char(port, last);
    return port;
}

int ch1 = ...;
int ch2 = ...;
Obj port = init_output_string(ch1, ch2);
</code>```

(error is 'init_output_string': no overloaded function takes 2 arguments for MSVC, g++ gives a similar error).

But the following variation does compile

```<code>inline Obj init_output_string() { return open_output_string(); }

template<typename... Args>
Obj init_output_string(int first, Args... rest)
{
    Obj port(init_output_string(rest...));
    write_char(port, first);
    return port;
}

int ch1 = ...;
int ch2 = ...;
Obj port = init_output_string(ch1, ch2);
</code>```

The difference being the order in which the characters are written. I can work around this easily enough, but I'm curious to know what rule my first example is breaking.

答:
Your construction is illformed.
see https://en.cppreference.com/w/cpp/language/parameter_pack

In a function template, the template parameter pack may appear earlier
  in the list provided that all following parameters can be deduced from
  the function arguments, or have default arguments:

the example given is(the latter in your case):

```<code>template<typename... Ts, typename U>
struct Invalid; // Error: Ts.. not at the end

template<typename ...Ts, typename U, typename=void>
void valid(U, Ts...);  // OK: can deduce U

// void valid(Ts..., U);
// Can't be used: Ts... is a non-deduced context in this position
</code>```

the problem is "how to deduce where to stop the int fro the pack"? is your last int part of the pack or not?

Imagine the compiler is just going thru the list of parameters and should directly know where to stop the pack.

Body:
Why does the following fail to compile?

inline Obj init_output_string() { return open_output_string(); }

template<typename... Args>
Obj init_output_string(Args... prev, int last)
{
    Obj port(init_output_string(prev...));
    write_char(port, last);
    return port;
}

int ch1 = ...;
int ch2 = ...;
Obj port = init_output_string(ch1, ch2);

(error is 'init_output_string': no overloaded function takes 2 arguments for MSVC, g++ gives a similar error).

But the following variation does compile

inline Obj init_output_string() { return open_output_string(); }

template<typename... Args>
Obj init_output_string(int first, Args... rest)
{
    Obj port(init_output_string(rest...));
    write_char(port, first);
    return port;
}

int ch1 = ...;
int ch2 = ...;
Obj port = init_output_string(ch1, ch2);

The difference being the order in which the characters are written. I can work around this easily enough, but I'm curious to know what rule my first example is breaking.

Body:
Your construction is illformed.
see https://en.cppreference.com/w/cpp/language/parameter_pack

In a function template, the template parameter pack may appear earlier
  in the list provided that all following parameters can be deduced from
  the function arguments, or have default arguments:

the example given is(the latter in your case):

template<typename... Ts, typename U>
struct Invalid; // Error: Ts.. not at the end

template<typename ...Ts, typename U, typename=void>
void valid(U, Ts...);  // OK: can deduce U

// void valid(Ts..., U);
// Can't be used: Ts... is a non-deduced context in this position

the problem is "how to deduce where to stop the int fro the pack"? is your last int part of the pack or not?

Imagine the compiler is just going thru the list of parameters and should directly know where to stop the pack.


问:
Create local backup when editing remote files via netrw in vim
I work with many files remotely using vim and the netrw plugin. I also keep timestamped backups by changing the &backupext (found in the documentation).

While working in a remote file (scp://server//folder/file.txt), I noticed that when I save it, a backup isn't even being made.

Is there a way I can have a backup automatically made locally (according to vim backup settings) every time I save a remote file?

答: I don't think there's a simple setting to toggle.  You could try to script something though - add your own BufWriteCmd autocommand to write a backup.  Try using set verbose=9 for debugging (and to see how netrw does it).

OwnerDisplayName: sirlancelot

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: rampion


问:
SharePoint 2007: Target Audience for Link Lists items
I created a Link List where each item has a specific target audience from the Active Directory group assigned. I added this link list on a page as a webpart. I am trying to get the user to ONLY be able to see the items on the list to which they have access to from the target audience field.</p>

答: audience targeting isn't really security trimming, its security by obscurity. What you're looking for is item level security. </p>


问:
Smart pointers cannot be used as raw pointers automatically?
I'm trying to convert codes to use smart pointers instead of raw pointers.  But was wondering - is it really not possible for smart pointers to be used as raw pointers?

In this example:

```<code>#include <iostream>
#include <string>
#include <memory>

void printer(int* x)
{
    std::cout << "x = " << x << std::endl;
}

int main()
{
    auto x = std::make_unique<int>(5);
    printer(x);
    return 0;
}
</code>```

I get an error:

```<code>In function 'int main()': 14:14: error: cannot convert
'std::unique_ptr<int, std::default_delete<int> >' to 'int*' for argument '1'
to 'void printer(int*)'
</code>```

How should this be coded?  Thanks!

答: std::make_unique<>() returns a std::unique_ptr, which makes variable x of type std::unique_ptr<int>. These smart pointers are not just raw pointers and you cannot use them just like raw pointers. You should instead use the get() method on x to get the int* it is pointing to.

Body:
I'm trying to convert codes to use smart pointers instead of raw pointers.  But was wondering - is it really not possible for smart pointers to be used as raw pointers?

In this example:

#include <iostream>
#include <string>
#include <memory>

void printer(int* x)
{
    std::cout << "x = " << x << std::endl;
}

int main()
{
    auto x = std::make_unique<int>(5);
    printer(x);
    return 0;
}

I get an error:

In function 'int main()': 14:14: error: cannot convert
'std::unique_ptr<int, std::default_delete<int> >' to 'int*' for argument '1'
to 'void printer(int*)'

How should this be coded?  Thanks!


问:
Error with setRequestHeader in GET request
The following JS function should be sending out a GET request to

http://127.0.0.1:5000/api.xml

with

?query=toast

```<code>function sendRequest(str){
    var request = new XMLHttpRequest();
    console.log('sending request');
    request.onreadystatechange = function() {
        if (request.readyState == XMLHttpRequest.DONE) {
            json=request.responseText;
            //json.forEach(function(obj) {
            //});
            for (word in json){
                var row=table.insertRow();
                var scoreC=row.insertCell();
                var wordC=row.insertCell();
                scoreC.innerHTML=json[word];
                wordC.innerHTML=word;
            }
        } else {
            concole.log("Silence on the line");
        }
    }
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    request.open('GET', 'http://127.0.0.1:5000/api.xml?query='+str, true);
    request.send();
  // and give it some content
    //var newContent = document.createTextNode(resp);
    //console.log(resp.responseType);
}
</code>```

Instead, it always queries

http://127.0.0.1:5000/?word=toast

ignoring the fact that I required a GET on

http://127.0.0.1:5000/api.xml

答:
Try this out</p>

```<code>function sendRequest(str) {
    const request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (this.readyState === 4) {
            if (this.status === 200) {
                console.log(this.responseText);
                const json = this.responseText;
                for (word in json) {
                    var row = table.insertRow();
                    var scoreC = row.insertCell();
                    var wordC = row.insertCell();
                    scoreC.innerHTML = json[word];
                    wordC.innerHTML = word;
                }
            } else if (this.response == null && this.status === 0) {
                console.log(this.responseText);
            } else {
                console.log('Error');
            }
        }
    };
    request.open('GET', 'http://127.0.0.1:5000/api.xml?query=' + str, true);
    request.send(null);
}
</code>```

Body:
The following JS function should be sending out a GET request to

http://127.0.0.1:5000/api.xml

with

?query=toast

function sendRequest(str){
    var request = new XMLHttpRequest();
    console.log('sending request');
    request.onreadystatechange = function() {
        if (request.readyState == XMLHttpRequest.DONE) {
            json=request.responseText;
            //json.forEach(function(obj) {
            //});
            for (word in json){
                var row=table.insertRow();
                var scoreC=row.insertCell();
                var wordC=row.insertCell();
                scoreC.innerHTML=json[word];
                wordC.innerHTML=word;
            }
        } else {
            concole.log("Silence on the line");
        }
    }
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    request.open('GET', 'http://127.0.0.1:5000/api.xml?query='+str, true);
    request.send();
  // and give it some content
    //var newContent = document.createTextNode(resp);
    //console.log(resp.responseType);
}

Instead, it always queries

http://127.0.0.1:5000/?word=toast

ignoring the fact that I required a GET on

http://127.0.0.1:5000/api.xml

Body:
Try this out

function sendRequest(str) {
    const request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (this.readyState === 4) {
            if (this.status === 200) {
                console.log(this.responseText);
                const json = this.responseText;
                for (word in json) {
                    var row = table.insertRow();
                    var scoreC = row.insertCell();
                    var wordC = row.insertCell();
                    scoreC.innerHTML = json[word];
                    wordC.innerHTML = word;
                }
            } else if (this.response == null && this.status === 0) {
                console.log(this.responseText);
            } else {
                console.log('Error');
            }
        }
    };
    request.open('GET', 'http://127.0.0.1:5000/api.xml?query=' + str, true);
    request.send(null);
}


问:
Node Sequelize (MSSQL) - Login failed for user ''
I've come across several posts for this question however, none of them seem to have an actual answer. Several ideas, yet none of them work.

After digging around both the Sequelize and Tedious packages and watching my config get passed down correctly, I'm at a loss.

I am trying to run migrations against a new database in MSSQL. I have no problem connecting to it with the same creds I'm using here so I know that's not the issue.

I have my config.js that is pulling env vars. With the exception of my custom console statements, this file was auto generated from sequelize and is correctly referenced in my sequelizerc

```<code>require('dotenv').config()
console.log('[+] Loading database config...')

if (process.env.NODE_ENV === 'production') {
  console.log(`[+] Using database: ${process.env.PROD_DB_DATABASE}`)
} else if (process.env.NODE_ENV === 'development') {
  console.log(`[+] Using database: ${process.env.DEV_DB_DATABASE}`)
} else if (process.env.NODE_ENV === 'test') {
  console.log(`[+] Using database: ${process.env.TEST_DB_DATABASE}`)
} else if (process.env.NODE_ENV === 'local') {
  console.log(`[+] Using database: ${process.env.LOCAL_DB_DATABASE}`)
} else {
  console.log(`[-] CANNOT LOAD DATABASE FROM ENV: ${process.env.NODE_ENV}`)
  process.exit()
}

module.exports = {
  production: {
    database: process.env.PROD_DB_DATABASE,
    username: process.env.PROD_DB_USERNAME,
    password: process.env.PROD_DB_PASSWORD,
    host: process.env.PROD_DB_HOST,
    port: process.env.PROD_DB_PORT,
    dialect: process.env.PROD_DB_DIALECT,
    storage: process.env.PROD_DB_STORAGE,
    logging: false,
    dialectOptions: {
      instanceName: process.env.PROD_INSTANCE_NAME
    },
    pool: {
      min: 5,
      max: 1,
      acquire: 6000,
      idle: 6000
    }
  },
  development: {
    database: process.env.DEV_DB_DATABASE,
    username: process.env.DEV_DB_USERNAME,
    password: process.env.DEV_DB_PASSWORD,
    host: process.env.DEV_DB_HOST,
    port: process.env.DEV_DB_PORT,
    dialect: process.env.DEV_DB_DIALECT,
    storage: process.env.DEV_DB_STORAGE,
    logging: console.log,
    dialectOptions: {
      instanceName: process.env.DEV_INSTANCE_NAME,
      debug: true
    },
    pool: {
      min: 5,
      max: 1,
      acquire: 6000,
      idle: 6000
    }
  },
  test: {
    database: process.env.TEST_DB_DATABASE,
    username: process.env.TEST_DB_USERNAME,
    password: process.env.TEST_DB_PASSWORD,
    host: process.env.TEST_DB_HOST,
    port: process.env.TEST_DB_PORT,
    dialect: process.env.TEST_DB_DIALECT,
    storage: process.env.TEST_DB_STORAGE,
    logging: false
  },
  local: {
    database: process.env.LOCAL_DB_DATABASE,
    username: process.env.LOCAL_DB_USERNAME,
    password: process.env.LOCAL_DB_PASSWORD,
    host: process.env.LOCAL_DB_HOST,
    port: process.env.LOCAL_DB_PORT,
    dialect: process.env.LOCAL_DB_DIALECT,
    storage: process.env.LOCAL_DB_STORAGE,
    logging: false
  }
}
</code>```

When i run my migration i get the error:

```<code>> node_modules/.bin/sequelize db:migrate

// ERROR: Login failed for user ''.
</code>```

As mentioned above I dug through sequelize and tedious and my config is getting passed properly through both so i know it's not an env var issue or a NODE_ENV issue.

Anyone have any ideas here? I'm about to smash my face into my keyboard.

答:
More for older versions:

If you are using sequelize@4, then it seems there is a hidden requirement that you must use tedious@<=5.

Which version of Sequelize are you using? If it's v5,
According to Sequelize v5's document:

Sequelize now works with tedious >= 6.0.0

However, in its package.json, it does not depend on tedious at all.
Since your program still runs, I guess you manually installed an older version of tedious before, which caused this strange problem.

Manually installing tedious of version>=6 should solve this problem, just like stated in its Getting started document page:

You'll also have to manually install the driver for your database of choice:

  # One of the following:
      $ npm install --save pg pg-hstore # Postgres
      $ npm install --save mysql2
      $ npm install --save mariadb
      $ npm install --save sqlite3
      $ npm install --save tedious # Microsoft SQL Server

Body:
I've come across several posts for this question however, none of them seem to have an actual answer. Several ideas, yet none of them work.

After digging around both the Sequelize and Tedious packages and watching my config get passed down correctly, I'm at a loss.

I am trying to run migrations against a new database in MSSQL. I have no problem connecting to it with the same creds I'm using here so I know that's not the issue.

I have my config.js that is pulling env vars. With the exception of my custom console statements, this file was auto generated from sequelize and is correctly referenced in my sequelizerc

require('dotenv').config()
console.log('[+] Loading database config...')

if (process.env.NODE_ENV === 'production') {
  console.log(`[+] Using database: ${process.env.PROD_DB_DATABASE}`)
} else if (process.env.NODE_ENV === 'development') {
  console.log(`[+] Using database: ${process.env.DEV_DB_DATABASE}`)
} else if (process.env.NODE_ENV === 'test') {
  console.log(`[+] Using database: ${process.env.TEST_DB_DATABASE}`)
} else if (process.env.NODE_ENV === 'local') {
  console.log(`[+] Using database: ${process.env.LOCAL_DB_DATABASE}`)
} else {
  console.log(`[-] CANNOT LOAD DATABASE FROM ENV: ${process.env.NODE_ENV}`)
  process.exit()
}

module.exports = {
  production: {
    database: process.env.PROD_DB_DATABASE,
    username: process.env.PROD_DB_USERNAME,
    password: process.env.PROD_DB_PASSWORD,
    host: process.env.PROD_DB_HOST,
    port: process.env.PROD_DB_PORT,
    dialect: process.env.PROD_DB_DIALECT,
    storage: process.env.PROD_DB_STORAGE,
    logging: false,
    dialectOptions: {
      instanceName: process.env.PROD_INSTANCE_NAME
    },
    pool: {
      min: 5,
      max: 1,
      acquire: 6000,
      idle: 6000
    }
  },
  development: {
    database: process.env.DEV_DB_DATABASE,
    username: process.env.DEV_DB_USERNAME,
    password: process.env.DEV_DB_PASSWORD,
    host: process.env.DEV_DB_HOST,
    port: process.env.DEV_DB_PORT,
    dialect: process.env.DEV_DB_DIALECT,
    storage: process.env.DEV_DB_STORAGE,
    logging: console.log,
    dialectOptions: {
      instanceName: process.env.DEV_INSTANCE_NAME,
      debug: true
    },
    pool: {
      min: 5,
      max: 1,
      acquire: 6000,
      idle: 6000
    }
  },
  test: {
    database: process.env.TEST_DB_DATABASE,
    username: process.env.TEST_DB_USERNAME,
    password: process.env.TEST_DB_PASSWORD,
    host: process.env.TEST_DB_HOST,
    port: process.env.TEST_DB_PORT,
    dialect: process.env.TEST_DB_DIALECT,
    storage: process.env.TEST_DB_STORAGE,
    logging: false
  },
  local: {
    database: process.env.LOCAL_DB_DATABASE,
    username: process.env.LOCAL_DB_USERNAME,
    password: process.env.LOCAL_DB_PASSWORD,
    host: process.env.LOCAL_DB_HOST,
    port: process.env.LOCAL_DB_PORT,
    dialect: process.env.LOCAL_DB_DIALECT,
    storage: process.env.LOCAL_DB_STORAGE,
    logging: false
  }
}

When i run my migration i get the error:

> node_modules/.bin/sequelize db:migrate

// ERROR: Login failed for user ''.

As mentioned above I dug through sequelize and tedious and my config is getting passed properly through both so i know it's not an env var issue or a NODE_ENV issue.

Anyone have any ideas here? I'm about to smash my face into my keyboard.


问:
AWX Failing to install requirements from private repo
I have an AWX installation with a project. The project is fetched perfectly from the private git repo.

The project has a requirements file which is executed by AWX. The requirements file contains private repositories like this:

```<code>- src: git+http://gitlab.test.com/ansible/test.git
  version: master
  name: test
</code>```

This however fails with the following error:

test was NOT installed successfully: - command git clone failed in directory.

How can I configure AWX to use the git credentials that are in place already in awx?

答:
It seems like AWX works 'smarter' than I thought it would.

In this case, AWX used the same credentials that it used to fetch the project in the first place. I had two options to resolve this:

Change the links to work via git

Update the same git credential and also add the username and password of that git user.

Body:
I have an AWX installation with a project. The project is fetched perfectly from the private git repo.

The project has a requirements file which is executed by AWX. The requirements file contains private repositories like this:

- src: git+http://gitlab.test.com/ansible/test.git
  version: master
  name: test

This however fails with the following error:

test was NOT installed successfully: - command git clone failed in directory.

How can I configure AWX to use the git credentials that are in place already in awx?


问:
tomcat JNDI 128-bit encryption
Most of the sample I found online is Base64 encoding, not really encryption for the username password for database access.  Our requirement is those info can't be store in clear text and has to be in 128-bit encryption.  We do have DSN setup since this database will be accessed from a .NET application as well.  Worst case I can use JDBC-ODBC bridge even though it's not recommended approach by Sun.

Does anyone have any experience on how to encypt the username / password into 128-bit?

Thanks!

答:
Base64 isn't encryption, it's encoding - and almost as insecure as plain text.

For encryption, maybe look at the BouncyCastle APIs.

However, there shouldn't really be any need to decrypt a password - it's far better to use one-way hashing (MD5, SHA-1 etc).

Title: tomcat JNDI 128-bit encryption


问:
Google OAuth API to get user's email address?
I am playing with Google's OAuth 2.0 Playground using my own personal Google account, but I cannot seem to recover my Gmail address using the playground.

The scope I am using is:

```<code>email profile https://www.googleapis.com/auth/plus.login
</code>```

But when I call the API:

```<code>https://www.googleapis.com/oauth2/v2/userinfo
</code>```

I get various information about the user such as family name, first name, gender, picture, etc. but it does not return the user's email.

How do I retrieve the user's email address? Do I have the wrong scope or am I calling the wrong API? I feel like this should be very simple but I have literally been trying to figure this out for hours and I cannot find an API and scope combination that consistently provides the user's email address.

答: Change the authorizationRequest with given scope: scope=openid%20email%20profile and use userinfoapi. This link worked for me

Body:
I am playing with Google's OAuth 2.0 Playground using my own personal Google account, but I cannot seem to recover my Gmail address using the playground.

The scope I am using is:

email profile https://www.googleapis.com/auth/plus.login

But when I call the API:

https://www.googleapis.com/oauth2/v2/userinfo

I get various information about the user such as family name, first name, gender, picture, etc. but it does not return the user's email.

How do I retrieve the user's email address? Do I have the wrong scope or am I calling the wrong API? I feel like this should be very simple but I have literally been trying to figure this out for hours and I cannot find an API and scope combination that consistently provides the user's email address.


问:
Can I automate an email off google sheets based on specific updated columns and rows?
I was wondering if you could help me. I know this code is incomplete it's been kind of a frankensteined piece I made from many other peoples issues close to mine. I just can't find exactly what I am looking for. I don't know Java and I am new to google sheets and google-apps-scripts

Problem: I want to build a script that automatically sends me an email when a spreadsheet is updated and tell me what Cell was updated. The issue I am having is I need it to meet certain criteria.
For Example, if cellvalue in column i = "Name" and on that row columns w, x , ae or af are updated or changed. Then send out an automated email.

If you guys could help I would really appreciate it.

Thank you!

I tried an import range and filtered only the person i need and the columns I need but the roadblock I hit there is that when it gets updated it updates the cell that contains the importrange formula. I also read it can be inconsistent as well.

function sendNotification(e){
  var ss = SpreadsheetApp.getActive().getSheetByName('Datasheet');
  //var gg = ss.getActiveCell().getValue().toString().getFilter('Person');
  //var sheet = ss.getActiveSheet();
  var cell = ss.getActiveCell().getA1Notation();
  var row = ss.getActiveRange().getRow();
  var column = ss.getActiveRange().getColumn().toString();
  var cellvalue = ss.getActiveCell().getValue().toString();
  var subject = '____ '+ ss.getName();
  var lastColumn = ss.getLastColumn();
  var lastRow = ss.getLastRow();
  var range = ss.getRange(1,1,lastRow,lastColumn);

  MailApp.sendEmail({
    to: "Email@gmail",
    subject: subject,
    htmlBody: "

"+
    "The following cell has been updated.

"+
    " Cell: " +
    cell + "

" +
    "The update was the following: " + cell + "
" + "

" +
    "Column: " + column + "
Updated Cell: " + cellvalue + "

" +
    "

Thank you.
"
  });
};

```

So I want to be able to filter out a specific person and specific columns that get updated. Currently I am trying it off of an importrange in a new sheet. When I update the masterlist though I get an email telling me it updated. But the updated cell is the cell that houses the importrange formula. I would love to just insert the code straight into the master list if I can filter out what I need.

答:
You need an if statement to achieve your goal. I've also changed a lot of your variables to use the e event object, this makes it much easier to grab ranges that have been edited etc.

```<code>function sendNotification(e){
  var ss = e.source.getSheetByName('Datasheet');
  var cell = e.range.getA1Notation();
  var row = e.range.getRow();
  var col = e.range.getColumn();
  var cellvalue = e.range.getValue();
  var subject = '____ '+ ss.getSheetName();
  var name = ss.getRange(row, 9).getValue(); //get column 9 for current row

  if (name === 'Name' && (col === 23 || col === 24 || col === 31 || col === 32) === true) {

    MailApp.sendEmail({
      to: "Email@gmail",
      subject: subject,
      htmlBody: "<br><br>"+
      "The following cell has been updated. <br><br>"+
      "<font size=\"3\" color=\"black\"><b> Cell: </b></font>" +
      cell + "<br><br>" +
      "The update was the following: " + cell + "<br>" + "<br><br>" +
      "Column: " + col + "<br>Updated Cell: " + cellvalue + "<br><br>" +
      "<br><br>Thank you. <br>"
    })
  }
}
</code>```

The if statement checks to make sure variable name (I took this literally from your question), which is column I, is set to 'Name'. I took this literally but you can change this check to whatever you'd like the script to run for. It then checks that either columns W, X, AE or AF are updated, then sends an email if both criteria are matched.

```<code>if (name === 'Name' && (col === 23 || col === 24 || col === 31 || col === 32) === true) {
</code>```

Body:
I was wondering if you could help me. I know this code is incomplete it's been kind of a frankensteined piece I made from many other peoples issues close to mine. I just can't find exactly what I am looking for. I don't know Java and I am new to google sheets and google-apps-scripts

Problem: I want to build a script that automatically sends me an email when a spreadsheet is updated and tell me what Cell was updated. The issue I am having is I need it to meet certain criteria.
For Example, if cellvalue in column i = "Name" and on that row columns w, x , ae or af are updated or changed. Then send out an automated email.

If you guys could help I would really appreciate it.

Thank you!

I tried an import range and filtered only the person i need and the columns I need but the roadblock I hit there is that when it gets updated it updates the cell that contains the importrange formula. I also read it can be inconsistent as well.

function sendNotification(e){
  var ss = SpreadsheetApp.getActive().getSheetByName('Datasheet');
  //var gg = ss.getActiveCell().getValue().toString().getFilter('Person');
  //var sheet = ss.getActiveSheet();
  var cell = ss.getActiveCell().getA1Notation();
  var row = ss.getActiveRange().getRow();
  var column = ss.getActiveRange().getColumn().toString();
  var cellvalue = ss.getActiveCell().getValue().toString();
  var subject = '____ '+ ss.getName();
  var lastColumn = ss.getLastColumn();
  var lastRow = ss.getLastRow();
  var range = ss.getRange(1,1,lastRow,lastColumn);

  MailApp.sendEmail({
    to: "Email@gmail",
    subject: subject,
    htmlBody: "

"+
    "The following cell has been updated.

"+
    " Cell: " +
    cell + "

" +
    "The update was the following: " + cell + "
" + "

" +
    "Column: " + column + "
Updated Cell: " + cellvalue + "

" +
    "

Thank you.
"
  });
};

So I want to be able to filter out a specific person and specific columns that get updated. Currently I am trying it off of an importrange in a new sheet. When I update the masterlist though I get an email telling me it updated. But the updated cell is the cell that houses the importrange formula. I would love to just insert the code straight into the master list if I can filter out what I need.

Body:
You need an if statement to achieve your goal. I've also changed a lot of your variables to use the e event object, this makes it much easier to grab ranges that have been edited etc.

function sendNotification(e){
  var ss = e.source.getSheetByName('Datasheet');
  var cell = e.range.getA1Notation();
  var row = e.range.getRow();
  var col = e.range.getColumn();
  var cellvalue = e.range.getValue();
  var subject = '____ '+ ss.getSheetName();
  var name = ss.getRange(row, 9).getValue(); //get column 9 for current row

  if (name === 'Name' && (col === 23 || col === 24 || col === 31 || col === 32) === true) {

    MailApp.sendEmail({
      to: "Email@gmail",
      subject: subject,
      htmlBody: "<br><br>"+
      "The following cell has been updated. <br><br>"+
      "<font size=\"3\" color=\"black\"><b> Cell: </b></font>" +
      cell + "<br><br>" +
      "The update was the following: " + cell + "<br>" + "<br><br>" +
      "Column: " + col + "<br>Updated Cell: " + cellvalue + "<br><br>" +
      "<br><br>Thank you. <br>"
    })
  }
}

The if statement checks to make sure variable name (I took this literally from your question), which is column I, is set to 'Name'. I took this literally but you can change this check to whatever you'd like the script to run for. It then checks that either columns W, X, AE or AF are updated, then sends an email if both criteria are matched.

if (name === 'Name' && (col === 23 || col === 24 || col === 31 || col === 32) === true) {


问:
Get Xaringan incremental animations to print to PDF?
My Xaringan (fantastic package) deck in HTML has incremental additions of bullets that behave as desired.

When printed to PDF, the incremental additions disappear.

I tried printing the HTML to PDF in a few ways suggested by the documentation: webshot(), pagedown::chrome_print(), and from Chrome browser by hand.  All produce the same PDF with no incremental additions.

A simple example:

---
title: "No incremental in PDF"
output:
  xaringan::moon_reader:
    css: ['default', 'metropolis', 'metropolis-fonts', 'bootcamp.css']
---

# Testing incremental bullets

- Bullet 1
--

- Bullet 2
--

- Bullet 3
```

The bullets appear on successive slides in the HTML, as desired.  But all three appear at once the second page after printing to PDF. That second page with all bullets is numbered "4/4" on the slide...but there are no 2/4 or 3/4 slides preceding it.  Thanks.

R 3.6.0
RStudio 1.2.1335
xaringan 0.10.1
pagedown 0.2.6
webshot 0.5.1
Chrome 74.0.3729.169

答:
When you're on an incremental slide then the class has-continuation is added to it and the corresponding print is set to display:none. To print out the incremental slides you need to overwrite this behaviour by inserting below to your css file:

```<code>@media print {
  .has-continuation {
    display: block !important;
  }
}
</code>```

Body:
My Xaringan (fantastic package) deck in HTML has incremental additions of bullets that behave as desired.

When printed to PDF, the incremental additions disappear.

I tried printing the HTML to PDF in a few ways suggested by the documentation: webshot(), pagedown::chrome_print(), and from Chrome browser by hand.  All produce the same PDF with no incremental additions.

A simple example:

---
title: "No incremental in PDF"
output:
  xaringan::moon_reader:
    css: ['default', 'metropolis', 'metropolis-fonts', 'bootcamp.css']
---

# Testing incremental bullets

- Bullet 1
--

- Bullet 2
--

- Bullet 3

The bullets appear on successive slides in the HTML, as desired.  But all three appear at once the second page after printing to PDF. That second page with all bullets is numbered "4/4" on the slide...but there are no 2/4 or 3/4 slides preceding it.  Thanks.

R 3.6.0
RStudio 1.2.1335
xaringan 0.10.1
pagedown 0.2.6
webshot 0.5.1
Chrome 74.0.3729.169

Body:
When you're on an incremental slide then the class has-continuation is added to it and the corresponding print is set to display:none. To print out the incremental slides you need to overwrite this behaviour by inserting below to your css file:

@media print {
  .has-continuation {
    display: block !important;
  }
}


问:
Hiding the selection in a WPF ListBox, keeping it in contained controls
I'm using a ListBox to display a list of editable objects whose template contains, among other things, a ComboBox.

I used this common technique to hide the ListBox selection, which is not used for anything:

```<code><ListBox.Resources>
  <Style TargetType="ListBoxItem">
    <Style.Resources>
      <Brush x:Key="{x:Static SystemColors.HighlightBrushKey}">Transparent</Brush>
      <Brush x:Key="{x:Static SystemColors.ControlBrushKey}">Transparent</Brush>
</code>```

The problem is this messes with the ComboBox dropdown list selection.

I'd like to override these resources again in my template, specifying the original values (SystemColors.HighlightBrush, etc) instead of hardcoding them. How can I do that?

```<code><ListBox.ItemTemplate>
  <DataTemplate DataType="{x:Type SearchService:Criterion}">
    <DataTemplate.Resources>
      <!--I know how to specify a hardcoded brush here,
          but not how to reference one from SystemColors-->
</code>```

答:
I used this common technique to hide
  the ListBox selection, which is not
  used for anything

If you do not use the selection for anything you should just use an ItemsControl instead.

Body:
I'm using a ListBox to display a list of editable objects whose template contains, among other things, a ComboBox.

I used this common technique to hide the ListBox selection, which is not used for anything:

<ListBox.Resources>


问:
If RDSADMIN is created by AWS, can Amazon actually access our database and data?
I created a new DB instance on AWS RDS. It created a default database as RDSADMIN. I created another DB for my project.

But my question is: can Amazon directly access my new DB data technically?

答:
Technically they can but doesn't mean they do.
An addition, everyone can use own master key for encryption in-place/in-transit.

you can choose to encrypt the data stored on your Amazon RDS DB instance under a customer master key (CMK) in AWS KMS

See: https://docs.aws.amazon.com/kms/latest/developerguide/services-rds.html


答:
imageio allows to read gifs like this:

```<code>import imageio

img = imageio.imread('filename.gif')
</code>```

Title: How to read the mask of an image using opencv in python

Body:
imageio allows to read gifs like this:

import imageio

img = imageio.imread('filename.gif')


问:
Parse a command line string into flags and arguments in Golang
I'm looking for a package that would take a string such as -v --format "some example" -i test and parse it into a slice of strings, handling quotes, spaces, etc. properly:

```<code>-v
--format
some example
-i
test
</code>```

I've checked the built-in flag package as well as other flag handling packages on Github but none of them seem to handle this particular case of parsing a raw string into tokens. Before trying to do it myself I'd rather look for a package as I'm sure there are a lot of special cases to handle.

Any suggestion?

答: hedzr/cmdr might be good. it's a getopt-like command-line parser, light weight, fluent api or classical style.</p>

Body:
I'm looking for a package that would take a string such as -v --format "some example" -i test and parse it into a slice of strings, handling quotes, spaces, etc. properly:

-v
--format
some example
-i
test

I've checked the built-in flag package as well as other flag handling packages on Github but none of them seem to handle this particular case of parsing a raw string into tokens. Before trying to do it myself I'd rather look for a package as I'm sure there are a lot of special cases to handle.

Any suggestion?


问:
Access value from function dispatch on component
I'm new to react.

I have a function, that need to refresh the state according with API request result on my component.

How can i access that value?

Code (Example):

LoginComponent.js

```<code>        class Login extends React.Component {
           constructor(props){
              super(props)
              this.state = {
                 username : '',
                 password : ''
              }
           }
           submit = (e) => {
              /* console.logging "Some response"*/
              console.log(this.props.doLogin(this.state))
           }
           render(){
              return (
                 <form onSubmit={this.submit}>/* some login element */</form>
              )
           }
        }

export default connect(null, {LoginAction})(Login);
</code>```

LoginAction.js

```<code>export function doLogin(state){
   return dispatch => {
      return axios.post('login', state).then(res =>{

      return "Some response";

    })
   }
}
</code>```

答:
you can do like this

for example create axios.js

```<code>import axios from 'axios';

var instance = axios.create({
      baseURL: 'https://www.',
      timeout: 1000,
      headers: {'Authorization': 'Bearer xxx'}
});
export default instance;
</code>```

then in your another screen

```<code>import React from 'react';
import API from '../axios';

export default class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      feedback: "",
      id: "",
      errors: {},
    };
}

  postComment = () => {
        API.post(`/new-comment`, {
          id: this.state.id,
          feedback: this.state.feedback,
        })
        .then(res => res.data)
        .then((response)=> {
          this.setState({
              feedback: '',
              error: response.error || null,
          })

        }).catch(error => {console.log(error), this.setState({ error});});
   }
</code>```

Body:
I'm new to react.

I have a function, that need to refresh the state according with API request result on my component.

How can i access that value?

Code (Example):

LoginComponent.js

        class Login extends React.Component {
           constructor(props){
              super(props)
              this.state = {
                 username : '',
                 password : ''
              }
           }
           submit = (e) => {
              /* console.logging "Some response"*/
              console.log(this.props.doLogin(this.state))
           }
           render(){
              return (
                 <form onSubmit={this.submit}>/* some login element */</form>
              )
           }
        }

export default connect(null, {LoginAction})(Login);

LoginAction.js

export function doLogin(state){
   return dispatch => {
      return axios.post('login', state).then(res =>{

      return "Some response";

    })
   }
}

Body:
you can do like this

for example create axios.js

import axios from 'axios';

var instance = axios.create({
      baseURL: 'https://www.',
      timeout: 1000,
      headers: {'Authorization': 'Bearer xxx'}
});
export default instance;

then in your another screen

import React from 'react';
import API from '../axios';

export default class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      feedback: "",
      id: "",
      errors: {},
    };
}

  postComment = () => {
        API.post(`/new-comment`, {
          id: this.state.id,
          feedback: this.state.feedback,
        })
        .then(res => res.data)
        .then((response)=> {
          this.setState({
              feedback: '',
              error: response.error || null,
          })

        }).catch(error => {console.log(error), this.setState({ error});});
   }


问:
php session not working when my page redirect from payment gateway server to my page
i am creating ticket booking website using some api , i use json for get & post values and creating php session's to pass data's to other pages,
page 1 : creating session's
page 2 : payment gateway (i checked session's payment page it works fine)
page 3 : success page (after redirecting from payment gateway to my server page the session's are showing null values in chrome browser but works fine in Firefox).
all suggestion's are welcome.thanks in advance.
some code</p>

```<code><?php
session_start();
if(isset($_REQUEST['blockTicketId'])!=''){
    $rootId= $_REQUEST['ruteId'];
    if( $_REQUEST['dropPoint_'.$rootId]!=''){
        $board = explode("_", $_REQUEST['dropPoint_'.$rootId]);
    }
    $_SESSION['formcity']=$_REQUEST['fromCity'];
    $_SESSION['tocity']=$_REQUEST['toCity'];
    $_SESSION['dateofjurny']=$_REQUEST['fromDate'];
    $_SESSION['pickup']=$board[0];
    $_SESSION['pickupTime']=$board[2];
    $_SESSION['travelName']=$_REQUEST['travelNmae'];
    $_SESSION['seat']=$_REQUEST['selectedSeat_'.$rootId];
    echo $_SESSION['blockTicketNumber']=$_REQUEST['blockTicketId'];
    $_SESSION['mobno']=$_REQUEST['bookerMob'];
    $_SESSION['mailid']=$_REQUEST['bookerEmail'];
    $_SESSION['user']=$_REQUEST['UserName_1'];
    $_SESSION['amnt']=$_REQUEST['selectedSeatAmnt_'.$rootId];
?>

<html>
  <head>
  <script>
  function submitPayuForm() {
    var payuForm = document.forms.payuForm;
    payuForm.submit();
  }
  </script>
  </head>
  <body onLoad="submitPayuForm()">
    <form action="PayUMoney_form.php" method="post" name="payuForm">
      <table>
        <tr>
          <td></td>
        </tr>
        <tr>
          <td></td>
          <td><input style="visibility:hidden" name="amount" value="<?php echo "1"; ?>" /></td>
          <td></td>
          <td><input style="visibility:hidden" name="firstname" id="firstname" value="<?php echo $_REQUEST['UserName_1']; ?>" /></td>
        </tr>
        <tr>
          <td></td>
          <td><input style="visibility:hidden" name="email" id="email" value="<?php echo $_REQUEST['bookerEmail']; ?>" /></td>
          <td></td>
          <td><input style="visibility:hidden" name="phone" value="<?php echo $_REQUEST['bookerMob']; ?>" /></td>
        </tr>
        <tr>
            <td colspan="4"><input type="submit" style="visibility:hidden" value="Submit" /></td>
        </tr>
      </table>
    </form>
  </body>
</html>

<?php
}
?>
</code>```

答:
i have not tried but you can try to pass "session variable" through paymnet gateway redirection page from your website to payumoney gateway sucess page./

example:
1)your website payment form + store your session in a GLOBAL session variable ($SESSION[var]="abc")  + and also store your session variable in (the array parameters given by payment gateway ) -> (2) gateway page -> (3) access your session variable again from passed array.

Note:- do not depend on session_start() function on gateway success page.
tell me if it works.

Body:
i am creating ticket booking website using some api , i use json for get & post values and creating php session's to pass data's to other pages,
page 1 : creating session's
page 2 : payment gateway (i checked session's payment page it works fine)
page 3 : success page (after redirecting from payment gateway to my server page the session's are showing null values in chrome browser but works fine in Firefox).
all suggestion's are welcome.thanks in advance.
some code

<?php
session_start();
if(isset($_REQUEST['blockTicketId'])!=''){
    $rootId= $_REQUEST['ruteId'];
    if( $_REQUEST['dropPoint_'.$rootId]!=''){
        $board = explode("_", $_REQUEST['dropPoint_'.$rootId]);
    }
    $_SESSION['formcity']=$_REQUEST['fromCity'];
    $_SESSION['tocity']=$_REQUEST['toCity'];
    $_SESSION['dateofjurny']=$_REQUEST['fromDate'];
    $_SESSION['pickup']=$board[0];
    $_SESSION['pickupTime']=$board[2];
    $_SESSION['travelName']=$_REQUEST['travelNmae'];
    $_SESSION['seat']=$_REQUEST['selectedSeat_'.$rootId];
    echo $_SESSION['blockTicketNumber']=$_REQUEST['blockTicketId'];
    $_SESSION['mobno']=$_REQUEST['bookerMob'];
    $_SESSION['mailid']=$_REQUEST['bookerEmail'];
    $_SESSION['user']=$_REQUEST['UserName_1'];
    $_SESSION['amnt']=$_REQUEST['selectedSeatAmnt_'.$rootId];
?>

    <form action="PayUMoney_form.php" method="post" name="payuForm">

          <input style="visibility:hidden" name="amount" value="<?php echo "1"; ?>" />

          <input style="visibility:hidden" name="firstname" id="firstname" value="<?php echo $_REQUEST['UserName_1']; ?>" />

          <input style="visibility:hidden" name="email" id="email" value="<?php echo $_REQUEST['bookerEmail']; ?>" />

          <input style="visibility:hidden" name="phone" value="<?php echo $_REQUEST['bookerMob']; ?>" />

            <input type="submit" style="visibility:hidden" value="Submit" />

    </form>

<?php
}
?>


问:
C++, I want to know how to allocate memory vector< pair<int, int> > *
I have an error _Has_unused_capacity() vector...
I don't know how to allocate dynamic memory

I try to push_back, but the error occurred

```<code>vector< pair<int, int> > * v;

void Some_Function(){
   int m=3;
   int idx1=1;
   int idx2=2;
   int idx3=3;

   for(int i = 0; i<m; i++) {
       v[idx1].push_back(make_pair(idx2, idx3));
       v[idx2].push_back(make_pair(idx1, idx3));
   }
}
</code>```

答:
At first, I don't recommend you to use pointer to container.

Also, the element is pointer may cause memory leak.

But, if must. you can use std::vector<std::vector<std::pair<int, int>>

OR, auto vec = std::make_shared<std::vector<std::vector<std::pair<int, int>>>()

use smart pointer may manage memory by itself. std::make_shared has been support since C++14

Body:
I have an error _Has_unused_capacity() vector...
I don't know how to allocate dynamic memory

I try to push_back, but the error occurred

vector< pair<int, int> > * v;

void Some_Function(){
   int m=3;
   int idx1=1;
   int idx2=2;
   int idx3=3;

   for(int i = 0; i<m; i++) {
       v[idx1].push_back(make_pair(idx2, idx3));
       v[idx2].push_back(make_pair(idx1, idx3));
   }
}


答:
At first, you should create desired URL, open request and then set request header. Let me show an example:

```<code>function sendRequest(){
  let theUrl = 'http://127.0.0.1:5000/api.xml'

  let xmlHttp = new XMLHttpRequest();
  let fooStr='?query=toast';
  theUrl = `http://127.0.0.1:5000/api.xml${fooStr}`;
  xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
  xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

  xmlHttp.send( null );
  return xmlHttp.responseText;
}

sendRequest();
</code>```

Or in your case:

```<code>request.open('GET', 'http://127.0.0.1:5000/api.xml?query='+str, true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.send();
</code>```

Title: Error with setRequestHeader in GET request

Body:
At first, you should create desired URL, open request and then set request header. Let me show an example:

function sendRequest(){
  let theUrl = 'http://127.0.0.1:5000/api.xml'

  let xmlHttp = new XMLHttpRequest();
  let fooStr='?query=toast';
  theUrl = `http://127.0.0.1:5000/api.xml${fooStr}`;
  xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
  xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

  xmlHttp.send( null );
  return xmlHttp.responseText;
}

sendRequest();

Or in your case:

request.open('GET', 'http://127.0.0.1:5000/api.xml?query='+str, true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.send();


问:
Redirect "ugly" URL to new URL using htaccess
I have already rewritten my old "ugly" URL:

```<code>http://example.com/ppd-brands/generic/?gen_id=Mjky
</code>```

to

```<code>http://example.com/ppd-brands/generic/gen_id/Mjky
</code>```

using the code below

```<code>RewriteRule ^ppd-brands/generic/gen_id/([^/]*)$ /ppd-brands/generic/?gen_id=$1 [L]
</code>```

and it's working.

Now my problem is how can I redirect the old "ugly" URL to the new URL when the user visits the old "ugly" URL?

答:
```<code>Redirect 301 /oldurl.htm /newurl.htm
</code>```

change old and new URL according to your need. Hope it helps you

Body:
I have already rewritten my old "ugly" URL:

http://example.com/ppd-brands/generic/?gen_id=Mjky

to

http://example.com/ppd-brands/generic/gen_id/Mjky

using the code below

RewriteRule ^ppd-brands/generic/gen_id/([^/]*)$ /ppd-brands/generic/?gen_id=$1 [L]

and it's working.

Now my problem is how can I redirect the old "ugly" URL to the new URL when the user visits the old "ugly" URL?

Body:
Redirect 301 /oldurl.htm /newurl.htm

change old and new URL according to your need. Hope it helps you


问:
SSRS - On what basis should I decide to choose Dataset Filter or Dataset Parameter?
For a shared dataset, that needs to be used as part of a cascading parameter; the logic can be implemented using Filter or Parameter.

For example - If there are 3 parameters - 1. Start Date (date); 2. End Date (date); 3. Policy (multivalue text) - and the task is to cascade the start/end date values to populate the Policy parameter.

We can implement this by using dataset filter - by having the Policy param dataset to include 3 columns: Startdate, enddate and policy and then filter the parameter to show only those policies that belong to the selected dates.

And also the same can be implemented using dataset parameter by having the Policy param dataset accept start/end date as parameters.

What is the best practice approach please?

答:
As you already you, we can use Dataset parameter and Dataset Filterto filter out required Data.

As far as my knowledge goes, it is always better to use dataset parameter. Reason: it will filter out data coming from database i.e on Report you will have let's say 100 Records rather than 1200.

Now if you use Dataset Filter you will have in your report 1200 records but you are filtering on top of your 1200 records in Report to just show 100.

That means fetching data and then using dataset filter will cost you more time and memory than dataset parameter.

Now when is dataset parameter more useful, just last week I had requirement to filter records (field: "created on date") by months.
This requirement was not possible using dataset parameter because I use Fetchxml as query and in fetchxml I cannot just add parameter on month. In this case unfortunately I had to use Dataset Filter. Reason: I could use expression to tweak filter.