问:
Extra segment won't register color data in assembly
I am programming a game similar to breakout in assembly (tools:DosBOX, notepad++, tasm), and whilst creating the borders and platform in Graphics mode, I've stumbled upon 2 problems:

It seems as if the extra segment won't register the color information, as I can't get it right and when I try to pull it gives me a 0 which is black, as opposed to white which is 0Fh.

It's a slight problem which I tried to resolve, but for some reason, when when I try to paint the second and third border, a part of the 1st border turns black, you'll see it if you run the code. I wasn't able to determine why it happens and the debugger didn't show anything odd.

This is my current code, the main procedures that are involved in the creating of the borders, platform and movement of the platform are BorderPaint, PlatBuild and PlatMove

```<code>    IDEAL
    MODEL small
    STACK 100h
    DATASEG
    platLoc dw 63806
    speed1 dw 10
    speed2 dw 0FFFFh
    CODESEG
    ;procedure to paint borders-6 px white pixels
    proc BorderPaint
        push ax
        push bx
        push di
        push cx

    mov ax,0A000h ;accesses graphics mode video memory
    mov es,ax
    xor di,di

    ;first line-left vertical
    ;sets color white

    mov ax,0Fh
    mov cx,200 ;enters nested loop
    FirstLoop1:
    push cx
    mov cx,6
    SecondLoop1:
    mov [es:di],ax
    inc di
    loop SecondLoop1
    sub di,6
    add di,320
    pop cx
    loop FirstLoop1
    ;second line- up horizontal
    mov di,7
    mov cx,313
    FirstLoop2:
    push cx
    mov cx,6
    SecondLoop2:
    mov [es:di],ax
    add di,320
    loop SecondLoop2
    sub di,1920
    inc di
    pop cx
    loop FirstLoop2

    mov di,314
    mov cx,200
    FirstLoop3:
    push cx
    mov cx,6
    SecondLoop3:
    mov [es:di],ax
    inc di
    loop SecondLoop3
    sub di,6
    add di,320
    pop cx
    loop FirstLoop3

    ; xor di,di
    ; mov ax,0Fh
    ; mov cx,200
    ; FirstLoop4:
    ; push cx
    ; mov cx,6
    ; SecondLoop4:
    ; mov [es:di],ax
    ; inc di
    ; loop SecondLoop4
    ; sub di,6
    ; add di,320
    ; pop cx
    ; loop FirstLoop4

        pop cx
        pop di
        pop bx
        pop ax
    ret
    endp BorderPaint

    proc PlatBuild
    push di
    push cx
    push ax
        mov di,[platLoc]
        mov ax,5
        mov cx,40
        LoopPaint2:
        push cx
        mov cx,10
        LoopPaint1:
        mov [es:di],ax
        sub di,320
        loop LoopPaint1
        add di,320*10
        inc di
        pop cx
        loop LoopPaint2
    pop ax
    pop cx
    pop di
    ret
    endp PlatBuild

    Proc PlatErase
    push di
    push cx
    push ax
        mov di,[platLoc]
        mov ax,0
        mov cx,40
        LoopPaint4:
        push cx
        mov cx,10
        LoopPaint3:
        mov [es:di],ax
        sub di,320
        loop LoopPaint3
        add di,320*10
        inc di
        pop cx
        loop LoopPaint4
    pop ax
    pop cx
    pop di
    ret
    endp PlatErase

    Proc PlatMove
    push ax
    push cx
    push dx
    push di
        mov ax,0A000h
        mov es,ax
        call BorderPaint
        ;Input
        CheckPress1:
        mov ah,0h
        int 16h

        cmp al,'a'
        jne nxt11
        jmp MoveLeft1
         Nxt11:
        cmp al,'d'
        jne nxt12
        jmp MoveRight1
        Nxt12:
        cmp al,'q'
        jne CheckPress1
        jmp endproc1

        MoveLeft1:
        call Delay
        mov dx,[platLoc]
        add dx,8*320
        sub dx,1d
        mov di,dx
        mov ax,[es:di]
        cmp ax,0Fh
        jne move1
        jmp CheckPress1
        move1:
        call PlatErase
        dec [platLoc]
        call PlatBuild
        mov ah,1h
        int 16h
        je MoveLeft1
        jmp CheckPress1

        MoveRight1:
        call Delay
        mov dx,[platLoc]
        add dx,41

        mov di,dx
        mov ax,[es:di]
        cmp ax,0Fh
        jne move2
        jmp CheckPress1
        move2:
        call PlatErase
        inc [platLoc]
        call PlatBuild
        mov ah,1h
        int 16h
        je MoveRight1
        jmp CheckPress1
        EndProc1:
    pop di
    pop dx
    pop cx
    pop ax
        ret
        endp PlatMove
        proc Delay
    push cx
        mov cx, [speed2]
    LoopLong:
    push cx
        mov cx, [speed1]
      LoopShort:
        loop LoopShort
    pop cx
        loop LoopLong
    pop cx
    ret
    Endp Delay
    start:
        mov ax,@data
        mov ds,ax
        mov ax,13h
        int 10h
        call BorderPaint
        call PlatBuild
        mov ax, [es:63680]
        call PlatMove

    exit:
        mov ax,4c00h
        int 21h
    END startenter code here
</code>```

答:
The problem with reading and writing

Since your program works with the 320x200 256-colors video mode 13h, every pixel is represented by a single byte in VRAM. The foremost problem in your code, and Ped7g already pointed this out, is that you consistently read and write words where you should be reading and writing bytes.

I'll show what we mean by writing the corrections for the topside border. Don't forget to make similar changes everywhere else!

```<code>;second line- up horizontal
    mov di,6          ; (6,0)   <--- See 1.
    mov cx,320-6-6    ; Width   <--- See 2.
FirstLoop2:
    push cx
    mov cx,6          ; Height
  SecondLoop2:
    mov [es:di],al    ; Color 0Fh, Byte from AL instead of word from AX
    add di,320        ; Go down 1 line
    loop SecondLoop2
    sub di,320*6      ; Take back 6 additions of 320
    inc di            ; Go right 1 pixel
    pop cx
    loop FirstLoop2
</code>```

I chose this part because it also had some additional errors:

Given that the leftside border is 6 pixels wide, the topside border starts at pixel position 6 (xy-positions are zero-based).

Given that later you'll draw also a rightside border that is 6 pixels wide, you only need to paint what's in between: 320-6-6

The above code can be optimized a lot, but for the moment you are struggling to get things working. So please don't try to process more than 1 pixel at a time. An important motto in programming says: "First make it work, then make it better".

Also do write comments like the ones I wrote. It'll help in understanding what you're doing.

The problem with testing the color

```<code>MoveLeft1:
    call Delay
    mov dx,[platLoc]
    add dx,8*320         ???
    sub dx,1d
    mov di,dx
    mov ax,[es:di]       ???
    cmp ax,0Fh           ???
</code>```

In the MoveLeft1 code you read from a mis-calculated address! By adding 8*320 to the dx register you land below the screen, so off-screen. Actually due to segment wraparound you will be wrongly addressing some random pixel in the top part of the VRAM.

```<code>  MoveLeft1:
      call Delay
      mov  di, [platLoc]
      mov  al, [es:di-1]    ; Pixel to the left of the platform
      cmp  al, 0Fh          ; Is it white?
      jne  move1
      jmp  CheckPress1
    move1:
      call PlatErase
      dec  [platLoc]
      call PlatBuild
      mov  ah, 01h
      int  16h              ; Key pending?
      je   MoveLeft1
      jmp  CheckPress1
</code>```

```<code>MoveRight1:
    call Delay
    mov dx,[platLoc]
    add dx,41          ???
    mov di,dx
    mov ax,[es:di]     ???
    cmp ax,0Fh         ???
</code>```

In the MoveRight1 code you also read from the wrong address. The platform is 40 pixels wide and so the last pixel will be at platLoc + 39, and thus the pixel that needs checking is at platLoc + 40.

```<code>MoveRight1:
    call Delay
    mov  di, [platLoc]
    mov  al, [es:di+40]     ; Pixel to the right of the platform
    cmp  al, 0Fh            ; Is it white?
    jne  move2
    jmp  CheckPress1
  move2:
    call PlatErase
    inc  [platLoc]
    call PlatBuild
    mov  ah, 01h
    int  16h                ; Key pending?
    je   MoveRight1
    jmp  CheckPress1
</code>```

Body:
I am programming a game similar to breakout in assembly (tools:DosBOX, notepad++, tasm), and whilst creating the borders and platform in Graphics mode, I've stumbled upon 2 problems:

It seems as if the extra segment won't register the color information, as I can't get it right and when I try to pull it gives me a 0 which is black, as opposed to white which is 0Fh.

It's a slight problem which I tried to resolve, but for some reason, when when I try to paint the second and third border, a part of the 1st border turns black, you'll see it if you run the code. I wasn't able to determine why it happens and the debugger didn't show anything odd.

This is my current code, the main procedures that are involved in the creating of the borders, platform and movement of the platform are BorderPaint, PlatBuild and PlatMove

    IDEAL
    MODEL small
    STACK 100h
    DATASEG
    platLoc dw 63806
    speed1 dw 10
    speed2 dw 0FFFFh
    CODESEG
    ;procedure to paint borders-6 px white pixels
    proc BorderPaint
        push ax
        push bx
        push di
        push cx

    mov ax,0A000h ;accesses graphics mode video memory
    mov es,ax
    xor di,di

    ;first line-left vertical
    ;sets color white

    mov ax,0Fh
    mov cx,200 ;enters nested loop
    FirstLoop1:
    push cx
    mov cx,6
    SecondLoop1:
    mov [es:di],ax
    inc di
    loop SecondLoop1
    sub di,6
    add di,320
    pop cx
    loop FirstLoop1
    ;second line- up horizontal
    mov di,7
    mov cx,313
    FirstLoop2:
    push cx
    mov cx,6
    SecondLoop2:
    mov [es:di],ax
    add di,320
    loop SecondLoop2
    sub di,1920
    inc di
    pop cx
    loop FirstLoop2

    mov di,314
    mov cx,200
    FirstLoop3:
    push cx
    mov cx,6
    SecondLoop3:
    mov [es:di],ax
    inc di
    loop SecondLoop3
    sub di,6
    add di,320
    pop cx
    loop FirstLoop3

    ; xor di,di
    ; mov ax,0Fh
    ; mov cx,200
    ; FirstLoop4:
    ; push cx
    ; mov cx,6
    ; SecondLoop4:
    ; mov [es:di],ax
    ; inc di
    ; loop SecondLoop4
    ; sub di,6
    ; add di,320
    ; pop cx
    ; loop FirstLoop4

        pop cx
        pop di
        pop bx
        pop ax
    ret
    endp BorderPaint

    proc PlatBuild
    push di
    push cx
    push ax
        mov di,[platLoc]
        mov ax,5
        mov cx,40
        LoopPaint2:
        push cx
        mov cx,10
        LoopPaint1:
        mov [es:di],ax
        sub di,320
        loop LoopPaint1
        add di,320*10
        inc di
        pop cx
        loop LoopPaint2
    pop ax
    pop cx
    pop di
    ret
    endp PlatBuild

    Proc PlatErase
    push di
    push cx
    push ax
        mov di,[platLoc]
        mov ax,0
        mov cx,40
        LoopPaint4:
        push cx
        mov cx,10
        LoopPaint3:
        mov [es:di],ax
        sub di,320
        loop LoopPaint3
        add di,320*10
        inc di
        pop cx
        loop LoopPaint4
    pop ax
    pop cx
    pop di
    ret
    endp PlatErase

    Proc PlatMove
    push ax
    push cx
    push dx
    push di
        mov ax,0A000h
        mov es,ax
        call BorderPaint
        ;Input
        CheckPress1:
        mov ah,0h
        int 16h

        cmp al,'a'
        jne nxt11
        jmp MoveLeft1
         Nxt11:
        cmp al,'d'
        jne nxt12
        jmp MoveRight1
        Nxt12:
        cmp al,'q'
        jne CheckPress1
        jmp endproc1

        MoveLeft1:
        call Delay
        mov dx,[platLoc]
        add dx,8*320
        sub dx,1d
        mov di,dx
        mov ax,[es:di]
        cmp ax,0Fh
        jne move1
        jmp CheckPress1
        move1:
        call PlatErase
        dec [platLoc]
        call PlatBuild
        mov ah,1h
        int 16h
        je MoveLeft1
        jmp CheckPress1

        MoveRight1:
        call Delay
        mov dx,[platLoc]
        add dx,41

        mov di,dx
        mov ax,[es:di]
        cmp ax,0Fh
        jne move2
        jmp CheckPress1
        move2:
        call PlatErase
        inc [platLoc]
        call PlatBuild
        mov ah,1h
        int 16h
        je MoveRight1
        jmp CheckPress1
        EndProc1:
    pop di
    pop dx
    pop cx
    pop ax
        ret
        endp PlatMove
        proc Delay
    push cx
        mov cx, [speed2]
    LoopLong:
    push cx
        mov cx, [speed1]
      LoopShort:
        loop LoopShort
    pop cx
        loop LoopLong
    pop cx
    ret
    Endp Delay
    start:
        mov ax,@data
        mov ds,ax
        mov ax,13h
        int 10h
        call BorderPaint
        call PlatBuild
        mov ax, [es:63680]
        call PlatMove

    exit:
        mov ax,4c00h
        int 21h
    END startenter code here

Body:
The problem with reading and writing

Since your program works with the 320x200 256-colors video mode 13h, every pixel is represented by a single byte in VRAM. The foremost problem in your code, and Ped7g already pointed this out, is that you consistently read and write words where you should be reading and writing bytes.

I'll show what we mean by writing the corrections for the topside border. Don't forget to make similar changes everywhere else!

;second line- up horizontal
    mov di,6          ; (6,0)   <--- See 1.
    mov cx,320-6-6    ; Width   <--- See 2.
FirstLoop2:
    push cx
    mov cx,6          ; Height
  SecondLoop2:
    mov [es:di],al    ; Color 0Fh, Byte from AL instead of word from AX
    add di,320        ; Go down 1 line
    loop SecondLoop2
    sub di,320*6      ; Take back 6 additions of 320
    inc di            ; Go right 1 pixel
    pop cx
    loop FirstLoop2

I chose this part because it also had some additional errors:

Given that the leftside border is 6 pixels wide, the topside border starts at pixel position 6 (xy-positions are zero-based).

Given that later you'll draw also a rightside border that is 6 pixels wide, you only need to paint what's in between: 320-6-6

The above code can be optimized a lot, but for the moment you are struggling to get things working. So please don't try to process more than 1 pixel at a time. An important motto in programming says: "First make it work, then make it better".

Also do write comments like the ones I wrote. It'll help in understanding what you're doing.

The problem with testing the color

MoveLeft1:
    call Delay
    mov dx,[platLoc]
    add dx,8*320         ???
    sub dx,1d
    mov di,dx
    mov ax,[es:di]       ???
    cmp ax,0Fh           ???

In the MoveLeft1 code you read from a mis-calculated address! By adding 8*320 to the dx register you land below the screen, so off-screen. Actually due to segment wraparound you will be wrongly addressing some random pixel in the top part of the VRAM.

  MoveLeft1:
      call Delay
      mov  di, [platLoc]
      mov  al, [es:di-1]    ; Pixel to the left of the platform
      cmp  al, 0Fh          ; Is it white?
      jne  move1
      jmp  CheckPress1
    move1:
      call PlatErase
      dec  [platLoc]
      call PlatBuild
      mov  ah, 01h
      int  16h              ; Key pending?
      je   MoveLeft1
      jmp  CheckPress1

MoveRight1:
    call Delay
    mov dx,[platLoc]
    add dx,41          ???
    mov di,dx
    mov ax,[es:di]     ???
    cmp ax,0Fh         ???

In the MoveRight1 code you also read from the wrong address. The platform is 40 pixels wide and so the last pixel will be at platLoc + 39, and thus the pixel that needs checking is at platLoc + 40.

MoveRight1:
    call Delay
    mov  di, [platLoc]
    mov  al, [es:di+40]     ; Pixel to the right of the platform
    cmp  al, 0Fh            ; Is it white?
    jne  move2
    jmp  CheckPress1
  move2:
    call PlatErase
    inc  [platLoc]
    call PlatBuild
    mov  ah, 01h
    int  16h                ; Key pending?
    je   MoveRight1
    jmp  CheckPress1


来源: stackexchange

问:
Flow complaining about incompatible type in object default values destructuring
I have this very simple function I'm trying to validate with Flow:

```<code>// @flow
type Props = {
  width: string | number,
};

function fun({
  width = '30em',
}: Props) {
  return width;
}
</code>```

The problem is that I get this error:

```<code>8:   width = '30em',
     ^ number. This type is incompatible with
8:   width = '30em',
     ^ string
8:   width = '30em',
     ^ string. This type is incompatible with
8:   width = '30em',
     ^ number
8:   width = '30em',
             ^ string. This type is incompatible with
8:   width = '30em',
     ^ number
</code>```

I wonder what I'm doing wrong... This other way works fine:

```<code>// @flow
type Props = {
  width: string | number,
};

function fun(props: Props) {
  const {
    width = '30em',
  } = props;
  return width;
}
</code>```

And this syntax inside function arguments seem supported because:

```<code>// @flow
type Props = {
  width: string,
};

function fun({ width = '30em' }: Props) {
  return width;
}
</code>```

This works just fine.

Ideas?

答:
Destructuring default assignment is not supported in Flow.

Rather than assigning defaults and destructuring at the same time, you should define defaultProps separately, then use those as your defaults.

For example:

```<code>type Props = {
    width: string | number
}

const defaultProps: Props = {
    width: '30em',
}

function fun ({ width }: Props = defaultProps) {
  return width
}

fun({ width: 30 })   // => 30
fun({ width: '30' }) // => '30'
fun()                // => '30em'

fun({ width: true }) // $ExpectError
</code>```

Here is a working example.

ContentLicense: CC BY-SA 3.0

Body:
I have this very simple function I'm trying to validate with Flow:

// @flow
type Props = {
  width: string | number,
};

function fun({
  width = '30em',
}: Props) {
  return width;
}

The problem is that I get this error:

8:   width = '30em',
     ^ number. This type is incompatible with
8:   width = '30em',
     ^ string
8:   width = '30em',
     ^ string. This type is incompatible with
8:   width = '30em',
     ^ number
8:   width = '30em',
             ^ string. This type is incompatible with
8:   width = '30em',
     ^ number

I wonder what I'm doing wrong... This other way works fine:

// @flow
type Props = {
  width: string | number,
};

function fun(props: Props) {
  const {
    width = '30em',
  } = props;
  return width;
}

And this syntax inside function arguments seem supported because:

// @flow
type Props = {
  width: string,
};

function fun({ width = '30em' }: Props) {
  return width;
}

This works just fine.

Ideas?

Body:
Destructuring default assignment is not supported in Flow.

Rather than assigning defaults and destructuring at the same time, you should define defaultProps separately, then use those as your defaults.

For example:

type Props = {
    width: string | number
}

const defaultProps: Props = {
    width: '30em',
}

function fun ({ width }: Props = defaultProps) {
  return width
}

fun({ width: 30 })   // => 30
fun({ width: '30' }) // => '30'
fun()                // => '30em'

fun({ width: true }) // $ExpectError

Here is a working example.


问:
How to split a number into its digits in APL
In APL, how can I split an integer or number into a vector containing its digits? What is the most concise (shortest) way of doing this?</p>

答:
I did this in APL2 by first applying FORMAT and then EXECUTE EACH (though it might be limited to positive integers) :

```<code>⍎¨⍕
</code>```

Try it online!

Body:
I did this in APL2 by first applying FORMAT and then EXECUTE EACH (though it might be limited to positive integers) :

⍎¨⍕

Try it online!


问:
Mocking a service thats provided in a component controller in a unit test
This is the error I'm seeing when trying to run my unit test ..

```<code>Expected undefined to be defined.
TypeError: undefined is not an object (evaluating '$rootScope.$digest')

Module 'ThirdPartyModule' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
</code>```

Any ideas how to mock the testService so that I can still compile my component?

test.component.spec.ts

```<code>import { TestModule } from '../index';

describe('Component: testComponent', () => {

  let $rootScope: angular.IScope;
  let element: angular.IAugmentedJQuery;

  beforeEach(() => {
    angular.mock.module('ui.router');
    angular.mock.module(TestModule.name);
  });

  beforeEach(inject((
    _$rootScope_: angular.IScope,
    $compile: angular.ICompileService,
    _$state_: angular.ui.IStateService) => {
    $rootScope = _$rootScope_;
    element = angular.element('<test></test>');
    element = $compile(element)($rootScope);
  }));

  it('should verify component compiled and rendered template', () => {
    expect(element).toBeDefined();
    $rootScope.$digest();
    let link = element.find('a');
    expect(link.text()).toContain('Click this link!');
  });
});
</code>```

test.module.ts

```<code>import { TestComponent } from './test';

export let TestModule: ng.IModule = angular.module(
  'test', // my module name
  ['ui.router', 'ThirdPartyModule']) // dependencies, ThirdPartyModule contains testService
  .component('test', new TestComponent());
</code>```

test.component.ts

```<code>import { TestComponentController } from './test.component.controller';

export class TestComponent implements ng.IComponentOptions {
  public template: string = '<a ng-if="ctrl.serviceReturned">Click this link!</a>';
  public controller: Function = TestComponentController;
  public controllerAs: string = 'ctrl';

  constructor() {}
}
</code>```

test.component.controller.ts

```<code>export class TestComponentController {

  public serviceReturned: boolean = false;

  constructor(private testService: any) {
    if (this.testService.isDone()) {
      this.serviceReturned = true;
    }
  }
}

TestComponentController.$inject = ['testService'];
</code>```

答: Don't you need to add 'ThirdPartyModule' in an angular.mock.module?</p>

Body:
This is the error I'm seeing when trying to run my unit test ..

Expected undefined to be defined.
TypeError: undefined is not an object (evaluating '$rootScope.$digest')

Module 'ThirdPartyModule' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

Any ideas how to mock the testService so that I can still compile my component?

test.component.spec.ts

import { TestModule } from '../index';

describe('Component: testComponent', () => {

  let $rootScope: angular.IScope;
  let element: angular.IAugmentedJQuery;

  beforeEach(() => {
    angular.mock.module('ui.router');
    angular.mock.module(TestModule.name);
  });

  beforeEach(inject((
    _$rootScope_: angular.IScope,
    $compile: angular.ICompileService,
    _$state_: angular.ui.IStateService) => {
    $rootScope = _$rootScope_;
    element = angular.element('<test></test>');
    element = $compile(element)($rootScope);
  }));

  it('should verify component compiled and rendered template', () => {
    expect(element).toBeDefined();
    $rootScope.$digest();
    let link = element.find('a');
    expect(link.text()).toContain('Click this link!');
  });
});

test.module.ts

import { TestComponent } from './test';

export let TestModule: ng.IModule = angular.module(
  'test', // my module name
  ['ui.router', 'ThirdPartyModule']) // dependencies, ThirdPartyModule contains testService
  .component('test', new TestComponent());

test.component.ts

import { TestComponentController } from './test.component.controller';

export class TestComponent implements ng.IComponentOptions {
  public template: string = 'Click this link!';
  public controller: Function = TestComponentController;
  public controllerAs: string = 'ctrl';

  constructor() {}
}

test.component.controller.ts

export class TestComponentController {

  public serviceReturned: boolean = false;

  constructor(private testService: any) {
    if (this.testService.isDone()) {
      this.serviceReturned = true;
    }
  }
}

TestComponentController.$inject = ['testService'];


问:
Optimizing a python Code
I'm trying to optimize this code (Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square). I'm new to coding and I'm having a hard time with this concept

```<code>  def list_squared(m, n):
    # your code
     import math
     MyList = []
     for i in range(m,n):
         A=[]
         for k in range(1,i+1):
             if i%k == 0:
                A.append(k**2)
         if round(math.sqrt(sum(A))) == math.sqrt(sum(A)):
                  B =[]
                  B.append(i)
                  B.append(sum(A))
                 MyList.append(B)
      return MyList
</code>```

答:
```<code>import math
def list_squared(m, n):
     MyList = []
     for i in range(m,n):
         res=0
         for k in range(1,i+1):
             if i%k == 0:
                res+=k**2
         if res == int(math.sqrt(res))**2
                 MyList.append(i)
      return MyList
</code>```

Title: Optimizing a python Code

Body:
I'm trying to optimize this code (Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square). I'm new to coding and I'm having a hard time with this concept

  def list_squared(m, n):
    # your code
     import math
     MyList = []
     for i in range(m,n):
         A=[]
         for k in range(1,i+1):
             if i%k == 0:
                A.append(k**2)
         if round(math.sqrt(sum(A))) == math.sqrt(sum(A)):
                  B =[]
                  B.append(i)
                  B.append(sum(A))
                 MyList.append(B)
      return MyList


问:
Parse server creating a "createdAt" query for a specific day
Hi (I'm new to this so you'll have to forgive me)

I'm trying to construct a Parse query to return all of the objects that were created on a specific day (the time they were created is irrelevant).

I've included the code I have so far below. I passed the date for the objects I'm trying to retrieve into the method. Then I've set two variables, one for the very start of the day and one for the very end of the day. I then used the whereGreaterThanOrEqualTo and whereLessThanmethods to set the end and start date.

The issue i'm having is that it's not returning any objects even though there are several that exist in that class. I have a feeling that it's because Parse Server uses a different date format to the standard java package so I'm not really sure what i should do. Could someone point me in the right direction?

```<code>public void updateNotices(Date date){
    if(isNetworkConnected()) {
        date.setTime(0);
        Date endDate = date;
        endDate.setDate(date.getDate()+1);
        ParseQuery<ParseObject> query = ParseQuery.getQuery("Notification");
        query.whereGreaterThanOrEqualTo("createdAt", date);
        query.whereLessThan("createdAt", endDate);
        startLoading();
        query.findInBackground(new FindCallback<ParseObject>() { ...
</code>```

答:
It would appear you are incorrectly using setTime(). See here: https://www.tutorialspoint.com/java/util/date_settime.htm

This answer appears to show how you'd want to properly create that date:
how to create a Java Date object of midnight today and midnight tomorrow?

If fixing that doesn't work, ensure you don't have any ACL/CLP settings that may restrict access to your objects.

If you don't have any ACL/CLP settings, consider setting them. Much easier to do sooner, rather than later.

Body:
Hi (I'm new to this so you'll have to forgive me)

I'm trying to construct a Parse query to return all of the objects that were created on a specific day (the time they were created is irrelevant).

I've included the code I have so far below. I passed the date for the objects I'm trying to retrieve into the method. Then I've set two variables, one for the very start of the day and one for the very end of the day. I then used the whereGreaterThanOrEqualTo and whereLessThanmethods to set the end and start date.

The issue i'm having is that it's not returning any objects even though there are several that exist in that class. I have a feeling that it's because Parse Server uses a different date format to the standard java package so I'm not really sure what i should do. Could someone point me in the right direction?

public void updateNotices(Date date){
    if(isNetworkConnected()) {
        date.setTime(0);
        Date endDate = date;
        endDate.setDate(date.getDate()+1);
        ParseQuery<ParseObject> query = ParseQuery.getQuery("Notification");
        query.whereGreaterThanOrEqualTo("createdAt", date);
        query.whereLessThan("createdAt", endDate);
        startLoading();
        query.findInBackground(new FindCallback<ParseObject>() { ...


问:
Do some dynamic time calculating events on several tags, jQuery or javascript
I have several p tags that have same class but different title values.

And depending on each title, I want to do some time calculating event.

Here are my p tag examples.

```<code><p class="timePTag" id="pId1" title="2017-07-09T17:50:58.528Z">Calculated timedelta 1</p>

<p class="timePTag" id="pId2" title="2017-07-10T17:50:58.528Z">Calculated timedelta 2</p>

<p class="timePTag" id="pId3" title="2017-07-12T17:50:58.528Z">Calculated timedelta 3</p>
</code>```

In that, pId can be grow, like pId4, pId5 ... and each title attribute has different value.

What i want to calculate is timedelta_ time difference between title value and now time, which can be from var now = new Date;

I tried this,

```<code>setInterval(function() {
        var now = new Date;
        var title = $(".timePTag").attr("title");
        var sourcedate = new Date(title);
        var timestamp = Math.floor((now - sourcedate) /1000) + "Days";
        console.log(timestamp);
        $(".timePTag").text(timestamp);
}, 1000);
</code>```

But it returned same things in all p tags.
I need dynamic timedelta result.

How can i do this?

My expecting result is like,

```<code><p class="timePTag" id="pId1" title="2017-07-09T17:50:58.528Z">12days ago</p>

<p class="timePTag" id="pId2" title="2017-07-10T17:50:58.528Z">11days ago</p>

<p class="timePTag" id="pId3" title="2017-07-12T17:50:58.528Z">9days ago</p>
</code>```

答:
You need to iterate over the results in jquery, Otherwise you work on all elements at once.  Use the each function:
https://api.jquery.com/each/

setInterval(function() {
  var now = new Date;
  $(".timePTag").each(function() {
    var title = $(this).attr("title");
        var sourcedate = new Date(title);
        var timestamp = Math.floor((now - sourcedate) /1000 / 60 / 60 / 24) + " Days";
        $(this).text(timestamp);
  });
}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="timePTag" id="pId1" title="2017-07-09T17:50:58.528Z">Calculated timedelta 1</p>

<p class="timePTag" id="pId2" title="2017-07-10T17:50:58.528Z">Calculated timedelta 2</p>

<p class="timePTag" id="pId3" title="2017-07-12T17:50:58.528Z">Calculated timedelta 3</p></code>```

Body:
I have several p tags that have same class but different title values.

And depending on each title, I want to do some time calculating event.

Here are my p tag examples.

Calculated timedelta 1

Calculated timedelta 2

Calculated timedelta 3

In that, pId can be grow, like pId4, pId5 ... and each title attribute has different value.

What i want to calculate is timedelta_ time difference between title value and now time, which can be from var now = new Date;

I tried this,

setInterval(function() {
        var now = new Date;
        var title = $(".timePTag").attr("title");
        var sourcedate = new Date(title);
        var timestamp = Math.floor((now - sourcedate) /1000) + "Days";
        console.log(timestamp);
        $(".timePTag").text(timestamp);
}, 1000);

But it returned same things in all p tags.
I need dynamic timedelta result.

How can i do this?

My expecting result is like,

12days ago

11days ago

9days ago

Body:
You need to iterate over the results in jquery, Otherwise you work on all elements at once.  Use the each function:
https://api.jquery.com/each/

setInterval(function() {
  var now = new Date;
  $(".timePTag").each(function() {
    var title = $(this).attr("title");
        var sourcedate = new Date(title);
        var timestamp = Math.floor((now - sourcedate) /1000 / 60 / 60 / 24) + " Days";
        $(this).text(timestamp);
  });
}, 1000);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="timePTag" id="pId1" title="2017-07-09T17:50:58.528Z">Calculated timedelta 1</p>

<p class="timePTag" id="pId2" title="2017-07-10T17:50:58.528Z">Calculated timedelta 2</p>

<p class="timePTag" id="pId3" title="2017-07-12T17:50:58.528Z">Calculated timedelta 3</p>


问:
Volley-AuthFailureError
I am trying to insert new user in phpMyAdmin database when users populate textboxes on android device. For that i write php code and I test it on POSTMAN and it's works but when i test on android real device i got AuthFailureError! In POSTMAN i set Authorization to "No Auth".
This is my code in android studio:

```<code>public class Registration extends AppCompatActivity {
private EditText name,surname,email,password,adress;
    private  Button btnLog;
    private RequestQueue requestQueue;
    private  static  final String URL="http://192.168.*.*/Log/LogUser.php";
    private StringRequest request;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registruj_se);
        name=(EditText) findViewById(R.id.txtName);
        surname=(EditText)findViewById(R.id.txtSurname);
        email=(EditText)findViewById(R.id.txtEmail);
        password=(EditText)findViewById(R.id.txtPassword);
        adress=(EditText)findViewById(R.id.txtAdress);
       btnLog=(Button)findViewById(R.id.btnLog);
        requestQueue= Volley.newRequestQueue(this);
        btnLog.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                request=new StringRequest(Request.Method.POST,URL,new Response.Listener<String>(){
                    @Override
                    public void onResponse(String response) {
                        try
                        {
                            JSONObject jsonObject=new JSONObject(response);
                        if(jsonObject.names().get(0).equals("success")){
                            Toast.makeText(getApplicationContext(),"success:"+jsonObject.getString("success"),Toast.LENGTH_SHORT).show();

                            startActivity(new Intent(getApplicationContext(),Welcome.class));
                        }else{  Toast.makeText(getApplicationContext(),"error:"+jsonObject.getString("error"),Toast.LENGTH_SHORT).show();}

                        }

                        catch (JSONException e){e.printStackTrace();}
                    }
                },new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        if (error instanceof NetworkError) {
                            Toast.makeText(getApplicationContext(),"Cannot connect to Internet...Please check your connection!",Toast.LENGTH_SHORT).show();
                        } else if (error instanceof ServerError) {
                            Toast.makeText(getApplicationContext(),"The server could not be found. Please try again after some time!!",Toast.LENGTH_SHORT).show();

                        } else if (error instanceof AuthFailureError) {
                            Toast.makeText(getApplicationContext(),"AuthFailureError",Toast.LENGTH_SHORT).show();
                        } else if (error instanceof ParseError) {
                            Toast.makeText(getApplicationContext(),"Parsing error! Please try again after some time!!",Toast.LENGTH_SHORT).show();

                        } else if (error instanceof NoConnectionError) {
                            Toast.makeText(getApplicationContext(),"NoConnectionError",Toast.LENGTH_SHORT).show();
                        } else if (error instanceof TimeoutError) {
                            Toast.makeText(getApplicationContext(),"Connection TimeOut! Please check your internet connection.",Toast.LENGTH_SHORT).show();

                        }
                    }
                })
                {

                   @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        HashMap<String,String>hashMap=new HashMap<String, String>();
                        hashMap.put("name",name.getText().toString());
                        hashMap.put("surname",surname.getText().toString());
                        hashMap.put("email",email.getText().toString());
                        hashMap.put("password",password.getText().toString());
                        hashMap.put("adress",adress.getText().toString());
                        return  hashMap;
                    }

                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        HashMap<String, String> headers = new HashMap<String, String>();
                        // do not add anything here
                        return headers;
                    }
                    @Override
                    public String getBodyContentType() {
                        return "application/json";
                    }

                };
                requestQueue.add(request);
            }
        });
</code>```

I appreciate any help!

答:
Try this:

In getBodyContentType() method return "application/x-www-form-urlencoded" instead of "application/json"

Code

```<code>@Override
public String getBodyContentType() {
       return "application/x-www-form-urlencoded";
}
</code>```

Title: Volley-AuthFailureError

Body:
I am trying to insert new user in phpMyAdmin database when users populate textboxes on android device. For that i write php code and I test it on POSTMAN and it's works but when i test on android real device i got AuthFailureError! In POSTMAN i set Authorization to "No Auth".
This is my code in android studio:

public class Registration extends AppCompatActivity {
private EditText name,surname,email,password,adress;
    private  Button btnLog;
    private RequestQueue requestQueue;
    private  static  final String URL="http://192.168.*.*/Log/LogUser.php";
    private StringRequest request;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registruj_se);
        name=(EditText) findViewById(R.id.txtName);
        surname=(EditText)findViewById(R.id.txtSurname);
        email=(EditText)findViewById(R.id.txtEmail);
        password=(EditText)findViewById(R.id.txtPassword);
        adress=(EditText)findViewById(R.id.txtAdress);
       btnLog=(Button)findViewById(R.id.btnLog);
        requestQueue= Volley.newRequestQueue(this);
        btnLog.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                request=new StringRequest(Request.Method.POST,URL,new Response.Listener<String>(){
                    @Override
                    public void onResponse(String response) {
                        try
                        {
                            JSONObject jsonObject=new JSONObject(response);
                        if(jsonObject.names().get(0).equals("success")){
                            Toast.makeText(getApplicationContext(),"success:"+jsonObject.getString("success"),Toast.LENGTH_SHORT).show();

                            startActivity(new Intent(getApplicationContext(),Welcome.class));
                        }else{  Toast.makeText(getApplicationContext(),"error:"+jsonObject.getString("error"),Toast.LENGTH_SHORT).show();}

                        }

                        catch (JSONException e){e.printStackTrace();}
                    }
                },new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        if (error instanceof NetworkError) {
                            Toast.makeText(getApplicationContext(),"Cannot connect to Internet...Please check your connection!",Toast.LENGTH_SHORT).show();
                        } else if (error instanceof ServerError) {
                            Toast.makeText(getApplicationContext(),"The server could not be found. Please try again after some time!!",Toast.LENGTH_SHORT).show();

                        } else if (error instanceof AuthFailureError) {
                            Toast.makeText(getApplicationContext(),"AuthFailureError",Toast.LENGTH_SHORT).show();
                        } else if (error instanceof ParseError) {
                            Toast.makeText(getApplicationContext(),"Parsing error! Please try again after some time!!",Toast.LENGTH_SHORT).show();

                        } else if (error instanceof NoConnectionError) {
                            Toast.makeText(getApplicationContext(),"NoConnectionError",Toast.LENGTH_SHORT).show();
                        } else if (error instanceof TimeoutError) {
                            Toast.makeText(getApplicationContext(),"Connection TimeOut! Please check your internet connection.",Toast.LENGTH_SHORT).show();

                        }
                    }
                })
                {

                   @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        HashMap<String,String>hashMap=new HashMap<String, String>();
                        hashMap.put("name",name.getText().toString());
                        hashMap.put("surname",surname.getText().toString());
                        hashMap.put("email",email.getText().toString());
                        hashMap.put("password",password.getText().toString());
                        hashMap.put("adress",adress.getText().toString());
                        return  hashMap;
                    }

                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        HashMap<String, String> headers = new HashMap<String, String>();
                        // do not add anything here
                        return headers;
                    }
                    @Override
                    public String getBodyContentType() {
                        return "application/json";
                    }

                };
                requestQueue.add(request);
            }
        });

I appreciate any help!

Body:
Try this:

In getBodyContentType() method return "application/x-www-form-urlencoded" instead of "application/json"

Code

@Override
public String getBodyContentType() {
       return "application/x-www-form-urlencoded";
}


问:
Problems while compiling XDR on macOS (RPC types.h issue)
I am trying to compile some source codes about UNIX scokets programs, on Linux I have no problems but on macOS I get stuck in front of types definition problems. I don't know how many details I can put here, but I'll try.

The source codes to be compiled are:

```<code>errlib.c
errlib.h
server_test.c
sockwrap.c
sockwrap.h
</code>```

where the main is located in server_test.c.

To compile I use:

```<code>gcc -Wall -DTRACE -o server_test server_test.c errlib.c sockwrap.c
</code>```

There are no problems running this on Linux, but on macOS I get more than 20 error and all of these are about a (perhaphs) missing definition of bool_t. I suppose something not working in /usr/include/rpc/* files located in macOS internal libraries.

So I looked for if <sys/types.h> is included in /usr/include/rpc/xdr.h and it seems to be not missing.

Some of the first lines of the gcc output are:

```<code>In file included from server_test.c:16:
/usr/include/rpc/xdr.h:126:3: error: type name requires a specifier or qualifier
                bool_t  (*x_getlong)(struct __rpc_xdr *, int *);
                ^
/usr/include/rpc/xdr.h:126:10: error: function cannot return function type 'int (struct __rpc_xdr *, int *)'
                bool_t  (*x_getlong)(struct __rpc_xdr *, int *);
                        ^
/usr/include/rpc/xdr.h:128:3: error: type name requires a specifier or qualifier
                bool_t  (*x_putlong)(struct __rpc_xdr *, const int *);
                ^
/usr/include/rpc/xdr.h:128:10: error: function cannot return function type 'int (struct __rpc_xdr *, const int *)'
                bool_t  (*x_putlong)(struct __rpc_xdr *, const int *);
                        ^

/usr/include/rpc/xdr.h:128:3: error: duplicate member 'bool_t'
                bool_t  (*x_putlong)(struct __rpc_xdr *, const int *);
                ^
/usr/include/rpc/xdr.h:126:3: note: previous declaration is here
                bool_t  (*x_getlong)(struct __rpc_xdr *, int *);
                ^
/usr/include/rpc/xdr.h:136:3: error: type name requires a specifier or qualifier
                bool_t  (*x_getbytes)(struct __rpc_xdr *, char *, unsigned int);
...
</code>```

and many others lines that are very similar.

For those who want to deepen, the sources are available here.

What could be the problem?

答:
The bad answer

Issue solved by simply including <rpc/types.h> in the server_test.c source as follows:

```<code>#include <rpc/types.h>
</code>```

The better one

This is a solution above is valid only for this server_test.c implementation.

If you want fix this issue "globally", you can follow follown steps:

disable SIP (how to? here)

get your macOS's xdr.h (from here /usr/include/rpc/xdr.h)

copy it elsewhere two times: one copy is for backup and modify the other one simply adding the required include (#include <rpc/types.h> and see the picture below)

overwrite your modified xdr.h onto the original one in /usr/include/rpc/

re-enable SIP

Here is how I did it:

Body:
I am trying to compile some source codes about UNIX scokets programs, on Linux I have no problems but on macOS I get stuck in front of types definition problems. I don't know how many details I can put here, but I'll try.

The source codes to be compiled are:

errlib.c
errlib.h
server_test.c
sockwrap.c
sockwrap.h

where the main is located in server_test.c.

To compile I use:

gcc -Wall -DTRACE -o server_test server_test.c errlib.c sockwrap.c

There are no problems running this on Linux, but on macOS I get more than 20 error and all of these are about a (perhaphs) missing definition of bool_t. I suppose something not working in /usr/include/rpc/* files located in macOS internal libraries.

So I looked for if <sys/types.h> is included in /usr/include/rpc/xdr.h and it seems to be not missing.

Some of the first lines of the gcc output are:

In file included from server_test.c:16:
/usr/include/rpc/xdr.h:126:3: error: type name requires a specifier or qualifier
                bool_t  (*x_getlong)(struct __rpc_xdr *, int *);
                ^
/usr/include/rpc/xdr.h:126:10: error: function cannot return function type 'int (struct __rpc_xdr *, int *)'
                bool_t  (*x_getlong)(struct __rpc_xdr *, int *);
                        ^
/usr/include/rpc/xdr.h:128:3: error: type name requires a specifier or qualifier
                bool_t  (*x_putlong)(struct __rpc_xdr *, const int *);
                ^
/usr/include/rpc/xdr.h:128:10: error: function cannot return function type 'int (struct __rpc_xdr *, const int *)'
                bool_t  (*x_putlong)(struct __rpc_xdr *, const int *);
                        ^

/usr/include/rpc/xdr.h:128:3: error: duplicate member 'bool_t'
                bool_t  (*x_putlong)(struct __rpc_xdr *, const int *);
                ^
/usr/include/rpc/xdr.h:126:3: note: previous declaration is here
                bool_t  (*x_getlong)(struct __rpc_xdr *, int *);
                ^
/usr/include/rpc/xdr.h:136:3: error: type name requires a specifier or qualifier
                bool_t  (*x_getbytes)(struct __rpc_xdr *, char *, unsigned int);
...

and many others lines that are very similar.

For those who want to deepen, the sources are available here.

What could be the problem?

Body:
The bad answer

Issue solved by simply including <rpc/types.h> in the server_test.c source as follows:

#include <rpc/types.h>

The better one

This is a solution above is valid only for this server_test.c implementation.

If you want fix this issue "globally", you can follow follown steps:

disable SIP (how to? here)

get your macOS's xdr.h (from here /usr/include/rpc/xdr.h)

copy it elsewhere two times: one copy is for backup and modify the other one simply adding the required include (#include <rpc/types.h> and see the picture below)

overwrite your modified xdr.h onto the original one in /usr/include/rpc/

re-enable SIP

Here is how I did it:


问:
Android - Send data to the server in every 5 minutes
I have some data in my SQLite database table. When my app starts, I want to send that data to the server every 5 minutes.

When the app is closed, it should stop.

What is the best approach for this?

Should I use Service or IntentService?

Should I use AlarmManager, Handler or any other thing?

I'm aware of my application speed. I don't want to make it slow. What is the effective approach?

答:
If you are only transmitting when the app is in foreground, you can do it with a Handler.

You start the handler in onResume() and cancel it in onPause().
And perform the transmision with an AsyncTask or in a separate thread.

If you need to stransmit in background, you can use a service instead and schedule it with the AlarmManager.

And then start the service from the app's Activity.

I am not sure how IntentService would be used for this.


问:
C# control browser
Please suggest how can write c# to control browser to go to url and auto fill in specific element</p>

答:
Why don't you use WebBrowser Control in C#? Drag the Control from the Toolbar to your Form. Then do webBrowser1.Navigate("http://www.example.com/bla");

fill in the element you want like this: webBrowser1.Document.getElementById("yourID").innerHTML = "some content";

hope this helps,

Alex

ContentLicense: CC BY-SA 2.5

Title: C# control browser


问:
Identity Server 4 and UWP on Localhost
I'm hoping for some help getting the Identity Server 4 Demo (https://github.com/IdentityServer/IdentityServer4.Demo) and the OidcClient Samples UWP Client (https://github.com/IdentityModel/IdentityModel.OidcClient.Samples) working on localhost.

I've downloaded both and they both run. I can access localhost:5000 from a web browser and it loads up identity server's home page. In the uwp sample when I click Login it returns an "Unknown error". If I point the uwp sample to demo.identityserver.io it works so the sample works just not on localhost.

The identity server logs show some activity, no errors, but a breakpoints on the login method never gets hit. I thought it might be local loopback but on windows 10 with visual studio 2017 local loopback is no longer an issue as far as I'm aware. Has anyone been able to get these two samples to work together?

Thanks

答:
You can do it locally by disabling Loopback,
as I'm doing it right now!
See here for more information </p>

Title: Identity Server 4 and UWP on Localhost


问:
Scraping page with javascript filled table
I'm trying to scrape this page to get generation data to pass to a parser later on.

My problem is that the table is populated by multiple scripts that make requests to another server. Beautiful Soup scrapes the page but returns the javascript unexecuted.  So I'm trying to use selenium to open the page in a browser then scrape the populated table.

When I run my code Firefox loads the page then closes, but BS still returns the page without the table being populated.  I've tried inspecting the page using web console once fully loaded and I can see the data I need i.e. one data point is contained in a div tag with class = "r11".  A search for this tag returns None.

My thoughts are that either a) I'm using selenium wrong or b) the page's formatting is throwing things off since it looks to be quite deeply nested with serveral "sub documents" (not sure of correct term).

```<code>from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup

arg_therm = ('http://portalweb.cammesa.com/MEMNet1/Pages/Informes%20por%20'
        'Categor%C3%ADa/Operativos/VisorReporteSinComDesp_minimal.asp'
        'x?hora=0&titulo=Despacho%20Generacion%20Termica&reportPath='
        'http://lauzet:5000/MemNet1/ReportingServices/Despacho'
        'GeneracionTermica.rdl--0--Despacho+Generaci%c3%b3n+T%c3%a9rmica')

browser = webdriver.Firefox()
browser.get(arg_therm)
html_source = browser.page_source

browser.quit()

soup=BeautifulSoup(html_source,'lxml')

print(soup.prettify())

print(soup.find('div', {"class": "r11"}))
</code>```

答:
Try to use below code to get required table:

```<code>from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

browser = webdriver.Firefox()
browser.get(arg_therm)

browser.switch_to.frame(browser.find_element_by_xpath('//iframe[starts-with(@name, "RportFramectl00")]'))
browser.switch_to.frame('report')

table_cells = wait(browser, 10).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "r11")))
for cell in table_cells:
    print(cell.text)
</code>```

this should wait for appearance of required elements and return you list of those DIVs

Body:
I'm trying to scrape this page to get generation data to pass to a parser later on.

My problem is that the table is populated by multiple scripts that make requests to another server. Beautiful Soup scrapes the page but returns the javascript unexecuted.  So I'm trying to use selenium to open the page in a browser then scrape the populated table.

When I run my code Firefox loads the page then closes, but BS still returns the page without the table being populated.  I've tried inspecting the page using web console once fully loaded and I can see the data I need i.e. one data point is contained in a div tag with class = "r11".  A search for this tag returns None.

My thoughts are that either a) I'm using selenium wrong or b) the page's formatting is throwing things off since it looks to be quite deeply nested with serveral "sub documents" (not sure of correct term).

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup

arg_therm = ('http://portalweb.cammesa.com/MEMNet1/Pages/Informes%20por%20'
        'Categor%C3%ADa/Operativos/VisorReporteSinComDesp_minimal.asp'
        'x?hora=0&titulo=Despacho%20Generacion%20Termica&reportPath='
        'http://lauzet:5000/MemNet1/ReportingServices/Despacho'
        'GeneracionTermica.rdl--0--Despacho+Generaci%c3%b3n+T%c3%a9rmica')

browser = webdriver.Firefox()
browser.get(arg_therm)
html_source = browser.page_source

browser.quit()

soup=BeautifulSoup(html_source,'lxml')

print(soup.prettify())

print(soup.find('div', {"class": "r11"}))

Body:
Try to use below code to get required table:

from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

browser = webdriver.Firefox()
browser.get(arg_therm)

browser.switch_to.frame(browser.find_element_by_xpath('//iframe[starts-with(@name, "RportFramectl00")]'))
browser.switch_to.frame('report')

table_cells = wait(browser, 10).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "r11")))
for cell in table_cells:
    print(cell.text)

this should wait for appearance of required elements and return you list of those DIVs


问:
Getting error 'There was an error sending this message to your bot: HTTP status code GatewayTimeout ' email channel in MS bot
I have published a bot in bot framework and it is working in test window of the bot framework. Then I configured the bot with email channel with office 365 mail. I am getting the error:

There was an error sending this message to your bot: HTTP status code GatewayTimeout

答: You probably have this message because you did not use your endpoint for some time. One possibility to try to avoid those timeout is to set your published bot to Always On on Azure


问:
adding a passed in number to a MySQL cell with PHP
I am trying to add a number to a number already in a MySQL table. I am using POST to pass in the number.

```<code>    <?php
    require "connection.php";

    $id = $_POST["id"];
    $number = $_POST["number"];
</code>```

Do I have to make 2 separate queries, one to retrieve the current value and set is as a variable and one to insert the new value by adding the number to the variable or can I accomplish this with one query with something like this:

```<code>    $update_query = "update Table set value = (value + $number) where id like '$id';"
</code>```

答:
Yes, you can use one query UPDATE tbl_name SET value_col = value_col + :number WHERE id = :id

Notes

ID is unique, so you need id = :id to achieve faster queries and only update one field.

Use prepared statements instead of putting values directly to query

Body:
I am trying to add a number to a number already in a MySQL table. I am using POST to pass in the number.

    <?php
    require "connection.php";

    $id = $_POST["id"];
    $number = $_POST["number"];

Do I have to make 2 separate queries, one to retrieve the current value and set is as a variable and one to insert the new value by adding the number to the variable or can I accomplish this with one query with something like this:

    $update_query = "update Table set value = (value + $number) where id like '$id';"


问:
Visual studio 2015 installer projects
I'm try to do some validation inside OnBeforeInstall method & if the validation pass will continue through the installation process, if the validation failed i want to rollback and uninstall the setup.

i tried something like this, even though this is successfull, this gave me some exceptions while rollback.

```<code>if(validation){
}
else{
    base.RollBack(savedState);
}
</code>```

Exception - savedState does not contain required values or corrupted.

Please help me to do this without any exceptions.

答:
That's not really how to cause a Visual Studio-generated MSI to roll back. You throw an InstallException, and that results in a rollback. </p>

<p>OnBeforeInstall isn't actually "before" the install. All Visual Studio install custom actions are called after all the files are already installed (despite the name), so the rollback actually uninstalls everything. If you are validating input (or some pre-install conditions) it's rather unfriendly. </p>

Title: Visual studio 2015 installer projects

Body:
I'm try to do some validation inside OnBeforeInstall method & if the validation pass will continue through the installation process, if the validation failed i want to rollback and uninstall the setup.

i tried something like this, even though this is successfull, this gave me some exceptions while rollback.

if(validation){
}
else{
    base.RollBack(savedState);
}

Exception - savedState does not contain required values or corrupted.

Please help me to do this without any exceptions.

Body:
That's not really how to cause a Visual Studio-generated MSI to roll back. You throw an InstallException, and that results in a rollback.

OnBeforeInstall isn't actually "before" the install. All Visual Studio install custom actions are called after all the files are already installed (despite the name), so the rollback actually uninstalls everything. If you are validating input (or some pre-install conditions) it's rather unfriendly.


问:
How does ::selection's specificity work against type selectors?
Some questions about using CSS to specify the color of selected text:

Imagine that a rule like the following exists in the default CSS that's implemented by the browser:

```<code>::selection { background-color: Highlight; color: HighlightText; }
</code>```

Further imagine that a rule like the following is defined in any site-specific authored stylesheet:

```<code>body { background-color: white }
</code>```

Given these rules, what would the background-color of the selected body text be? Would it be white, or Highlight?

Perhaps the rule in the author stylesheet should override the default rule: because according to specificity, body is just as specific as ::selection and is specified later (and should therefore override the previous entry).

On the other hand, that would result in text being invisible when it's selected (because if Highlight is blue and HighlightText is white so that selected text is white-on-blue, then overriding the background-color of selected text so that it's white would result in its being white-on-white).

Assuming that the behaviour in step 2 is undesirable, how to avoid it?

Say that it's a bug in the user stylesheet, which shouldn't ever specify background-color without also specifying color?

Say that body isn't a match for selected body text except when the ::selection pseudo-element is specified as part of the selector?

答:
The following style:

```<code>body { background-color: white }
</code>```

applies to background color of your page.

On the other hand, this rule:

```<code>::selection { background-color: Highlight; color: HighlightText; }
</code>```

applies styles when you select text on your page.

So they do completely different things and there is no question of collision between them.

ContentLicense: CC BY-SA 4.0

Body:
Some questions about using CSS to specify the color of selected text:

Imagine that a rule like the following exists in the default CSS that's implemented by the browser:

::selection { background-color: Highlight; color: HighlightText; }

Further imagine that a rule like the following is defined in any site-specific authored stylesheet:

body { background-color: white }

Given these rules, what would the background-color of the selected body text be? Would it be white, or Highlight?

Perhaps the rule in the author stylesheet should override the default rule: because according to specificity, body is just as specific as ::selection and is specified later (and should therefore override the previous entry).

On the other hand, that would result in text being invisible when it's selected (because if Highlight is blue and HighlightText is white so that selected text is white-on-blue, then overriding the background-color of selected text so that it's white would result in its being white-on-white).

Assuming that the behaviour in step 2 is undesirable, how to avoid it?

Say that it's a bug in the user stylesheet, which shouldn't ever specify background-color without also specifying color?

Say that body isn't a match for selected body text except when the ::selection pseudo-element is specified as part of the selector?

Body:
The following style:

body { background-color: white }

applies to background color of your page.

On the other hand, this rule:

::selection { background-color: Highlight; color: HighlightText; }

applies styles when you select text on your page.

So they do completely different things and there is no question of collision between them.


问:
Selecting points in dataset that belong to a multivariate Gaussian distribution
I have a set of values D:

```<code> [[  6.83822474   3.54843586]
 [ 12.45778114   4.42755159]
 [ 10.27710359   9.47337879]
 ...,
 [ 46.55259568  64.73755611]
 [ 51.50842754  44.60132979]
</code>```

Given a Multivariate Gaussian distribution with mean M and covariance V:

What is the equivalent multivariate case of a univariate point being within 2 standard deviations of the mean? i.e. assuming I have a univariate distribution with mean A and std B, I can say a point x_i is within 2 standard deviations of the mean if x_i - A < B. What would be the equivalent of this in the multivariate case?

How would I compute all the points in D that are within 2 std's (or the equivalent in the multivariate case) from the mean M?

答:
The correct way to define distance for the multivariate case is the Mahalanobis distance, i.e.

An example of doing this would be:

```<code>import numpy as np

vals = np.array([[  6.83822474,   3.54843586],
                 [ 12.45778114,   4.42755159],
                 [ 10.27710359,   9.47337879],
                 [ 46.55259568,  64.73755611],
                 [ 51.50842754,  44.60132979]])

# Compute covariance matrix and its inverse
cov = np.cov(vals.T)
cov_inverse = np.linalg.inv(cov)

# Mean center the values
mean = np.mean(vals, axis=0)
centered_vals = vals - mean

# Compute Mahalanobis distance
dist = np.sqrt(np.sum(centered_vals * cov_inverse.dot(centered_vals.T).T, axis=1))

# Find points that are "far away" from the mean
indices = dist > 2
</code>```

Body:
I have a set of values D:

 [[  6.83822474   3.54843586]
 [ 12.45778114   4.42755159]
 [ 10.27710359   9.47337879]
 ...,
 [ 46.55259568  64.73755611]
 [ 51.50842754  44.60132979]

Given a Multivariate Gaussian distribution with mean M and covariance V:

What is the equivalent multivariate case of a univariate point being within 2 standard deviations of the mean? i.e. assuming I have a univariate distribution with mean A and std B, I can say a point x_i is within 2 standard deviations of the mean if x_i - A < B. What would be the equivalent of this in the multivariate case?

How would I compute all the points in D that are within 2 std's (or the equivalent in the multivariate case) from the mean M?

Body:
The correct way to define distance for the multivariate case is the Mahalanobis distance, i.e.

An example of doing this would be:

import numpy as np

vals = np.array([[  6.83822474,   3.54843586],
                 [ 12.45778114,   4.42755159],
                 [ 10.27710359,   9.47337879],
                 [ 46.55259568,  64.73755611],
                 [ 51.50842754,  44.60132979]])

# Compute covariance matrix and its inverse
cov = np.cov(vals.T)
cov_inverse = np.linalg.inv(cov)

# Mean center the values
mean = np.mean(vals, axis=0)
centered_vals = vals - mean

# Compute Mahalanobis distance
dist = np.sqrt(np.sum(centered_vals * cov_inverse.dot(centered_vals.T).T, axis=1))

# Find points that are "far away" from the mean
indices = dist > 2


问:
Generating random numbers over a range in Go
All the integer functions in math/rand generate non-negative numbers.

```<code>rand.Int() int              // [0, MaxInt]
rand.Int31() int32          // [0, MaxInt32]
rand.Int31n(n int32) int32  // [0, n)
rand.Int63() int64          // [0, MaxInt64]
rand.Int63n(n int64) int64  // [0, n)
rand.Intn(n int) int        // [0, n)
</code>```

I would like to generate random numbers in the range [-m, n). In other words, I would like to generate a mix of positive and negative numbers.

答:
A small utility I wrote for generating random slices(very much like python range)

Code - https://github.com/alok87/goutils/blob/master/pkg/random/random.go

```<code>import "github.com/alok87/goutils/pkg/random"
random.RangeInt(2, 100, 5)

[3, 10, 30, 56, 67]
</code>```

Body:
All the integer functions in math/rand generate non-negative numbers.

rand.Int() int              // [0, MaxInt]
rand.Int31() int32          // [0, MaxInt32]
rand.Int31n(n int32) int32  // [0, n)
rand.Int63() int64          // [0, MaxInt64]
rand.Int63n(n int64) int64  // [0, n)
rand.Intn(n int) int        // [0, n)

I would like to generate random numbers in the range [-m, n). In other words, I would like to generate a mix of positive and negative numbers.

Body:
A small utility I wrote for generating random slices(very much like python range)

Code - https://github.com/alok87/goutils/blob/master/pkg/random/random.go

import "github.com/alok87/goutils/pkg/random"
random.RangeInt(2, 100, 5)

[3, 10, 30, 56, 67]


问:
Trouble centering background image
I'm having problems centering the background image within a certain div. I'm using the following code for CSS:

```<code>.background3 {
  max-width: 90%;
  height: 400px;
  margin: 0 auto;
  background: linear-gradient( rgba(86, 71, 71, 0.56), rgba(86, 71, 71, 0.56)), url(img/kitpage.jpg) no-repeat 50% 50%;
}
</code>```

I've tinkered and tried, but to no avail. I'm pretty sure it's an easy answer, and thank you all in advance for your help and advice.

A screenshot of the problem is attached below

答:
You have to use background position property e.g:

```<code>.background3 {
  max-width: 90%;
  height: 400px;
  margin: 0 auto;
  background-position:20% 20%; // Margin background from top and left
}
</code>```

You can adjust margin as you need  but it's not a good way. If you want more proper way then try this:

```<code>.background3 {
  max-width: 90%;
  height: 400px;
  margin: 0 auto;
  background-size:auto 100%;
  background-position:center center;
}
</code>```

Title: Trouble centering background image

Body:
I'm having problems centering the background image within a certain div. I'm using the following code for CSS:

.background3 {
  max-width: 90%;
  height: 400px;
  margin: 0 auto;
  background: linear-gradient( rgba(86, 71, 71, 0.56), rgba(86, 71, 71, 0.56)), url(img/kitpage.jpg) no-repeat 50% 50%;
}

I've tinkered and tried, but to no avail. I'm pretty sure it's an easy answer, and thank you all in advance for your help and advice.

A screenshot of the problem is attached below

Body:
You have to use background position property e.g:

.background3 {
  max-width: 90%;
  height: 400px;
  margin: 0 auto;
  background-position:20% 20%; // Margin background from top and left
}

You can adjust margin as you need  but it's not a good way. If you want more proper way then try this:

.background3 {
  max-width: 90%;
  height: 400px;
  margin: 0 auto;
  background-size:auto 100%;
  background-position:center center;
}


答:
It sounds like the generalization that you want is the Mahalanobis distance.  A Mahalanobis distance of 1 from the mean is the generalization of one standard deviation from the mean of a univariate Gaussian.

You can compute the Mahalanobis distance using functions in the module scipy.spatial.distance.  (There is almost certainly code for this distance in some form in scikit-learn, and possibly statsmodels, but I haven't checked.)

For computing a single distance, there is scipy.spatial.distance.mahalanobis, and for computing distances among or between collections of points, you can use pdist and cdist, respectively (also from scipy.spatial.distance).

Here's a script that uses cdist. In the plot, the points circled in red are within a Mahalanobis distance of 2 from the mean.

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist

# Mean
M = [10, 7]

# Covariance matrix
V = np.array([[ 9, -2],
              [-2,  2]])
VI = np.linalg.inv(V)

# Generate a sample from the multivariate normal distribution
# with mean M and covariance matrix V.
rng = np.random.default_rng()
x = rng.multivariate_normal(M, V, size=250)

# Compute the Mahalanobis distance of each point in the sample.
mdist = cdist(x, [M], metric='mahalanobis', VI=VI)[:,0]

# Find where the Mahalanobis distance is less than 2.
d2_mask = mdist < 2
x2 = x[d2_mask]

plt.plot(x2[:,0], x2[:,1], 'o',
         markeredgecolor='r', markerfacecolor='w', markersize=6, alpha=0.6)
plt.plot(x[:,0], x[:,1], 'k.', markersize=5, alpha=0.5)
plt.grid(alpha=0.3)
plt.axis('equal')
plt.show()
</code>```

Title: Selecting points in dataset that belong to a multivariate Gaussian distribution

Body:
It sounds like the generalization that you want is the Mahalanobis distance.  A Mahalanobis distance of 1 from the mean is the generalization of one standard deviation from the mean of a univariate Gaussian.

You can compute the Mahalanobis distance using functions in the module scipy.spatial.distance.  (There is almost certainly code for this distance in some form in scikit-learn, and possibly statsmodels, but I haven't checked.)

For computing a single distance, there is scipy.spatial.distance.mahalanobis, and for computing distances among or between collections of points, you can use pdist and cdist, respectively (also from scipy.spatial.distance).

Here's a script that uses cdist. In the plot, the points circled in red are within a Mahalanobis distance of 2 from the mean.

import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist

# Mean
M = [10, 7]

# Covariance matrix
V = np.array([[ 9, -2],
              [-2,  2]])
VI = np.linalg.inv(V)

# Generate a sample from the multivariate normal distribution
# with mean M and covariance matrix V.
rng = np.random.default_rng()
x = rng.multivariate_normal(M, V, size=250)

# Compute the Mahalanobis distance of each point in the sample.
mdist = cdist(x, [M], metric='mahalanobis', VI=VI)[:,0]

# Find where the Mahalanobis distance is less than 2.
d2_mask = mdist < 2
x2 = x[d2_mask]

plt.plot(x2[:,0], x2[:,1], 'o',
         markeredgecolor='r', markerfacecolor='w', markersize=6, alpha=0.6)
plt.plot(x[:,0], x[:,1], 'k.', markersize=5, alpha=0.5)
plt.grid(alpha=0.3)
plt.axis('equal')
plt.show()


问:
How access to $loop variable in nested foreach blade
```<code>@foreach($last_articles->chunk(3) as $row)
        @foreach($row as $last_article)
                @if($loop->index!=0) {{"in $loop"}} @endif
        @endforeach
        @if($loop->index!=0) {{"out $loop"}} @endif
@endforeach
</code>```

how to access the $loop of any of foreach, that was used in the code?

答: You could use $loop->parent to access the parent loop of the current loop.

Body:
@foreach($last_articles->chunk(3) as $row)
        @foreach($row as $last_article)
                @if($loop->index!=0) {{"in $loop"}} @endif
        @endforeach
        @if($loop->index!=0) {{"out $loop"}} @endif
@endforeach

how to access the $loop of any of foreach, that was used in the code?


问:
Create (dplyr::mutate) and select (dplyr::select) new variables that paste two existing columns by means of a user-defined function
Using a user-defined function I have to join the lower and higher bound of confidence intervals (named as CIlow and CIhigh) of a selected number of columns from a data frame. The data frame has CIlow and CIhigh for a number of groups (named as a, b and c) and for a number row (in this example just two). See below how the data frame looks like.

```<code>dataframe<-data.frame(CIlow_a=c(1.1,1.2),CIlow_b=c(2.1,2.2),CIlow_c=c(3.1,3.2),
CIhigh_a=c(1.3,1.4),CIhigh_b=c(2.3,2.4),CIhigh_c=c(3.3,3.4))
</code>```

I would like to have a joined column for each group in a selected number of groups (e.g. a, b) among the existing ones (a, b and c).

Thus, the expected output should be the following:

```<code>output<-data.frame(CI_a=c("(1.1,1.3)","(1.2,1.4)"),
                  CI_b=c("(2.1,2.3)","(2.2,2.4)"))
</code>```

To built my own user-defined function I tried the following code:

```<code>f<-function(df,gr){

enquo_gr<-enquo(gr)

r<-df%>%
   dplyr::mutate(UQ(paste("CI",quo_name(gr),sep="_")):=
                   sprintf("(%s,%s)",
                           paste("CIlow",UQ(enquo_gr),sep="_"),
                           paste("CIhigh",UQ(enquo_gr),sep="_")))%>%
   dplyr::select(paste("CI",UQ(enquo_gr),sep="_"))

return(r)
}
</code>```

However when using the above mentioned function in this way

```<code>library(dplyr)
group<-c("a","b")
dataframe<-data.frame(CIlow_a=c(1.1,1.2),CIlow_b=c(2.1,2.2),CIlow_c=c(3.1,3.2),CIhigh_a=c(1.3,1.4),CIhigh_b=c(2.3,2.4),CIhigh_c=c(3.3,3.4))

f(df=dataframe,gr=group)
</code>```

I get the following error message:

Error: expr must quote a symbol, scalar, or call

How could I solve this issue?

PS1: This question is similar to a previous one. However, this question goes one step further because it requires selecting the columns to be merged.

PS2: I would appreciate code suggestions following the approach of this question.

答:
If we are passing quoted strings, then use sym (for more than one element - syms which return a list)

```<code>f <- function(df, gr){
   sl <-  rlang::syms(paste("CIlow", gr, sep="_"))
   sh <-  rlang::syms(paste("CIhigh", gr, sep="_"))
   nmN <- paste("CI", gr, sep= "_")

   df %>%
       dplyr::mutate(!!(nmN[1]) := sprintf("(%s,%s)",
                               !!(sl[[1]]), !!(sh[[1]])),
                     !!(nmN[2]) := sprintf("(%s,%s)",
                               !!(sl[[2]]), !!(sh[[2]]))) %>%
       dplyr::select(paste("CI", gr, sep="_"))

 }

group <- c("a","b")
f(dataframe, group)
#      CI_a      CI_b
#1 (1.1,1.3) (2.1,2.3)
#2 (1.2,1.4) (2.2,2.4)
</code>```

Body:
Using a user-defined function I have to join the lower and higher bound of confidence intervals (named as CIlow and CIhigh) of a selected number of columns from a data frame. The data frame has CIlow and CIhigh for a number of groups (named as a, b and c) and for a number row (in this example just two). See below how the data frame looks like.

dataframe<-data.frame(CIlow_a=c(1.1,1.2),CIlow_b=c(2.1,2.2),CIlow_c=c(3.1,3.2),
CIhigh_a=c(1.3,1.4),CIhigh_b=c(2.3,2.4),CIhigh_c=c(3.3,3.4))

I would like to have a joined column for each group in a selected number of groups (e.g. a, b) among the existing ones (a, b and c).

Thus, the expected output should be the following:

output<-data.frame(CI_a=c("(1.1,1.3)","(1.2,1.4)"),
                  CI_b=c("(2.1,2.3)","(2.2,2.4)"))

To built my own user-defined function I tried the following code:

f<-function(df,gr){

enquo_gr<-enquo(gr)

r<-df%>%
   dplyr::mutate(UQ(paste("CI",quo_name(gr),sep="_")):=
                   sprintf("(%s,%s)",
                           paste("CIlow",UQ(enquo_gr),sep="_"),
                           paste("CIhigh",UQ(enquo_gr),sep="_")))%>%
   dplyr::select(paste("CI",UQ(enquo_gr),sep="_"))

return(r)
}

However when using the above mentioned function in this way

library(dplyr)
group<-c("a","b")
dataframe<-data.frame(CIlow_a=c(1.1,1.2),CIlow_b=c(2.1,2.2),CIlow_c=c(3.1,3.2),CIhigh_a=c(1.3,1.4),CIhigh_b=c(2.3,2.4),CIhigh_c=c(3.3,3.4))

f(df=dataframe,gr=group)

I get the following error message:

Error: expr must quote a symbol, scalar, or call

How could I solve this issue?

PS1: This question is similar to a previous one. However, this question goes one step further because it requires selecting the columns to be merged.

PS2: I would appreciate code suggestions following the approach of this question.

Body:
If we are passing quoted strings, then use sym (for more than one element - syms which return a list)

f <- function(df, gr){
   sl <-  rlang::syms(paste("CIlow", gr, sep="_"))
   sh <-  rlang::syms(paste("CIhigh", gr, sep="_"))
   nmN <- paste("CI", gr, sep= "_")

   df %>%
       dplyr::mutate(!!(nmN[1]) := sprintf("(%s,%s)",
                               !!(sl[[1]]), !!(sh[[1]])),
                     !!(nmN[2]) := sprintf("(%s,%s)",
                               !!(sl[[2]]), !!(sh[[2]]))) %>%
       dplyr::select(paste("CI", gr, sep="_"))

 }

group <- c("a","b")
f(dataframe, group)
#      CI_a      CI_b
#1 (1.1,1.3) (2.1,2.3)
#2 (1.2,1.4) (2.2,2.4)


问:
Get all classes that implement a certain abstract class
I'm trying to get all classes that implement a certain abstract class. I'm trying to do that with the following code:

```<code>var type = typeof(BaseViewComponent);
var types = Assembly
    .GetEntryAssembly()
    .GetReferencedAssemblies()
    .Select(Assembly.Load)
    .SelectMany(s => s.GetTypes())
    .Where(p => type.IsAssignableFrom(p));
</code>```

But thus far I'm only able to get the abstract class it self. Not any class that implements that base class.

What do I have to change to get all the classes that implement this abstract base class?

答:
using System.Reflection;
using Microsoft.Extensions.DependencyModel;
```

<pre class="lang-cs prettyprint-override"><code>var asmNames = DependencyContext.Default.GetDefaultAssemblyNames();
var type = typeof(BaseViewComponent);

var allTypes = asmNames.Select(Assembly.Load)
    .SelectMany(t => t.GetTypes())
    .Where(p => p.GetTypeInfo().IsSubclassOf(type));
</code>```

Body:
I'm trying to get all classes that implement a certain abstract class. I'm trying to do that with the following code:

var type = typeof(BaseViewComponent);
var types = Assembly
    .GetEntryAssembly()
    .GetReferencedAssemblies()
    .Select(Assembly.Load)
    .SelectMany(s => s.GetTypes())
    .Where(p => type.IsAssignableFrom(p));

But thus far I'm only able to get the abstract class it self. Not any class that implements that base class.

What do I have to change to get all the classes that implement this abstract base class?

Body:
using System.Reflection;
using Microsoft.Extensions.DependencyModel;

var asmNames = DependencyContext.Default.GetDefaultAssemblyNames();
var type = typeof(BaseViewComponent);

var allTypes = asmNames.Select(Assembly.Load)
    .SelectMany(t => t.GetTypes())
    .Where(p => p.GetTypeInfo().IsSubclassOf(type));


问:
Matlab lsqnonlin Fit Problems with Options
Pretty sure Matlab is just ignoring my Solver Option settings... I'm setting the FuctionTolerance from the default 1e-6 to 1e-10 and the solver is stopping at 1e-8 telling me it's below the default 1e-6 limit.

The command I am using is options = optimoptions('lsqnonlin', 'FunctionTolerance', 1e-10). Any ideas?

Command window output below:

```<code>options =

  lsqnonlin options:

   Options used by current Algorithm ('trust-region-reflective'):
   (Other available algorithms: 'levenberg-marquardt')

   Set properties:
           FunctionTolerance: 1.0000e-10

   Default properties:
                   Algorithm: 'trust-region-reflective'
              CheckGradients: 0
                     Display: 'final'
    FiniteDifferenceStepSize: 'sqrt(eps)'
        FiniteDifferenceType: 'forward'
         JacobianMultiplyFcn: []
      MaxFunctionEvaluations: '100*numberOfVariables'
               MaxIterations: 400
         OptimalityTolerance: 1.0000e-06
                   OutputFcn: []
                     PlotFcn: []
    SpecifyObjectiveGradient: 0
               StepTolerance: 1.0000e-06
         SubproblemAlgorithm: 'factorization'
                    TypicalX: 'ones(numberOfVariables,1)'
                 UseParallel: 0

Local minimum possible.

lsqnonlin stopped because the final change in the sum of squares relative to
its initial value is less than the default value of the function tolerance.

<stopping criteria details>

Optimization stopped because the relative sum of squares (r) is changing
by less than options.FunctionTolerance = 1.000000e-06.

Optimization Metric                                  Options
relative change r =   6.50e-08             FunctionTolerance =   1e-06 (default)
</code>```

答:
Try reducing FiniteDifferenceStepSize, e.g.,

```<code>options = optimoptions('lsqnonlin', 'FunctionTolerance', 1e-10, 'FiniteDifferenceStepSize',1e-6)
</code>```

or even smaller Finite Difference Step Size.

Body:
Pretty sure Matlab is just ignoring my Solver Option settings... I'm setting the FuctionTolerance from the default 1e-6 to 1e-10 and the solver is stopping at 1e-8 telling me it's below the default 1e-6 limit.

The command I am using is options = optimoptions('lsqnonlin', 'FunctionTolerance', 1e-10). Any ideas?

Command window output below:

options =

  lsqnonlin options:

   Options used by current Algorithm ('trust-region-reflective'):
   (Other available algorithms: 'levenberg-marquardt')

   Set properties:
           FunctionTolerance: 1.0000e-10

   Default properties:
                   Algorithm: 'trust-region-reflective'
              CheckGradients: 0
                     Display: 'final'
    FiniteDifferenceStepSize: 'sqrt(eps)'
        FiniteDifferenceType: 'forward'
         JacobianMultiplyFcn: []
      MaxFunctionEvaluations: '100*numberOfVariables'
               MaxIterations: 400
         OptimalityTolerance: 1.0000e-06
                   OutputFcn: []
                     PlotFcn: []
    SpecifyObjectiveGradient: 0
               StepTolerance: 1.0000e-06
         SubproblemAlgorithm: 'factorization'
                    TypicalX: 'ones(numberOfVariables,1)'
                 UseParallel: 0

Local minimum possible.

lsqnonlin stopped because the final change in the sum of squares relative to
its initial value is less than the default value of the function tolerance.

<stopping criteria details>

Optimization stopped because the relative sum of squares (r) is changing
by less than options.FunctionTolerance = 1.000000e-06.

Optimization Metric                                  Options
relative change r =   6.50e-08             FunctionTolerance =   1e-06 (default)

Body:
Try reducing FiniteDifferenceStepSize, e.g.,

options = optimoptions('lsqnonlin', 'FunctionTolerance', 1e-10, 'FiniteDifferenceStepSize',1e-6)

or even smaller Finite Difference Step Size.


问:
IIS8 RewriteModule / URLRewrite Extremely Slow
I'm running a website with IIS8 on Windows Server 2012. I'm trying to determine what's causing high CPU usage by IIS (frequently 50% or more CPU usage by IIS). Server receives about 40 total requests per second throughout the day, but probably only 1-2 URLs per second that require processing.

I enabled Request Tracing and found that some RewriteModule requests are taking over 100 seconds (!) to complete. I'm having trouble determining how this is possible on a machine with more than sufficient hardware. The exact same URL structure is processed via mod_rewrite on Apache in less than a second.

An example URL would be like this:

```<code>http://<domain-name>/Product/<Parent-Category>/<Child-Category1>/<Child-Category2>/<Child-Category3>/<Product-Name>
</code>```

The accompanying rewrite rule is:

```<code><rule name="Rule" stopProcessing="true">
      <match url="^Product/([^/\?]+)/?([^/\?]+)?/?([^/\?]+)?/?([^/\?]+)?/?([^/\?]+)?/?([^/\?]+)?/?[\?]?(.+)?$"/>
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
      </conditions>
      <action type="Rewrite" url="/Product/index.php?a={R:1}&b={R:2}&c={R:3}&d={R:4}&e={R:5}&f={R:6}&{R:7}" appendQueryString="true"/>
    </rule>
</code>```

Is there something in the way that I'm defining the match URL that's causing high processing time? Some of the matching urls contain a high number of characters if they utilize many parent/child categories (up to 5, typically 3-4).

答:
Problem is definitely in your regexp. Best way is try to split it to different more specific patterns.

If it is not the case, this rule should keep the same functionality and work faster:

```<code><rule name="Rule" stopProcessing="true">
  <match url="^Product/([^/]+)/?([^/]+)?/?([^/]+)?/?([^/]+)?/?([^/]+)?/?([^/]+)?"/>
  <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
  </conditions>
  <action type="Rewrite" url="/Product/index.php?a={R:1}&b={R:2}&c={R:3}&d={R:4}&e={R:5}&f={R:6}" appendQueryString="true"/>
</rule>
</code>```

I removed unnecessary \? checks in your regexp, because patter inside <match url is checking URL without query string, so, it is redundant to have ? checks in your regexp.

I checked on my PC and it works definitely faster, but you need to double check that it remains the same functionality

Body:
I'm running a website with IIS8 on Windows Server 2012. I'm trying to determine what's causing high CPU usage by IIS (frequently 50% or more CPU usage by IIS). Server receives about 40 total requests per second throughout the day, but probably only 1-2 URLs per second that require processing.

I enabled Request Tracing and found that some RewriteModule requests are taking over 100 seconds (!) to complete. I'm having trouble determining how this is possible on a machine with more than sufficient hardware. The exact same URL structure is processed via mod_rewrite on Apache in less than a second.

An example URL would be like this:

http://<domain-name>/Product/<Parent-Category>/<Child-Category1>/<Child-Category2>/<Child-Category3>/<Product-Name>

The accompanying rewrite rule is:

<rule name="Rule" stopProcessing="true">
      <match url="^Product/([^/\?]+)/?([^/\?]+)?/?([^/\?]+)?/?([^/\?]+)?/?([^/\?]+)?/?([^/\?]+)?/?[\?]?(.+)?$"/>
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
      </conditions>
      <action type="Rewrite" url="/Product/index.php?a={R:1}&b={R:2}&c={R:3}&d={R:4}&e={R:5}&f={R:6}&{R:7}" appendQueryString="true"/>
    </rule>

Is there something in the way that I'm defining the match URL that's causing high processing time? Some of the matching urls contain a high number of characters if they utilize many parent/child categories (up to 5, typically 3-4).

Body:
Problem is definitely in your regexp. Best way is try to split it to different more specific patterns.

If it is not the case, this rule should keep the same functionality and work faster:

<rule name="Rule" stopProcessing="true">
  <match url="^Product/([^/]+)/?([^/]+)?/?([^/]+)?/?([^/]+)?/?([^/]+)?/?([^/]+)?"/>
  <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
  </conditions>
  <action type="Rewrite" url="/Product/index.php?a={R:1}&amp;b={R:2}&amp;c={R:3}&amp;d={R:4}&amp;e={R:5}&amp;f={R:6}" appendQueryString="true"/>
</rule>

I removed unnecessary \? checks in your regexp, because patter inside <match url is checking URL without query string, so, it is redundant to have ? checks in your regexp.

I checked on my PC and it works definitely faster, but you need to double check that it remains the same functionality


问:
Why is math.sqrt() incorrect for large numbers?
Why does the math module return the wrong result?

First test

```<code>A = 12345678917
print 'A =',A
B = sqrt(A**2)
print 'B =',int(B)
</code>```

Result

```<code>A = 12345678917
B = 12345678917
</code>```

Here, the result is correct.

Second test

```<code>A = 123456758365483459347856
print 'A =',A
B = sqrt(A**2)
print 'B =',int(B)
</code>```

Result

```<code>A = 123456758365483459347856
B = 123456758365483467538432
</code>```

Here the result is incorrect.

Why is that the case?

答:
The way floating-point numbers are stored in memory makes calculations with them prone to slight errors that can nevertheless be significant when exact results are needed. As mentioned in one of the comments, the decimal library can help you here:

```<code>>>> A = Decimal(12345678917)
>>> A
Decimal('123456758365483459347856')
>>> B = A.sqrt()**2
>>> B
Decimal('123456758365483459347856.0000')
>>> A == B
True
>>> int(B)
123456758365483459347856
</code>```

I use version 3.6, which has no hardcoded limit on the size of integers. I don't know if, in 2.7, casting B as an int would cause overflow, but decimal is incredibly useful regardless.

Body:
Why does the math module return the wrong result?

First test

A = 12345678917
print 'A =',A
B = sqrt(A**2)
print 'B =',int(B)

Result

A = 12345678917
B = 12345678917

Here, the result is correct.

Second test

A = 123456758365483459347856
print 'A =',A
B = sqrt(A**2)
print 'B =',int(B)

Result

A = 123456758365483459347856
B = 123456758365483467538432

Here the result is incorrect.

Why is that the case?

Body:
The way floating-point numbers are stored in memory makes calculations with them prone to slight errors that can nevertheless be significant when exact results are needed. As mentioned in one of the comments, the decimal library can help you here:

>>> A = Decimal(12345678917)
>>> A
Decimal('123456758365483459347856')
>>> B = A.sqrt()**2
>>> B
Decimal('123456758365483459347856.0000')
>>> A == B
True
>>> int(B)
123456758365483459347856

I use version 3.6, which has no hardcoded limit on the size of integers. I don't know if, in 2.7, casting B as an int would cause overflow, but decimal is incredibly useful regardless.