问:
MSIE Browser Detect: Missing Radix?
```<code>if($.browser.msie && parseInt($.browser.version) < 9) {}
</code>```

Jshint says it's missing the radix. I'm not sure how I would write that?

答:
Try using parseInt($.browser.version, 10). The ', 10' tells parseInt to use base-10.

EDIT:
In most circumstances, the default behavior of parseInt is to treat the input as base-10, so you can get away with not including the radix. However, if you're converting from a string that has a leading zero, parseInt treats the value as an octal (base-8) number if you don't tell it what base to use, so you get this:
parseInt("07") == 7

parseInt("08") == 0

parseInt("010") == 8

Title: MSIE Browser Detect: Missing Radix?

Body:
if($.browser.msie && parseInt($.browser.version) < 9) {}

Jshint says it's missing the radix. I'm not sure how I would write that?


来源: stackexchange

问:
How to use dynamic sources for a video in an AMP page?
I’m creating an AMP version of video pages on my VOD website. I’m using amp-access to authenticate the user, and then amp-subscriptions to check if a user has purchased access to the video. This works fine. However, what I am having difficulty with is, how to dynamically set the source elements for the video itself.

As these videos are premium videos, I don’t want the source URLs in the mark-up on page load. What I would like to happen is: if a user has purchased access, to dynamically add <source> child elements to my amp-video tag.

I’ve tried using amp-list and fetching the source URLs like this:

<amp-list layout="nodisplay" src="/amp/encodings.json">
    <template type="amp-mustache">
        <source src="{{url}}" />
    </template>
</amp-list>
```

But this seems to throw the following error in the browser console:

AMP validation had errors:
  http://example.com/video.amp.html:295:48 The parent tag of tag 'picture > source' is 'template', but it can only be 'picture'. (see https://amp.dev/documentation/components/amp-img)

So now I’m at a loss.

Does any one have any ideas how I could dynamically set the source URLs for a video after authorisation?

答:
I am not sure exactly what you looking for but i can suggest you to use amp-iframe here. You can load your video content over separate page and load it though amp-iframe over web page.

By this approach you can add all your related scripts/styles inside iframe loaded page without any restrictions.

ContentLicense: CC BY-SA 4.0

Body:
I’m creating an AMP version of video pages on my VOD website. I’m using amp-access to authenticate the user, and then amp-subscriptions to check if a user has purchased access to the video. This works fine. However, what I am having difficulty with is, how to dynamically set the source elements for the video itself.

As these videos are premium videos, I don’t want the source URLs in the mark-up on page load. What I would like to happen is: if a user has purchased access, to dynamically add <source> child elements to my amp-video tag.

I’ve tried using amp-list and fetching the source URLs like this:

<amp-list layout="nodisplay" src="/amp/encodings.json">
    <template type="amp-mustache">
        <source src="{{url}}" />
    </template>
</amp-list>

But this seems to throw the following error in the browser console:

AMP validation had errors:
  http://example.com/video.amp.html:295:48 The parent tag of tag 'picture > source' is 'template', but it can only be 'picture'. (see https://amp.dev/documentation/components/amp-img)

So now I’m at a loss.

Does any one have any ideas how I could dynamically set the source URLs for a video after authorisation?


问:
how to drop a bomb in character position in a pygame game
I'm making a pygame game where a character is currently moving around on a screen and can buy items from a shop. I want the character to be able to drop the bombs that he buys from the shop in the location of the player (I need to fix this). I'm attaching my whole code along with some screen shots. Any help is appreciated, thank you.

```<code> import pygame

pygame.font.init()

width = 900
height = 600

screen = pygame.display.set_mode([width, height])

walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'),
             pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'),
             pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]

walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'),
            pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'),
            pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]

char = pygame.image.load('standing.png')
bomb_pic = pygame.transform.scale(pygame.image.load('bomb.png'), (20,20))
# char_rect = char.get_rect()

x = 50
y = 50
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 10
left = False
right = False
down = False
up = False
walkCount = 0
shop = pygame.transform.scale(pygame.image.load("shop.png"), (60, 60))

clock = pygame.time.Clock()
FPS = 60

bag = {'bomb': 0}
print(bag["bomb"])
class Button():
    def __init__(self, color, x, y, width, height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self, win, outline=None):

        # Call this method to draw the button on the screen
        if outline:
            pygame.draw.rect(win, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)

        pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)

        if self.text != '':
            font = pygame.font.SysFont('comicsans', 20)
            text = font.render(self.text, 1, (0, 0, 0))
            win.blit(text, (
                self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2)))

def shop_run():
    shop_bomb = Button((0, 200, 0), 820, 150, 60, 20, text="Bomb_q")
    bright_green = (0, 255, 0)
    green = (0, 200, 0)
    shop_bomb.draw(screen)

def redrawGameWindow():
    global walkCount
    screen.fill([166, 166, 166])

    pygame.draw.rect(screen, (0, 0, 0), (800, 0, 100, 600))
    if x + char.get_width() < 60 and y + char.get_height() < 60:
        shop_run()

    screen.blit(shop, (0, 0))

    if walkCount + 1 >= 27:
        walkCount = 0

    if left:
        screen.blit(walkLeft[walkCount // 3], (x, y))
        walkCount += 1

    elif right:
        screen.blit(walkRight[walkCount // 3], (x, y))
        walkCount += 1

    elif down:
        screen.blit(char, (x, y))
        walkcount = 0

    elif up:
        screen.blit(char, (x, y))
        walkcount = 0

    else:
        screen.blit(char, (x, y))
        walkCount = 0

    buy = pygame.key.get_pressed()
    if buy[pygame.K_SPACE] and bag["bomb"] >= 1:
        screen.blit(bomb_pic,(x,y))
    pygame.display.update()

def main():
    run = True
    # shopper()
    pygame.display.set_caption("bomb-mania")

    global x
    global y
    global width
    global height
    global vel

    global isJump
    global jumpCount

    global left
    global right
    global down
    global up

    global walkCount

    global bomb_pic
    while run:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if x + char.get_width() < 60 and y + char.get_height() < 60:
                buy = pygame.key.get_pressed()
                if buy[pygame.K_q]:
                    bag["bomb"] += 1
                    print(bag["bomb"])

        redrawGameWindow()

        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT] and x > vel - 15:
            x -= vel
            left = True
            right = False
            down = False
            up = False

        elif keys[pygame.K_RIGHT] and x < 800 - vel - width:
            x += vel
            left = False
            right = True[![enter image description here][1]][1]
            down = False
            up = False

        elif keys[pygame.K_DOWN] and y < 600 - height:
            y += vel
            left = False
            right = False
            down = True
            up = False

        elif keys[pygame.K_UP] and y > vel - 15:
            y -= vel
            left = False
            right = False
            down = False
            up = True

        else:
            left = False
            right = False
            down = False
            up = False
            walkCount = 0

        clock.tick(FPS)
        pygame.display.flip()

main()
</code>```

答:
You're only drawing the bomb when you press the space bar. You have to draw it continuously. You need to add these three things in your code (not directly after each other as shown here).</p>

```<code># Create a list to keep track on the bombs positions (do this **before**
# the game loop). Could be a global variable if you want.
bomb_positions = []

# Add a bomb when you press space. Do this in the event loop and not with
# 'pygame.key.get_pressed()', because that will add a new bomb every frame if
# you hold down the spacebar.
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
        bomb_positions.append((x, y))

# Draw all the bombs at their position. If the list is empty, nothing will
# be drawn.
for bomb_position in bomb_positions:
    screen.blit(bomb_pic, bomb_position)
</code>```

Body:
I'm making a pygame game where a character is currently moving around on a screen and can buy items from a shop. I want the character to be able to drop the bombs that he buys from the shop in the location of the player (I need to fix this). I'm attaching my whole code along with some screen shots. Any help is appreciated, thank you.

 import pygame

pygame.font.init()

width = 900
height = 600

screen = pygame.display.set_mode([width, height])

walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'),
             pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'),
             pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]

walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'),
            pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'),
            pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]

char = pygame.image.load('standing.png')
bomb_pic = pygame.transform.scale(pygame.image.load('bomb.png'), (20,20))
# char_rect = char.get_rect()

x = 50
y = 50
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 10
left = False
right = False
down = False
up = False
walkCount = 0
shop = pygame.transform.scale(pygame.image.load("shop.png"), (60, 60))

clock = pygame.time.Clock()
FPS = 60

bag = {'bomb': 0}
print(bag["bomb"])
class Button():
    def __init__(self, color, x, y, width, height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self, win, outline=None):

        # Call this method to draw the button on the screen
        if outline:
            pygame.draw.rect(win, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)

        pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)

        if self.text != '':
            font = pygame.font.SysFont('comicsans', 20)
            text = font.render(self.text, 1, (0, 0, 0))
            win.blit(text, (
                self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2)))

def shop_run():
    shop_bomb = Button((0, 200, 0), 820, 150, 60, 20, text="Bomb_q")
    bright_green = (0, 255, 0)
    green = (0, 200, 0)
    shop_bomb.draw(screen)

def redrawGameWindow():
    global walkCount
    screen.fill([166, 166, 166])

    pygame.draw.rect(screen, (0, 0, 0), (800, 0, 100, 600))
    if x + char.get_width() < 60 and y + char.get_height() < 60:
        shop_run()

    screen.blit(shop, (0, 0))

    if walkCount + 1 >= 27:
        walkCount = 0

    if left:
        screen.blit(walkLeft[walkCount // 3], (x, y))
        walkCount += 1

    elif right:
        screen.blit(walkRight[walkCount // 3], (x, y))
        walkCount += 1

    elif down:
        screen.blit(char, (x, y))
        walkcount = 0

    elif up:
        screen.blit(char, (x, y))
        walkcount = 0

    else:
        screen.blit(char, (x, y))
        walkCount = 0

    buy = pygame.key.get_pressed()
    if buy[pygame.K_SPACE] and bag["bomb"] >= 1:
        screen.blit(bomb_pic,(x,y))
    pygame.display.update()

def main():
    run = True
    # shopper()
    pygame.display.set_caption("bomb-mania")

    global x
    global y
    global width
    global height
    global vel

    global isJump
    global jumpCount

    global left
    global right
    global down
    global up

    global walkCount

    global bomb_pic
    while run:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if x + char.get_width() < 60 and y + char.get_height() < 60:
                buy = pygame.key.get_pressed()
                if buy[pygame.K_q]:
                    bag["bomb"] += 1
                    print(bag["bomb"])

        redrawGameWindow()

        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT] and x > vel - 15:
            x -= vel
            left = True
            right = False
            down = False
            up = False

        elif keys[pygame.K_RIGHT] and x < 800 - vel - width:
            x += vel
            left = False
            right = True[![enter image description here][1]][1]
            down = False
            up = False

        elif keys[pygame.K_DOWN] and y < 600 - height:
            y += vel
            left = False
            right = False
            down = True
            up = False

        elif keys[pygame.K_UP] and y > vel - 15:
            y -= vel
            left = False
            right = False
            down = False
            up = True

        else:
            left = False
            right = False
            down = False
            up = False
            walkCount = 0

        clock.tick(FPS)
        pygame.display.flip()

main()

Body:
You're only drawing the bomb when you press the space bar. You have to draw it continuously. You need to add these three things in your code (not directly after each other as shown here).

# Create a list to keep track on the bombs positions (do this **before**
# the game loop). Could be a global variable if you want.
bomb_positions = []

# Add a bomb when you press space. Do this in the event loop and not with
# 'pygame.key.get_pressed()', because that will add a new bomb every frame if
# you hold down the spacebar.
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
        bomb_positions.append((x, y))

# Draw all the bombs at their position. If the list is empty, nothing will
# be drawn.
for bomb_position in bomb_positions:
    screen.blit(bomb_pic, bomb_position)


问:
Iterate over a proxy list selenium python
I am making a twitter scraper that scrapes the recovery info of twitter accounts
The thing is that i need to change proxys every 4 iterations
what i've came up with:

```<code>     from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import smtplib
import time
import sys
import os

#puts all the links into a username
with open('list.txt', 'r') as f:
    users = [line.strip() for line in f]
#where results are stored
result = open(r"results.txt","w")
#stores the proxys
with open('proxy.txt', 'r') as f:
    proxies = [line.strip() for line in f]
counter = 0
for user in users:

    #adding proxy
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--proxy-server=http://%s' % proxies[counter])      #iniatialization of the driver
    browser = webdriver.Chrome(chrome_options=chrome_options)
    counter=counter+1
    #stage 1 username was entered and submitted
    url = 'https://twitter.com/account/begin_password_reset'
    browser.get(url)
    textbox = browser.find_element_by_xpath('/html/body/div[2]/div/form/input[2]')
    textbox.send_keys(user)
    submit_button = browser.find_element_by_xpath('/html/body/div[2]/div/form/input[3]')
    submit_button.click()
    validator= browser.find_element_by_xpath('/html/body/div[2]/div/form/input[2]')
    validator2=browser.find_element_by_xpath('/html/body/div[2]/div/a')
    if not validator or not validator2:

        name = browser.find_element_by_xpath("/html/body/div[2]/div/div[2]/div/div[1]").text
        email= browser.find_element_by_xpath("/html/body/div[2]/div/form/ul/li/label/strong").text
        result.write(user+ ":"+ name+":"+email)

</code>```

the problem i am facing is that the proxies are not iterating and some proxies are dead so its stopping the whole program.

答:
To solve your problem you could implement an approach choosing a different random proxy from your list every four iterations and a try and except block to deal with dead proxies like this:

```<code>import random

for i,user in enumerate(users):
    chrome_options = webdriver.ChromeOptions()
    if i % 4 == 0:
        proxy = random.choice(proxies)
    try:
        chrome_options.add_argument('--proxy-server=http://%s' % proxy)
        # continue with your scraping
    except Exception as e:
        print(e)
</code>```

You can easily improve this snippet, for example by catching the specific error when you run into a dead proxy and delete it from your list (with .pop()) or adding a while loop to repeat the iteration after you ran into an error.

Body:
I am making a twitter scraper that scrapes the recovery info of twitter accounts
The thing is that i need to change proxys every 4 iterations
what i've came up with:

     from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import smtplib
import time
import sys
import os

#puts all the links into a username
with open('list.txt', 'r') as f:
    users = [line.strip() for line in f]
#where results are stored
result = open(r"results.txt","w")
#stores the proxys
with open('proxy.txt', 'r') as f:
    proxies = [line.strip() for line in f]
counter = 0
for user in users:

    #adding proxy
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--proxy-server=http://%s' % proxies[counter])      #iniatialization of the driver
    browser = webdriver.Chrome(chrome_options=chrome_options)
    counter=counter+1
    #stage 1 username was entered and submitted
    url = 'https://twitter.com/account/begin_password_reset'
    browser.get(url)
    textbox = browser.find_element_by_xpath('/html/body/div[2]/div/form/input[2]')
    textbox.send_keys(user)
    submit_button = browser.find_element_by_xpath('/html/body/div[2]/div/form/input[3]')
    submit_button.click()
    validator= browser.find_element_by_xpath('/html/body/div[2]/div/form/input[2]')
    validator2=browser.find_element_by_xpath('/html/body/div[2]/div/a')
    if not validator or not validator2:

        name = browser.find_element_by_xpath("/html/body/div[2]/div/div[2]/div/div[1]").text
        email= browser.find_element_by_xpath("/html/body/div[2]/div/form/ul/li/label/strong").text
        result.write(user+ ":"+ name+":"+email)

the problem i am facing is that the proxies are not iterating and some proxies are dead so its stopping the whole program.

Body:
To solve your problem you could implement an approach choosing a different random proxy from your list every four iterations and a try and except block to deal with dead proxies like this:

import random

for i,user in enumerate(users):
    chrome_options = webdriver.ChromeOptions()
    if i % 4 == 0:
        proxy = random.choice(proxies)
    try:
        chrome_options.add_argument('--proxy-server=http://%s' % proxy)
        # continue with your scraping
    except Exception as e:
        print(e)

You can easily improve this snippet, for example by catching the specific error when you run into a dead proxy and delete it from your list (with .pop()) or adding a while loop to repeat the iteration after you ran into an error.


问:
Map NumPy Values
Let's say I have a NumPy array:

```<code>x = np.array([[0, 5],
              [1, 6],
              [4, 3],
              [2, 4],
              [3, 2]])
</code>```

and a "look-up" array that tells me how to map one integer (first column) to another (second column):

```<code>lookup = np.array([[0, 50],
                   [1, 16],
                   [2, 47],
</code>```

So, 0 -> 50, 1 -> 16, and 2 -> 47. Notice that integers [3, 4, 5, 6] is not in the lookup and therefore do not need to be changed. A simple way to do this is:

```<code>for i in range(lookup.shape[0]):
    num = lookup[i, 0]
    x[x == num] = lookup[i, 1]
</code>```

And the expected output should be:

```<code>np.array([[50, 5],
          [16, 6],
          [4, 3],
          [47, 4],
          [3, 47]])
</code>```

For a big 2D array x and a much larger lookup, is there a more efficient way to do this in a vectorized way in NumPy?

答:
Hope this helps!

```<code>x = np.array([[0, 5],
              [1, 6],
              [4, 3],
              [2, 4],
              [3, 2]])

lookup = np.array([[0, 50],
                   [1, 16],

                   [2, 47]])

# building a dictionary
lookup = {each[0]:each[1] for each in lookup}

vfunc = np.vectorize(lambda x: lookup.get(x, x))

vfunc(x) # gives your result
</code>```

output

array([[50,  5],
       [16,  6],
       [ 4,  3],
       [47,  4],
       [ 3, 47]])
```

Title: Map NumPy Values

Body:
Let's say I have a NumPy array:

x = np.array([[0, 5],
              [1, 6],
              [4, 3],
              [2, 4],
              [3, 2]])

and a "look-up" array that tells me how to map one integer (first column) to another (second column):

lookup = np.array([[0, 50],
                   [1, 16],
                   [2, 47],

So, 0 -> 50, 1 -> 16, and 2 -> 47. Notice that integers [3, 4, 5, 6] is not in the lookup and therefore do not need to be changed. A simple way to do this is:

for i in range(lookup.shape[0]):
    num = lookup[i, 0]
    x[x == num] = lookup[i, 1]

And the expected output should be:

np.array([[50, 5],
          [16, 6],
          [4, 3],
          [47, 4],
          [3, 47]])

For a big 2D array x and a much larger lookup, is there a more efficient way to do this in a vectorized way in NumPy?

Body:
Hope this helps!

x = np.array([[0, 5],
              [1, 6],
              [4, 3],
              [2, 4],
              [3, 2]])

lookup = np.array([[0, 50],
                   [1, 16],

                   [2, 47]])

# building a dictionary
lookup = {each[0]:each[1] for each in lookup}

vfunc = np.vectorize(lambda x: lookup.get(x, x))

vfunc(x) # gives your result

output

array([[50,  5],
       [16,  6],
       [ 4,  3],
       [47,  4],
       [ 3, 47]])


问:
Two times form submitted, when I click the hide and show button
```<code>    **Component.ts**
     hide = true;
  constructor(private userService: UserService,
    private fb: FormBuilder,
    private alertService: AlertService
  ) { }

  signUpForm = this.fb.group({
    _id: ['s'],
    fullName: ['', [Validators.required, Validators.minLength(4)]],
    email: ['', [Validators.required, Validators.email]],
    password: ['', [Validators.required, Validators.minLength(8)]],
    confirmPassword: ['', Validators.required]
  }, { validator: passwordMatchValidator })

  /* Shorthands for form controls (used from within template) */
  get fullName() { return this.signUpForm.get('fullName'); }
  get email() { return this.signUpForm.get('email'); }
  get password() { return this.signUpForm.get('password'); }
  get confirmPassword() { return this.signUpForm.get('confirmPassword'); }

  register() {
    if (this.signUpForm.invalid) {
      return;
    }
    this.userService.register(this.signUpForm.value).subscribe(data => {
      console.log(this.alertService.sucess('Registration Sucessful'));
    }, error => {
      this.alertService.error(error);
    })
  }

    **Component.html**

    <form
      class="example-form"
      [formGroup]="signUpForm"
      (ngSubmit)="register()"
      validate
    >
      <mat-form-field class="example-full-width">
        <mat-label>User Name</mat-label>
        <input matInput formControlName="fullName" />
        <mat-error *ngIf="fullName.hasError('required')">
          User Name is <strong>required</strong>
        </mat-error>
        <mat-error *ngIf="fullName.hasError('minlength')">
          User Name must have at least 4 characters
        </mat-error>
      </mat-form-field>
      <mat-form-field class="example-full-width">
        <mat-label>Email</mat-label>
        <input
          matInput
          formControlName="email"
          placeholder="Ex. pat@example.com"
        />
        <mat-error
          *ngIf="email.hasError('email') && !email.hasError('required')"
        >
          Please enter a valid email address
        </mat-error>
        <mat-error *ngIf="email.hasError('required')">
          Email is <strong>required</strong>
        </mat-error>
      </mat-form-field>
      <div class="example-container">
        <mat-form-field class="example-full-width">
          <mat-label>Password</mat-label>
          <input
            matInput
            (input)="onPasswordInput()"
            [type]="hide ? 'password' : 'text'"
            formControlName="password"
          />
          <mat-error *ngIf="password.hasError('required')"
            >Password is <strong>required</strong></mat-error
          >
          <mat-error *ngIf="password.hasError('minlength')"
            >Password must have at least 8 characters</mat-error
          >
          <button
            mat-icon-button
            matSuffix
            (click)="hide = !hide"
            [attr.aria-label]="'Hide password'"
            [attr.aria-pressed]="hide"
          >
            <mat-icon>{{ hide ? "visibility_off" : "visibility" }}</mat-icon>
          </button>
        </mat-form-field>
      </div>
      <div class="example-container">
        <mat-form-field class="example-full-width">
          <mat-label>Confirm Password</mat-label>
          <input
            matInput
            type="password"
            placeholder="Confirm password"
            formControlName="confirmPassword"
            (input)="onPasswordInput()"
          />
          <mat-error *ngIf="confirmPassword.hasError('required')"
            >Please confirm your password</mat-error
          >
          <mat-error
            *ngIf="
              confirmPassword.invalid && !confirmPassword.hasError('required')
            "
            >Passwords don't match</mat-error
          >
        </mat-form-field>
        <div class="example-button-row">
          <button
            mat-raised-button
            color="primary"
            type="submit"
            [disabled]="!signUpForm.valid"
          >
            Submit
          </button>
          <a mat-raised-button routerLink="/login" color="accent">Cancel</a>
        </div>
      </div>
    </form>
</code>```

When I try to show and hide the password button it working fine with hiding and show functionality, but when I click the same button two or more times continuously it behaves as form submit and showing all forms fields are showing errors how can we resolve it, can anyone help me on this.

When I try to show and hide the password button it working fine with hiding and show functionality, but when I click the same button two or more times continuously it behaves as form submit and showing all forms fields are showing errors how can we resolve it, can anyone help me on this

答: Default type for button are "submit", just include type="button" to avoid it to submit</p>

Body:
    **Component.ts**
     hide = true;
  constructor(private userService: UserService,
    private fb: FormBuilder,
    private alertService: AlertService
  ) { }

  signUpForm = this.fb.group({
    _id: ['s'],
    fullName: ['', [Validators.required, Validators.minLength(4)]],
    email: ['', [Validators.required, Validators.email]],
    password: ['', [Validators.required, Validators.minLength(8)]],
    confirmPassword: ['', Validators.required]
  }, { validator: passwordMatchValidator })

  /* Shorthands for form controls (used from within template) */
  get fullName() { return this.signUpForm.get('fullName'); }
  get email() { return this.signUpForm.get('email'); }
  get password() { return this.signUpForm.get('password'); }
  get confirmPassword() { return this.signUpForm.get('confirmPassword'); }

  register() {
    if (this.signUpForm.invalid) {
      return;
    }
    this.userService.register(this.signUpForm.value).subscribe(data => {
      console.log(this.alertService.sucess('Registration Sucessful'));
    }, error => {
      this.alertService.error(error);
    })
  }

    **Component.html**

    <form
      class="example-form"
      [formGroup]="signUpForm"
      (ngSubmit)="register()"
      validate
    >
      <mat-form-field class="example-full-width">
        <mat-label>User Name</mat-label>
        <input matInput formControlName="fullName" />
        <mat-error *ngIf="fullName.hasError('required')">
          User Name is required
        </mat-error>
        <mat-error *ngIf="fullName.hasError('minlength')">
          User Name must have at least 4 characters
        </mat-error>
      </mat-form-field>
      <mat-form-field class="example-full-width">
        <mat-label>Email</mat-label>
        <input
          matInput
          formControlName="email"
          placeholder="Ex. pat@example.com"
        />
        <mat-error
          *ngIf="email.hasError('email') && !email.hasError('required')"
        >
          Please enter a valid email address
        </mat-error>
        <mat-error *ngIf="email.hasError('required')">
          Email is required
        </mat-error>
      </mat-form-field>

        <mat-form-field class="example-full-width">
          <mat-label>Password</mat-label>
          <input
            matInput
            (input)="onPasswordInput()"
            [type]="hide ? 'password' : 'text'"
            formControlName="password"
          />
          <mat-error *ngIf="password.hasError('required')"
            >Password is required</mat-error
          >
          <mat-error *ngIf="password.hasError('minlength')"
            >Password must have at least 8 characters</mat-error
          >
          <button
            mat-icon-button
            matSuffix
            (click)="hide = !hide"
            [attr.aria-label]="'Hide password'"
            [attr.aria-pressed]="hide"
          >
            <mat-icon>{{ hide ? "visibility_off" : "visibility" }}</mat-icon>
          </button>
        </mat-form-field>

        <mat-form-field class="example-full-width">
          <mat-label>Confirm Password</mat-label>
          <input
            matInput
            type="password"
            placeholder="Confirm password"
            formControlName="confirmPassword"
            (input)="onPasswordInput()"
          />
          <mat-error *ngIf="confirmPassword.hasError('required')"
            >Please confirm your password</mat-error
          >
          <mat-error
            *ngIf="
              confirmPassword.invalid && !confirmPassword.hasError('required')
            "
            >Passwords don't match</mat-error
          >
        </mat-form-field>

          <button
            mat-raised-button
            color="primary"
            type="submit"
            [disabled]="!signUpForm.valid"
          >
            Submit
          </button>
          Cancel

    </form>

When I try to show and hide the password button it working fine with hiding and show functionality, but when I click the same button two or more times continuously it behaves as form submit and showing all forms fields are showing errors how can we resolve it, can anyone help me on this.

When I try to show and hide the password button it working fine with hiding and show functionality, but when I click the same button two or more times continuously it behaves as form submit and showing all forms fields are showing errors how can we resolve it, can anyone help me on this


问:
org.openqa.selenium.SessionNotCreatedException: Unable to find a matching set of capabilities while initiating Firefox v37 through Selenium v3.11.0
I am trying to run test a run a website in Firefox, but I am getting error "The path to the driver executable must be set by the webdriver.gecko.driver system property;" I have set the path correctly, still don't know where the problem is. Here is my code:

```<code>if (browsers.equalsIgnoreCase("Firefox"))
{
        String driverPath = System.getProperty("user.dir") + "\\src/test/java\\drivers\\geckodriver.exe";
        System.setProperty("webdriver.firefox.marionette", "false");
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    } else if (browsers.equalsIgnoreCase("Chrome")) {
        // String driverPath = System.getProperty("user.dir") +
        // "\\src\\Drivers\\chromedriver";
        // System.setProperty("webdriver.chrome.driver", driverPath);
        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    }
</code>```

Here is the Failure Trace of my code:

```<code>FAILED CONFIGURATION: @BeforeClass launchBrowser
org.openqa.selenium.SessionNotCreatedException: Unable to find a matching set of capabilities
Build info: version: '3.8.0', revision: '924c4067df', time: '2017-11-30T11:36:59.109Z'
System info: host: 'DSCHD-PC-180', ip: '192.168.6.122', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_161'
Driver info: driver.version: FirefoxDriver
remote stacktrace:
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$new$0(W3CHandshakeResponse.java:57)
    at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$getResponseFunction$2(W3CHandshakeResponse.java:104)
    at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:123)
    org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:126)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:142)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:219)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:142)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:120)
    at Utility.UtilityMethods.openBrowser(UtilityMethods.java:26)
    at TestCases.LoginTestCase.launchBrowser(LoginTestCase.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:455)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:142)
    at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:168)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:105)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

SKIPPED CONFIGURATION: @AfterClass quitBrowser
SKIPPED: registration
</code>```

答:
I had this error for 2 days, the solution for me was in Set.Platform, put Platform.ANY or Platform.Windows because Platform.WIN10 not worked, marionette wasn't necessary.</p>
```<code>public class Main { public static RemoteWebDriver driver;

public static void main(String[] args) throws MalformedURLException {
    System.setProperty("webdriver.gecko.driver", "D:/Lib/geckodriver.exe");
    DesiredCapabilities desiredCapabilities = new
                                        DesiredCapabilities().firefox();
    desiredCapabilities.setPlatform(Platform.ANY);
    desiredCapabilities.setBrowserName("firefox");

    driver = new RemoteWebDriver(new URL("http://172.20.19.182:5557/wd/hub"),
                                                desiredCapabilities);
    driver.navigate().to("http://www.google.com");
    driver.findElementByName("q").sendKeys("execute automation");
    driver.findElementByName("q").sendKeys(Keys.ENTER);
    driver.close();
    // write your code here
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run test a run a website in Firefox, but I am getting error "The path to the driver executable must be set by the webdriver.gecko.driver system property;" I have set the path correctly, still don't know where the problem is. Here is my code:

if (browsers.equalsIgnoreCase("Firefox"))
{
        String driverPath = System.getProperty("user.dir") + "\\src/test/java\\drivers\\geckodriver.exe";
        System.setProperty("webdriver.firefox.marionette", "false");
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    } else if (browsers.equalsIgnoreCase("Chrome")) {
        // String driverPath = System.getProperty("user.dir") +
        // "\\src\\Drivers\\chromedriver";
        // System.setProperty("webdriver.chrome.driver", driverPath);
        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    }

Here is the Failure Trace of my code:

FAILED CONFIGURATION: @BeforeClass launchBrowser
org.openqa.selenium.SessionNotCreatedException: Unable to find a matching set of capabilities
Build info: version: '3.8.0', revision: '924c4067df', time: '2017-11-30T11:36:59.109Z'
System info: host: 'DSCHD-PC-180', ip: '192.168.6.122', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_161'
Driver info: driver.version: FirefoxDriver
remote stacktrace:
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$new$0(W3CHandshakeResponse.java:57)
    at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$getResponseFunction$2(W3CHandshakeResponse.java:104)
    at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:123)
    org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:126)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:142)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:219)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:142)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:120)
    at Utility.UtilityMethods.openBrowser(UtilityMethods.java:26)
    at TestCases.LoginTestCase.launchBrowser(LoginTestCase.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:455)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:142)
    at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:168)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:105)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

SKIPPED CONFIGURATION: @AfterClass quitBrowser
SKIPPED: registration

Body:
I had this error for 2 days, the solution for me was in Set.Platform, put Platform.ANY or Platform.Windows because Platform.WIN10 not worked, marionette wasn't necessary.

public class Main { public static RemoteWebDriver driver;

public static void main(String[] args) throws MalformedURLException {
    System.setProperty("webdriver.gecko.driver", "D:/Lib/geckodriver.exe");
    DesiredCapabilities desiredCapabilities = new
                                        DesiredCapabilities().firefox();
    desiredCapabilities.setPlatform(Platform.ANY);
    desiredCapabilities.setBrowserName("firefox");

    driver = new RemoteWebDriver(new URL("http://172.20.19.182:5557/wd/hub"),
                                                desiredCapabilities);
    driver.navigate().to("http://www.google.com");
    driver.findElementByName("q").sendKeys("execute automation");
    driver.findElementByName("q").sendKeys(Keys.ENTER);
    driver.close();
    // write your code here
}


问:
jQuery namespace variable undeclared
I have the following JavaScript code:

```<code>function LoadWord(currentLanguage, currentId, isBadWord)
{
    var filePath, badFilePath;
    switch(currentLanguage) {
        case 'spanish':
                filePath = 'data/spanish.xml';
                badFilePath = 'data/badSpanish.xml';
            break;
        case 'catalan':
                filePath = 'data/catalan.xml';
                badFilePath = 'data/badCatalan.xml';
            break;

        default: return;
    }

    $.ajax({
        type: "GET",
        url: filePath,
        dataType: "xml",
        success: function(xml) {
            $(xml).find('word').each(function(){
                if($(this).find('id').text() == $.myNameSpace.cImgId)
                {
                    $.myNameSpace.currentWord = $(this).attr('name');
                    $.ajax({
                        type: "GET",
                        url: badFilePath,
                        dataType: "xml",
                        success: function(xml) {
                            $(xml).find('word').each(function(){
                                for(index = 0; index < 3; index++)
                                {
                                    if($(this).find('id').text() == $.myNameSpace.badWordsIds[index])
                                    {
                                        $.myNameSpace.badWords[index] = $(this).attr('name');
                                    }
                                }
                                UpdateWords();
                            });
                        },
                        error: function(x) { alert(x.responceText); }
                    });
                }
            });
        },
        error: function(x) { alert(x.responceText); }
    });
}

function UpdateWords()
{
    var languageWordPos = randomFromTo(1, 4);
    var index = 1;
    var badWordsIndex = 0;

    while (index < 5) {
        if (index == languageWordPos ) {
            SetTextToButton(index, $.myNameSpace.currentWord);
        }
        else {
            SetTextToButton(index, $.myNameSpace.badWords[badWordsIndex]);
            badWordsIndex++;
        }
        index++;
    }

    LoadUserOwnWord($.myNameSpace.lang, $.myNameSpace.cImgId);
}

function SetTextToButton(index, text)
{
    console.log("SetTextToButton");
    switch(index)
    {
        case 1:
            $('#Word1').html(text);
        break;
        case 2:
            $('#Word2').html(text);
        break;
        case 3:
            $('#Word3').html(text);
        break;
        case 4:
            $('#Word4').html(text);
        break;
        default: return;
    }
}
</code>```

I declare $.myNameSpace.badWords in this line:

```<code>$.myNameSpace.badWords[index] = $(this).attr('name');
</code>```

This line is declared inside second ajax call sucess function.

When I try to get a value from $.myNameSpace.badWords here:

```<code>SetTextToButton(index, $.myNameSpace.badWords[badWordsIndex]);
</code>```

I get an undeclared variable. This line is inside UpdateWords() function.

I'm debugging with FireBug and I can't see BadWords on $.myNameSpace variable.

How can I fix this problem?

答:
The correct answer is that I can't use an Array it is not initialized.

I can do this inside success function:

```<code>$.myNameSpace.badWords = new Array(3);
</code>```

And it will be available to any other function.

Title: jQuery namespace variable undeclared

Body:
I have the following JavaScript code:

function LoadWord(currentLanguage, currentId, isBadWord)
{
    var filePath, badFilePath;
    switch(currentLanguage) {
        case 'spanish':
                filePath = 'data/spanish.xml';
                badFilePath = 'data/badSpanish.xml';
            break;
        case 'catalan':
                filePath = 'data/catalan.xml';
                badFilePath = 'data/badCatalan.xml';
            break;

        default: return;
    }

    $.ajax({
        type: "GET",
        url: filePath,
        dataType: "xml",
        success: function(xml) {
            $(xml).find('word').each(function(){
                if($(this).find('id').text() == $.myNameSpace.cImgId)
                {
                    $.myNameSpace.currentWord = $(this).attr('name');
                    $.ajax({
                        type: "GET",
                        url: badFilePath,
                        dataType: "xml",
                        success: function(xml) {
                            $(xml).find('word').each(function(){
                                for(index = 0; index < 3; index++)
                                {
                                    if($(this).find('id').text() == $.myNameSpace.badWordsIds[index])
                                    {
                                        $.myNameSpace.badWords[index] = $(this).attr('name');
                                    }
                                }
                                UpdateWords();
                            });
                        },
                        error: function(x) { alert(x.responceText); }
                    });
                }
            });
        },
        error: function(x) { alert(x.responceText); }
    });
}

function UpdateWords()
{
    var languageWordPos = randomFromTo(1, 4);
    var index = 1;
    var badWordsIndex = 0;

    while (index < 5) {
        if (index == languageWordPos ) {
            SetTextToButton(index, $.myNameSpace.currentWord);
        }
        else {
            SetTextToButton(index, $.myNameSpace.badWords[badWordsIndex]);
            badWordsIndex++;
        }
        index++;
    }

    LoadUserOwnWord($.myNameSpace.lang, $.myNameSpace.cImgId);
}

function SetTextToButton(index, text)
{
    console.log("SetTextToButton");
    switch(index)
    {
        case 1:
            $('#Word1').html(text);
        break;
        case 2:
            $('#Word2').html(text);
        break;
        case 3:
            $('#Word3').html(text);
        break;
        case 4:
            $('#Word4').html(text);
        break;
        default: return;
    }
}

I declare $.myNameSpace.badWords in this line:

$.myNameSpace.badWords[index] = $(this).attr('name');

This line is declared inside second ajax call sucess function.

When I try to get a value from $.myNameSpace.badWords here:

SetTextToButton(index, $.myNameSpace.badWords[badWordsIndex]);

I get an undeclared variable. This line is inside UpdateWords() function.

I'm debugging with FireBug and I can't see BadWords on $.myNameSpace variable.

How can I fix this problem?

Body:
The correct answer is that I can't use an Array it is not initialized.

I can do this inside success function:

$.myNameSpace.badWords = new Array(3);

And it will be available to any other function.


问:
Transport scheme NOT recognized: [nsp]
I am trying to connect to a SoftwareAg's Universal Messaging queue in a Spring application. This is my Config class.

@Configuration
@EnableJms
public class Config {

    @Bean
    public ActiveMQConnectionFactory receiverActiveMQConnectionFactory() {
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();

        var properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.pcbsys.nirvana.nSpace.NirvanaContextFactory");
        properties.setProperty(Context.PROVIDER_URL, "nsp://localhost:9200");
        activeMQConnectionFactory.buildFromProperties(properties);

        return activeMQConnectionFactory;
    }

    @Bean
    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() {
        var factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(receiverActiveMQConnectionFactory());
        factory.setConcurrency("3-10");
        return factory;
    }

}
```

<p>This is the part of my pom.xml</p>

<pre class="lang-xml prettyprint-override"><code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-broker</artifactId>
</dependency>
<dependency>
    <groupId>com.pcbsys.nirvana</groupId>
    <artifactId>nClient</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>com.pcbsys.nirvana</groupId>
    <artifactId>nJMS</artifactId>
    <version>1.0</version>
</dependency>
</code>```

However, I get the following exception when I try to connect to the queue:

```<code>Caused by: org.springframework.jms.UncategorizedJmsException: Uncategorized exception occurred during JMS processing; nested exception is javax.jms.JMSException: Could not create Transport. Reason: java.io.IOException: Transport scheme NOT recognized: [nsp]
    at org.springframework.jms.support.JmsUtils.convertJmsAccessException(JmsUtils.java:311) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.support.JmsAccessor.convertJmsAccessException(JmsAccessor.java:185) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:507) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.send(JmsTemplate.java:584) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.convertAndSend(JmsTemplate.java:661) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at id.mandiri.co.id.um.Main.lambda$runner$0(Main.java:21) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:784) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    ... 5 common frames omitted
Caused by: javax.jms.JMSException: Could not create Transport. Reason: java.io.IOException: Transport scheme NOT recognized: [nsp]
    at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:36) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:333) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:346) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:304) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:244) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.springframework.jms.support.JmsAccessor.createConnection(JmsAccessor.java:196) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:494) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    ... 9 common frames omitted
Caused by: java.io.IOException: Transport scheme NOT recognized: [nsp]
    at org.apache.activemq.util.IOExceptionSupport.create(IOExceptionSupport.java:28) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.transport.TransportFactory.findTransportFactory(TransportFactory.java:185) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.transport.TransportFactory.connect(TransportFactory.java:64) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:331) ~[activemq-client-5.15.10.jar:5.15.10]
    ... 14 common frames omitted
Caused by: java.io.IOException: Could not find factory class for resource: META-INF/services/org/apache/activemq/transport/nsp
    at org.apache.activemq.util.FactoryFinder$StandaloneObjectFactory.loadProperties(FactoryFinder.java:98) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.util.FactoryFinder$StandaloneObjectFactory.create(FactoryFinder.java:60) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.util.FactoryFinder.newInstance(FactoryFinder.java:148) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.transport.TransportFactory.findTransportFactory(TransportFactory.java:182) ~[activemq-client-5.15.10.jar:5.15.10]
    ... 16 common frames omitted
</code>```

It says here:

UM can be used with Spring. In general, the Spring XML that works for ActiveMQ should work for UM with only the connection factory class and URL changed accordingly.

What am I missing?

Edit:

var properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.pcbsys.nirvana.nSpace.NirvanaContextFactory");
properties.setProperty(Context.PROVIDER_URL, "nsp://localhost:9200");

Context ctx = new InitialContext(properties);
return (ConnectionFactory) ctx.lookup("local_um"); // THIS?
```

答:
As noted, the link you cited states:

In general, the Spring XML that works for ActiveMQ should work for UM with only the connection factory class and URL changed accordingly. [emphasis mine]

However, you haven't changed the connection factory class. The method receiverActiveMQConnectionFactory is returning an instance of ActiveMQConnectionFactory which is wrong. Furthermore, that method is using ActiveMQConnectionFactory.buildFromProperties() with UM properties which is why you're getting the java.io.IOException. You can't mix these two implementations together.

There probably is a way to simply instantiate the UM connection factory implementation (similar to what is possible with the ActiveMQ connection factory implementation), but I think you'd probably have to consult the UM developer guide for that information.

That said, JNDI is the recommended way to get references to admin objects (i.e. connection factories and destinations) so that your JMS applications are portable between providers. Therefore, I recommend you simply use that.

Title: Transport scheme NOT recognized: [nsp]

Body:
I am trying to connect to a SoftwareAg's Universal Messaging queue in a Spring application. This is my Config class.

@Configuration
@EnableJms
public class Config {

    @Bean
    public ActiveMQConnectionFactory receiverActiveMQConnectionFactory() {
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();

        var properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.pcbsys.nirvana.nSpace.NirvanaContextFactory");
        properties.setProperty(Context.PROVIDER_URL, "nsp://localhost:9200");
        activeMQConnectionFactory.buildFromProperties(properties);

        return activeMQConnectionFactory;
    }

    @Bean
    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() {
        var factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(receiverActiveMQConnectionFactory());
        factory.setConcurrency("3-10");
        return factory;
    }

}

This is the part of my pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-broker</artifactId>
</dependency>
<dependency>
    <groupId>com.pcbsys.nirvana</groupId>
    <artifactId>nClient</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>com.pcbsys.nirvana</groupId>
    <artifactId>nJMS</artifactId>
    <version>1.0</version>
</dependency>

However, I get the following exception when I try to connect to the queue:

Caused by: org.springframework.jms.UncategorizedJmsException: Uncategorized exception occurred during JMS processing; nested exception is javax.jms.JMSException: Could not create Transport. Reason: java.io.IOException: Transport scheme NOT recognized: [nsp]
    at org.springframework.jms.support.JmsUtils.convertJmsAccessException(JmsUtils.java:311) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.support.JmsAccessor.convertJmsAccessException(JmsAccessor.java:185) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:507) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.send(JmsTemplate.java:584) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.convertAndSend(JmsTemplate.java:661) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at id.mandiri.co.id.um.Main.lambda$runner$0(Main.java:21) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:784) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    ... 5 common frames omitted
Caused by: javax.jms.JMSException: Could not create Transport. Reason: java.io.IOException: Transport scheme NOT recognized: [nsp]
    at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:36) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:333) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:346) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:304) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:244) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.springframework.jms.support.JmsAccessor.createConnection(JmsAccessor.java:196) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:494) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    ... 9 common frames omitted
Caused by: java.io.IOException: Transport scheme NOT recognized: [nsp]
    at org.apache.activemq.util.IOExceptionSupport.create(IOExceptionSupport.java:28) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.transport.TransportFactory.findTransportFactory(TransportFactory.java:185) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.transport.TransportFactory.connect(TransportFactory.java:64) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:331) ~[activemq-client-5.15.10.jar:5.15.10]
    ... 14 common frames omitted
Caused by: java.io.IOException: Could not find factory class for resource: META-INF/services/org/apache/activemq/transport/nsp
    at org.apache.activemq.util.FactoryFinder$StandaloneObjectFactory.loadProperties(FactoryFinder.java:98) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.util.FactoryFinder$StandaloneObjectFactory.create(FactoryFinder.java:60) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.util.FactoryFinder.newInstance(FactoryFinder.java:148) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.transport.TransportFactory.findTransportFactory(TransportFactory.java:182) ~[activemq-client-5.15.10.jar:5.15.10]
    ... 16 common frames omitted

It says here:

UM can be used with Spring. In general, the Spring XML that works for ActiveMQ should work for UM with only the connection factory class and URL changed accordingly.

What am I missing?

Edit:

var properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.pcbsys.nirvana.nSpace.NirvanaContextFactory");
properties.setProperty(Context.PROVIDER_URL, "nsp://localhost:9200");

Context ctx = new InitialContext(properties);
return (ConnectionFactory) ctx.lookup("local_um"); // THIS?


问:
How to change Fontawesome.wpf Icon in c# code
I'm fairly new to programming in wpf, so this might be pretty basic, but I have no Idea how to change a FontAwesome Icon of a button dynamically (in c# code). I use the nuget package as described in this post here. However the last part:

And finally in your C# code behind:

```<code>using FontAwesome.WPF; // on the top of the code
btnButton.Content = FontAwesomeIcon.LongArrowRight;
</code>```

is not working for me, as it only shows the text "LongArrowRight" after clicking the button.

This is my code:

```<code><Window
...
xmlns:fa="http://schemas.fontawesome.io/icons/">

<Grid>
    <Button x:Name="btnPlay" Click="btnPlay_Click">
        <Button.Content>
            <fa:ImageAwesome Icon="Play"/>
        </Button.Content>
    </Button>
</Grid>

</Window>
</code>```

```<code>using FontAwesome.WPF; // at the top

private bool running = false;
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
     if (running)
     {
         running = false;
         btnPlay.Content = FontAwesomeIcon.Play;
     }
     else
     {
          running = true;
          btnPlay.Content = FontAwesomeIcon.Stop;
     }
}
</code>```

As already stated when the button is clicked it does not show the Icon but only the text "Stop" and when pressed again "Play".

答:
FontAwesomeIcon is enum. When you assign enum value to Button.Content it will be displayed as text.

You need to assign ImageAwesome element to Content:

```<code>btnPlay.Content = new ImageAwesome { Icon = FontAwesomeIcon.LongArrowRight };
btnPlay.Content = new ImageAwesome { Icon = FontAwesomeIcon.Play };
btnPlay.Content = new ImageAwesome { Icon = FontAwesomeIcon.Stop };
</code>```

Body:
I'm fairly new to programming in wpf, so this might be pretty basic, but I have no Idea how to change a FontAwesome Icon of a button dynamically (in c# code). I use the nuget package as described in this post here. However the last part:

And finally in your C# code behind:

using FontAwesome.WPF; // on the top of the code
btnButton.Content = FontAwesomeIcon.LongArrowRight;

is not working for me, as it only shows the text "LongArrowRight" after clicking the button.

This is my code:

<Window
...
xmlns:fa="http://schemas.fontawesome.io/icons/">

<Grid>
    <Button x:Name="btnPlay" Click="btnPlay_Click">
        <Button.Content>
            <fa:ImageAwesome Icon="Play"/>
        </Button.Content>
    </Button>
</Grid>

</Window>

using FontAwesome.WPF; // at the top

private bool running = false;
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
     if (running)
     {
         running = false;
         btnPlay.Content = FontAwesomeIcon.Play;
     }
     else
     {
          running = true;
          btnPlay.Content = FontAwesomeIcon.Stop;
     }
}

As already stated when the button is clicked it does not show the Icon but only the text "Stop" and when pressed again "Play".

Body:
FontAwesomeIcon is enum. When you assign enum value to Button.Content it will be displayed as text.

You need to assign ImageAwesome element to Content:

btnPlay.Content = new ImageAwesome { Icon = FontAwesomeIcon.LongArrowRight };
btnPlay.Content = new ImageAwesome { Icon = FontAwesomeIcon.Play };
btnPlay.Content = new ImageAwesome { Icon = FontAwesomeIcon.Stop };


问:
How can I fix Highcharts error #13?
I use highchart so, the user can close and open the chart page and redraw the chart, in some case give me this error, how can I fix it, Thanks
Here is my code

```<code> function populateGraph(graph1data1,graph1data2,id,time,bottomText,tickinterval){
$(function () {
  $('#'+id).highcharts({
      chart: {
          type: 'line'
      },
      xAxis: {
        tickWidth: 0,
        categories: ['1,2,3,4']
      },
      yAxis: {
        gridLineColor: '#fff',
          title: {
              text: ''
          },
          labels: {
              formatter: function() {
                  return '';
              }
          }
      },
      navigation: {
        buttonOptions: {
            enabled: false
        }
    },
      series: [{
          name: 'This ',
          data: [1,2,3,4],
          color: '#1e71ef'
      }, {
          name: 'Last ',
          data: [5,6,7,8],
          color:'#dfe0e1'
      }]
  });
});
}
}

       function loadOnlineDashboardChannel(channel){
          $.ajax({
          type: "get",
          dataType: 'html',
          data: {},
          url: "/companies/2/online_dashboard_channel",
          success: function(data, status){
          var obj = JSON.parse(data);
          var template_data = {
            measures_list:
              obj.measures
          };
          $(function() {
        var tmplHTML_measures = '{{#measures_list}} <div class="col-lg-11  col-lg-offset-1"><p class="indicator-title gray-bottom-border">{{name}}</br></p><div><p><span class="font30px">{{total}} </span> Total {{name}}<br><span class="green-text">{{increase}}%</span> from last <span class="metric_time"></span></p></div><div class="graph-header"><h3>{{this_interval}} </h3><p>New {{name}}</p><p class="percentage-graph green-text">{{percentag e}}%<p></div><div id={{graph_id}} class="graph"></div> </div>{{/measures_list}}';
          Handlebars.render = function(tmpl, data){data = data || {};return                                                       Handlebars.compile(tmpl)(data);};
      $("#template").empty().append(Handlebars.render(tmplHTML_measures,template_data) );
      var data_graph;
      for ( var i = 0; i < obj.measures.length; i++ ) {
        data_graph=obj.measures[i];
                      populateGraph(data_graph.this_interval_detail,data_graph.last_interval_detail,data_graph.graph_id,time,obj.bottom_graph_text,parseInt($('#timeframe-select').find(":selected").attr('interval')) );
      }
     })

  },
  error: function(error) {

}
});

return this;
};
</code>```

I use handlebar so in this part

in
               var tmplHTML_measures
I create the div, in the for I call the function to draw the chart.

Thanks, I repeat sometimes it works perfectly and sometimes fail give me the error #13

答:
This is an old question, but none of the answers are really satisfactory in my opinion. </p>

<p>I would suggest checking to make sure the chart div exists before rendering the chart. </p>

```<code>if($('#'+id).length){ $('#'+id).highcharts({});}
</code>```

Title: How can I fix Highcharts error #13?

Body:
I use highchart so, the user can close and open the chart page and redraw the chart, in some case give me this error, how can I fix it, Thanks
Here is my code

 function populateGraph(graph1data1,graph1data2,id,time,bottomText,tickinterval){
$(function () {
  $('#'+id).highcharts({
      chart: {
          type: 'line'
      },
      xAxis: {
        tickWidth: 0,
        categories: ['1,2,3,4']
      },
      yAxis: {
        gridLineColor: '#fff',
          title: {
              text: ''
          },
          labels: {
              formatter: function() {
                  return '';
              }
          }
      },
      navigation: {
        buttonOptions: {
            enabled: false
        }
    },
      series: [{
          name: 'This ',
          data: [1,2,3,4],
          color: '#1e71ef'
      }, {
          name: 'Last ',
          data: [5,6,7,8],
          color:'#dfe0e1'
      }]
  });
});
}
}

       function loadOnlineDashboardChannel(channel){
          $.ajax({
          type: "get",
          dataType: 'html',
          data: {},
          url: "/companies/2/online_dashboard_channel",
          success: function(data, status){
          var obj = JSON.parse(data);
          var template_data = {
            measures_list:
              obj.measures
          };
          $(function() {
        var tmplHTML_measures = '{{#measures_list}}

{{name}}

{{total}}  Total {{name}}
{{increase}}% from last

{{this_interval}}

New {{name}}

{{percentag e}}%

{{/measures_list}}';
          Handlebars.render = function(tmpl, data){data = data || {};return                                                       Handlebars.compile(tmpl)(data);};
      $("#template").empty().append(Handlebars.render(tmplHTML_measures,template_data) );
      var data_graph;
      for ( var i = 0; i < obj.measures.length; i++ ) {
        data_graph=obj.measures[i];
                      populateGraph(data_graph.this_interval_detail,data_graph.last_interval_detail,data_graph.graph_id,time,obj.bottom_graph_text,parseInt($('#timeframe-select').find(":selected").attr('interval')) );
      }
     })

  },
  error: function(error) {

}
});

return this;
};

I use handlebar so in this part

in
               var tmplHTML_measures
I create the div, in the for I call the function to draw the chart.

Thanks, I repeat sometimes it works perfectly and sometimes fail give me the error #13

Body:
This is an old question, but none of the answers are really satisfactory in my opinion.

I would suggest checking to make sure the chart div exists before rendering the chart.

if($('#'+id).length){ $('#'+id).highcharts({});}


问:
Typescript throws "is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }"
I know this has been discussed at length, but not other SO solutions seem to work, or I fail at implementing them.

I am brand new to typescript, and have the following:

```<code>import faker from "faker";
import React from "react";
import Index from "../components/Index";
import List from "../components/List";

interface Props {
  departments: [
    {
      id: number;
      name: string;
    }
  ];
}

const IndexPage: React.FunctionComponent<Props> = ({ departments }) => {
  return (
    <>
      <Index />
      <List departments={departments} />
    </>
  );
};

export async function getStaticProps() {
  let departments: { id: number; name: string }[] = [];

  for (let i = 0; i < 50; i += 1) {
    const name: string = await faker.company.companyName();
    departments = [...departments, { id: i, name }];
  }

  return {
    props: {
      departments,
    },
  };
}

export default IndexPage;
</code>```

While I am not sure I even implemented TypeScript correctly, the compiler throws this error:

Type '{ departments: [{ id: number; name: string; }]; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
Property 'departments' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.

The compiler underlines the departments prop on the <List> component.

Why is this error being thrown, and how do I fix it?

答:
Typescript is trying to tell you that you're trying to give the property departments to an object (in this case, a React component) which doesn't have that property on its type.

The type 'IntrinsicAttributes & { children?: ReactNode; }' is just the default typing for a react component; provided that departments is not included in the props of that type (and it isn't) then you can't pass that prop to the List component.

To fix this, you just need to add departmentsto the definition of List's props

Body:
I know this has been discussed at length, but not other SO solutions seem to work, or I fail at implementing them.

I am brand new to typescript, and have the following:

import faker from "faker";
import React from "react";
import Index from "../components/Index";
import List from "../components/List";

interface Props {
  departments: [
    {
      id: number;
      name: string;
    }
  ];
}

const IndexPage: React.FunctionComponent<Props> = ({ departments }) => {
  return (
    <>
      <Index />
      <List departments={departments} />
    </>
  );
};

export async function getStaticProps() {
  let departments: { id: number; name: string }[] = [];

  for (let i = 0; i < 50; i += 1) {
    const name: string = await faker.company.companyName();
    departments = [...departments, { id: i, name }];
  }

  return {
    props: {
      departments,
    },
  };
}

export default IndexPage;

While I am not sure I even implemented TypeScript correctly, the compiler throws this error:

Type '{ departments: [{ id: number; name: string; }]; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
Property 'departments' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.

The compiler underlines the departments prop on the <List> component.

Why is this error being thrown, and how do I fix it?


问:
How can I stop Microsoft Dynamics NAV instance to start automatically after server restart
When my server restart, I would like that my NAV instance does not restart automatically

Do you know where do I have to do the setup for this?

答:
Ok I found how to do that.
You just have to go to the instance properties in the list of the windows services, and there you have an option to say if you want to restart the instance automatically or manually </p>


问:
How to overwrite jquery event handlers
I'll try to explain the problem with a simple code.

```<code>var fireClick = function() { alert('Wuala!!!') };

$('#clickme').click(fireclick);
$('#clickme').click(fireclick);
</code>```

So now it will obviously alert 2 times but i need it alert only once. Tried so many ways, but no result.

Thanks.

答:
```<code>$(document).off('click', '#clickme').on('click', '#clickme', fireclick);
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to overwrite jquery event handlers

Body:
I'll try to explain the problem with a simple code.

var fireClick = function() { alert('Wuala!!!') };

$('#clickme').click(fireclick);
$('#clickme').click(fireclick);

So now it will obviously alert 2 times but i need it alert only once. Tried so many ways, but no result.

Thanks.


问:
Increment hex string
I'm trying to increment an hex string like this:

```
#$67#$1c#$87#$b1;
#$67#$1c#$87#$b2;
#$67#$1c#$87#$b3;
```

Here's my procedure:

```<code>var test : array [0..3] of char; intSequence : cardinal;

Sequence := #$67#$1c#$87#$b1;

procedure IncSequence;
begin
  move(Sequence[1],intSequence,SizeOF(Sequence));
  inc(intSequence);
  move(intSequence,Sequence[1],SizeOf(test));
end;
</code>```

Whith this procedure, only the second byte increment.
The result is:

```
#$67#$1D#$87#$B1
#$67#$1E#$87#$B1
#$67#$1F#$87#$B1
```

Thanks

答:
If you want to increment the sequence, you should do something like:

```<code>move(Sequence[0], intSequence, SizeOf(Cardinal));
inc(intSequence);
move(intSequence, Sequence[0], SizeOf(Cardinal));
</code>```

Your code doesn't work because Sequence[1] points to the second byte of Sequence (arrays start with 0) and both Sequence and test consist of bytes/chars, so only 1 byte gets transferred.

EDIT: After trying this, I saw that intSequence is stored in "backwards" byte order, this increments the first byte of Sequence, so you perhaps want to reverse Sequence before.

Title: Increment hex string

Body:
I'm trying to increment an hex string like this:

#$67#$1c#$87#$b1;
#$67#$1c#$87#$b2;
#$67#$1c#$87#$b3;

Here's my procedure:

var test : array [0..3] of char; intSequence : cardinal;

Sequence := #$67#$1c#$87#$b1;

procedure IncSequence;
begin
  move(Sequence[1],intSequence,SizeOF(Sequence));
  inc(intSequence);
  move(intSequence,Sequence[1],SizeOf(test));
end;

Whith this procedure, only the second byte increment.
The result is:

#$67#$1D#$87#$B1
#$67#$1E#$87#$B1
#$67#$1F#$87#$B1

Thanks

LastEditorDisplayName: Tomalak

Body:
If you want to increment the sequence, you should do something like:

move(Sequence[0], intSequence, SizeOf(Cardinal));
inc(intSequence);
move(intSequence, Sequence[0], SizeOf(Cardinal));

Your code doesn't work because Sequence[1] points to the second byte of Sequence (arrays start with 0) and both Sequence and test consist of bytes/chars, so only 1 byte gets transferred.

EDIT: After trying this, I saw that intSequence is stored in "backwards" byte order, this increments the first byte of Sequence, so you perhaps want to reverse Sequence before.

OwnerDisplayName: schnaader

LastEditorDisplayName: schnaader


问:
Inspecting HTTP POST headers in Python without downloading body
A web server responds to a POST request with a file to download (has Content-Disposition header). Using urllib or mechanize opener at what point will the response body be downloaded?

```<code>opener = mechanize.build_opener(HTTPRefererProcessor, HTTPEquivProcessor, HTTPRefreshProcessor)
r = make_post_request() # makes Request object to send
res = opener.open(r)
info = response.info()
content_disp = info.getheader('content-disposition')
filename = content_disp.split('=')[1]
content = res.read() # or skip based on filename
</code>```

I was under the impression that the body won't download until read(), which would be useful for skipping certain download (such as files already downloaded) but I am not seeing great deal of performance improvement.

答:
Well, when you just want headers, you should be using HTTP HEAD. POST and GET will by definition return content.

In terms of stopping the download, the web server won't wait to start sending you data, and everything from Python to your network card will start receiving and buffering the data immediately.

So your best bet is to find a better way of doing this -- HTTP HEAD for example. If that's not an option, call close() on your request object immediately after getting whatever headers you need and hope you didn't waste too much bandwidth.

(And for an example on using HTTP HEAD in Python, see this answer from a while ago.)

Body:
A web server responds to a POST request with a file to download (has Content-Disposition header). Using urllib or mechanize opener at what point will the response body be downloaded?

opener = mechanize.build_opener(HTTPRefererProcessor, HTTPEquivProcessor, HTTPRefreshProcessor)
r = make_post_request() # makes Request object to send
res = opener.open(r)
info = response.info()
content_disp = info.getheader('content-disposition')
filename = content_disp.split('=')[1]
content = res.read() # or skip based on filename

I was under the impression that the body won't download until read(), which would be useful for skipping certain download (such as files already downloaded) but I am not seeing great deal of performance improvement.


问:
When accessing C++ API from C via a wrapper, how do I access enum types?
I have a C program which I need to connect to a C++ API.  I asked on here and was given great advice, leading to creating a "wrapper".

So, in the API there is a type called "APIName::ReturnCode", and I wanted to create a C equivalent, so I've done the following:

In c_api.h:

```<code>#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif

typedef void* API_ReturnCode_t;
EXTERNC API_ReturnCode_t api_returncode_init();
EXTERNC void api_returncode_destroy(API_ReturnCode_t rc);

#undef EXTERNC
</code>```

in c_api.cpp:

```<code>#include "c_api.h"
#include "/path/to/api/api.h"

API_ReturnCode_t api_returncode_init() {
        return new APIName::ReturnCode;
}

void api_returncode_destroy(API_ReturnCode_t untyped_ptr) {
        APIName::ReturnCode* typed_ptr = static_cast< APIName::ReturnCode*>(untyped_ptr);
        delete typed_ptr;
}
</code>```

So I compile that into a library and include it in my main program, and I can use things like:

```<code>API_ReturnCode rc;
</code>```

to define a variable.

However, my next issue is how to define enumerated types in a similar way.  So, the api has the following definition for error codes:

```<code>namespace APIName {

    typedef enum ReturnCode_enum ReturnCode;

    enum ReturnCode_enum {
        RC_OK                               ,   // success
        RC_ERROR                            ,   // general error
        RC_NOT_AVAILABLE                    ,   // feature is not available
    };
}
</code>```

How do I recreate this in my wrapper so that I can do something like this in my code:

```<code>API_ReturnCode rc = API_RC_OK;
</code>```

Thank you.

答:
So after some clarification, my original answer is no longer applicable -- but is still retained below this answer.

Since the original C++ API cannot be altered in any way, you are much more limited in your available options.

You want to be able to do:

API_ReturnCode rc = API_RC_OK;
```

<p>But <code>rc</code> is an opaque type (<code>void*</code>) that requires being destroyed with <code>api_returncode_destroy</code> -- so this won't be possible in an easy and sane way (not without confusing who owns the <code>API_RC_OK</code> calls). The biggest issue is that if we could produce an <code>API_RC_OK</code> instance, it leads to questionable ownership. For example:</p>

<pre class="lang-c prettyprint-override"><code>API_ReturnCode rc = API_RC_OK;
api_returncode_destroy(rc); // is this good? is 'API_RC_OK' a resource that needs deleting?
</code>```

And it gets more confusing in more complicated expressions.

Since the APIName::ReturnCode_enum type is just a classic C-style enum, which is implicitly convertible to an int, your best-bet here would be to try to preserve the int-like property by making API_ReturnCode_t's definition be:

typedef int API_ReturnCode_t;
```

<p>Then any of the C++-wrapped calls can propagate the values as this <code>int</code></p>

<p>Unfortunately to be able to receive these values on the other side, you will need to duplicate some effort here by manually re-creating these constants in some way. There are a few approaches that come to mind, all with pros and cons.</p>

<p>The inconvenient truth here is that, because you're trying to expose values defined in C++ in C, you'll need to somehow re-encode this on the other side in some way. You can't simply include the C++ header and use it in C, since they are different languages and C++ contains features that C doesn't understand.</p>

<h2>1. Use <code>extern</code> constants</h2>

<p>One possible approach is to use <code>extern const</code> values that get defined in the source from the underlying values, so you aren't stuck duplicating the values themselves. For example:</p>

<p><strong>c_api.h</strong></p>

<pre class="lang-c prettyprint-override"><code>EXTERNC extern const API_ReturnCode_t API_RC_OK;
EXTERNC extern const API_ReturnCode_t API_RC_ERROR;
EXTERNC extern const API_ReturnCode_t API_RC_NOT_AVAILABLE;
</code>```

c_api.cpp

extern "C" {

const API_ReturnCode_t API_RC_OK = APIName::RC_OK;
const API_ReturnCode_t API_RC_ERROR = APIName::RC_ERROR;
const API_ReturnCode_t API_RC_NOT_AVAILABLE = APIName::RC_NOT_AVAILABLE;

} // extern "C"
```

<p>The good thing with this approach is that you aren't stuck manually setting <code>API_RC_OK</code> to <code>0</code>, and <code>API_RC_ERROR</code> to <code>1</code>, etc -- so these values are not strongly coupled.</p>

<p>The thing to watch out for is that these <code>extern</code> constants would not be (safely) usable from other objects during <code>static</code> initialization, since it's not guaranteed when these values will be set. If you aren't doing much <code>static</code> initialization, this shouldn't be of any concern.</p>

<h2>2. Just duplicate the effort</h2>

<p>If the enum is not large, and not likely to grow much larger, the obvious simple approach is to just do:</p>

<pre class="lang-c prettyprint-override"><code>#define API_RC_OK 0
#define API_RC_ERROR 1
#define API_RC_NOT_AVAILABLE 2
</code>```

or some equivalent thereof. The pro is that this can be used anywhere, compared to extern constants. The obvious con here is that the wrapper is strongly coupled to the wrapped library. If this is a large enumeration, or an enum that is likely to change often / regularly -- this is approach is probably not the best.

3. Define a possibly-orthogonal enumeration

One other option is to define an orthogonal enumeration instead. This requires re-defining the enum cases that you care about, and translating them through a separate function call. This results in more effort -- so depending on what you're doing, this may not be the best case.

c_api.h

typedef enum {
    API_RC_OK,
    API_RC_ERROR,
    API_RC_NOT_AVAILABLE,
    /* other states? */
} API_ReturnCode_t;
```

<p>**c_api.cpp</p>

<pre class="lang-cpp prettyprint-override"><code>API_ReturnCode_t to_return_code(APIName::ReturnCode rc)
{
    switch (rc) {
        case APIName::RC_OK: return API_RC_OK;
        case APIName::RC_ERROR: return API_RC_ERROR;
        case APIName::RC_NOT_AVAILABLE: return API_RC_NOT_AVAILABLE;
    }
    return API_RC_NOT_AVAILABLE;
}
</code>```

In your wrapper code, anywhere you receive an APIName::ReturnCode you would now translate to an API_ReturnCode_t before returning back to the C caller.

The nice thing about this approach is that the enumerators no longer need to be in-sync, and that you can restrict the enum cases that you want to abstract out (assuming you don't want 1-1 mapping).

This also presents an easier way to upgrade in the future to different versions of the C++ library, since everything is internalized by the translation function. If the C++ library introduces new states, you can choose to coalesce some of those values together in a way that may make it more consumable by the C client.

The obvious downside with this approach is that it takes more work, since you're defining a separate hierarchy and a translation system that will be quite similar in the beginning. It's more work up-front for a higher return later on.

Old Answer

There is nothing specific to C++ about your ReturnCode_enum class. It's actually written in a more legacy-C++ style (e.g. not using enum class for scoping), which makes it usable in C directly.

So why not define the enum in the c_api.h header file instead, and use it in your C++ as well? This may require changing your opaque handle definition depending on what is stored in it; but this way you would have exactly 1 definition of the enumeration.

You can bring the C symbol into C++ namespaces using either typedef or using aliases, which allow a more C++-esque discovery of the values.

In c_api.h:

enum Api_ReturnCode_enum {
    RC_OK                               ,   /* success */
    RC_ERROR                            ,   /* general error */
    RC_NOT_AVAILABLE                    ,   /* feature is not available */
};
/*
or 'typedef enum { ... } Api_ReturnCode_enum;' if you want don't want to specify
'enum' every time in C
*/
```

<p>In your C++ API:</p>

<pre class="lang-cpp prettyprint-override"><code>#include "c_api.h"

namespace APIName { // bring it into this namespace:

    // Alias the "Api_" prefixed enum to be more C++ like
    typedef Api_ReturnCode_enum ReturnCode;

    // alternative, in C++11 or above:
    // using ReturnCode = Api_ReturnCode_enum;
}
</code>```

Body:
I have a C program which I need to connect to a C++ API.  I asked on here and was given great advice, leading to creating a "wrapper".

So, in the API there is a type called "APIName::ReturnCode", and I wanted to create a C equivalent, so I've done the following:

In c_api.h:

#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif

typedef void* API_ReturnCode_t;
EXTERNC API_ReturnCode_t api_returncode_init();
EXTERNC void api_returncode_destroy(API_ReturnCode_t rc);

#undef EXTERNC

in c_api.cpp:

#include "c_api.h"
#include "/path/to/api/api.h"

API_ReturnCode_t api_returncode_init() {
        return new APIName::ReturnCode;
}

void api_returncode_destroy(API_ReturnCode_t untyped_ptr) {
        APIName::ReturnCode* typed_ptr = static_cast< APIName::ReturnCode*>(untyped_ptr);
        delete typed_ptr;
}

So I compile that into a library and include it in my main program, and I can use things like:

API_ReturnCode rc;

to define a variable.

However, my next issue is how to define enumerated types in a similar way.  So, the api has the following definition for error codes:

namespace APIName {

    typedef enum ReturnCode_enum ReturnCode;

    enum ReturnCode_enum {
        RC_OK                               ,   // success
        RC_ERROR                            ,   // general error
        RC_NOT_AVAILABLE                    ,   // feature is not available
    };
}

How do I recreate this in my wrapper so that I can do something like this in my code:

API_ReturnCode rc = API_RC_OK;

Thank you.

Body:
So after some clarification, my original answer is no longer applicable -- but is still retained below this answer.

Since the original C++ API cannot be altered in any way, you are much more limited in your available options.

You want to be able to do:

API_ReturnCode rc = API_RC_OK;

But rc is an opaque type (void*) that requires being destroyed with api_returncode_destroy -- so this won't be possible in an easy and sane way (not without confusing who owns the API_RC_OK calls). The biggest issue is that if we could produce an API_RC_OK instance, it leads to questionable ownership. For example:

API_ReturnCode rc = API_RC_OK;
api_returncode_destroy(rc); // is this good? is 'API_RC_OK' a resource that needs deleting?

And it gets more confusing in more complicated expressions.

Since the APIName::ReturnCode_enum type is just a classic C-style enum, which is implicitly convertible to an int, your best-bet here would be to try to preserve the int-like property by making API_ReturnCode_t's definition be:

typedef int API_ReturnCode_t;

Then any of the C++-wrapped calls can propagate the values as this int

Unfortunately to be able to receive these values on the other side, you will need to duplicate some effort here by manually re-creating these constants in some way. There are a few approaches that come to mind, all with pros and cons.

The inconvenient truth here is that, because you're trying to expose values defined in C++ in C, you'll need to somehow re-encode this on the other side in some way. You can't simply include the C++ header and use it in C, since they are different languages and C++ contains features that C doesn't understand.

1. Use extern constants

One possible approach is to use extern const values that get defined in the source from the underlying values, so you aren't stuck duplicating the values themselves. For example:

c_api.h

EXTERNC extern const API_ReturnCode_t API_RC_OK;
EXTERNC extern const API_ReturnCode_t API_RC_ERROR;
EXTERNC extern const API_ReturnCode_t API_RC_NOT_AVAILABLE;

c_api.cpp

extern "C" {

const API_ReturnCode_t API_RC_OK = APIName::RC_OK;
const API_ReturnCode_t API_RC_ERROR = APIName::RC_ERROR;
const API_ReturnCode_t API_RC_NOT_AVAILABLE = APIName::RC_NOT_AVAILABLE;

} // extern "C"

The good thing with this approach is that you aren't stuck manually setting API_RC_OK to 0, and API_RC_ERROR to 1, etc -- so these values are not strongly coupled.

The thing to watch out for is that these extern constants would not be (safely) usable from other objects during static initialization, since it's not guaranteed when these values will be set. If you aren't doing much static initialization, this shouldn't be of any concern.

2. Just duplicate the effort

If the enum is not large, and not likely to grow much larger, the obvious simple approach is to just do:

#define API_RC_OK 0
#define API_RC_ERROR 1
#define API_RC_NOT_AVAILABLE 2

or some equivalent thereof. The pro is that this can be used anywhere, compared to extern constants. The obvious con here is that the wrapper is strongly coupled to the wrapped library. If this is a large enumeration, or an enum that is likely to change often / regularly -- this is approach is probably not the best.

3. Define a possibly-orthogonal enumeration

One other option is to define an orthogonal enumeration instead. This requires re-defining the enum cases that you care about, and translating them through a separate function call. This results in more effort -- so depending on what you're doing, this may not be the best case.

c_api.h

typedef enum {
    API_RC_OK,
    API_RC_ERROR,
    API_RC_NOT_AVAILABLE,
    /* other states? */
} API_ReturnCode_t;

**c_api.cpp

API_ReturnCode_t to_return_code(APIName::ReturnCode rc)
{
    switch (rc) {
        case APIName::RC_OK: return API_RC_OK;
        case APIName::RC_ERROR: return API_RC_ERROR;
        case APIName::RC_NOT_AVAILABLE: return API_RC_NOT_AVAILABLE;
    }
    return API_RC_NOT_AVAILABLE;
}

In your wrapper code, anywhere you receive an APIName::ReturnCode you would now translate to an API_ReturnCode_t before returning back to the C caller.

The nice thing about this approach is that the enumerators no longer need to be in-sync, and that you can restrict the enum cases that you want to abstract out (assuming you don't want 1-1 mapping).

This also presents an easier way to upgrade in the future to different versions of the C++ library, since everything is internalized by the translation function. If the C++ library introduces new states, you can choose to coalesce some of those values together in a way that may make it more consumable by the C client.

The obvious downside with this approach is that it takes more work, since you're defining a separate hierarchy and a translation system that will be quite similar in the beginning. It's more work up-front for a higher return later on.

Old Answer

There is nothing specific to C++ about your ReturnCode_enum class. It's actually written in a more legacy-C++ style (e.g. not using enum class for scoping), which makes it usable in C directly.

So why not define the enum in the c_api.h header file instead, and use it in your C++ as well? This may require changing your opaque handle definition depending on what is stored in it; but this way you would have exactly 1 definition of the enumeration.

You can bring the C symbol into C++ namespaces using either typedef or using aliases, which allow a more C++-esque discovery of the values.

In c_api.h:

enum Api_ReturnCode_enum {
    RC_OK                               ,   /* success */
    RC_ERROR                            ,   /* general error */
    RC_NOT_AVAILABLE                    ,   /* feature is not available */
};
/*
or 'typedef enum { ... } Api_ReturnCode_enum;' if you want don't want to specify
'enum' every time in C
*/

In your C++ API:

#include "c_api.h"

namespace APIName { // bring it into this namespace:

    // Alias the "Api_" prefixed enum to be more C++ like
    typedef Api_ReturnCode_enum ReturnCode;

    // alternative, in C++11 or above:
    // using ReturnCode = Api_ReturnCode_enum;
}