问:
Angular 9 - Avoiding multiple API calls on typeahead feature
I'm implementing a search box that should make a call to an API with the value the user entered. I want to make the call when the user stops typing for some ms.

This works fine for the first request:

```<code>this.searchForm.get('searchQuery').valueChanges.pipe(
  filter(data => data.trim().length > 0),
  debounceTime(500),
  switchMap( (query: string) => this.productsService.searchProducts(query))
).subscribe();
</code>```

But, if I continue to type it waits for another 500ms and then sends multiple requests (equal to the number of characters typed, for what it seems).

```<code>productsChanged = new Subject<Product[]>();

  searchProducts(query: string) {
    return this.http.get<Product[]>(this.baseUrl + '/products/search/' + query)
        .pipe(
          tap(products => {
            this.products = products;
            this.productsChanged.next(this.products.slice());
          }));
   }
</code>```

It will probably be something very simple, but I can't seem to understand what's happening.

Stackblitz: https://stackblitz.com/edit/angular-ivy-w4mbhm

Solution

I have found the problem.

I was listening to (ngModelChange):

```<code>  <input
name="searchQuery"
type="text"
[(ngModel)]="searchQuery"
(ngModelChange)="onSearch()"
formControlName="searchQuery" />
</code>```

And inside that listener I was appending a new listener to 'valueChanges'. So on each key stroke, a new listener was created.

As expected, a simple mistake, that made me spend some hours.

Thanks for your help!

答:
Like I suspected, you are subscribing constantly to your form changes. You should only do this once in your component (or not at all, if you use the async pipe):

working stack

```<code>ngOnInit(): void {
  this.searchForm = new FormGroup({
    searchQuery: new FormControl()
  });

  this.searchForm
    .get("searchQuery")
    .valueChanges.pipe(
      filter(data => data?.trim().length > 0),
      debounceTime(500),
      switchMap((query: string) => this.productsService.searchProducts(query).pipe(
        catchError((e) => of([])
      )))
    )
    .subscribe((e) => {
      console.log(e)
    });
}
</code>```

You can also do:

```<code>ngOnInit(): void {
  this.products$ = this.searchForm.get("searchQuery").valueChanges.pipe(
    // ...
  )
}
</code>```

and use the async pipe. This way you don't have to unsubscribe on destroy

Body:
I'm implementing a search box that should make a call to an API with the value the user entered. I want to make the call when the user stops typing for some ms.

This works fine for the first request:

this.searchForm.get('searchQuery').valueChanges.pipe(
  filter(data => data.trim().length > 0),
  debounceTime(500),
  switchMap( (query: string) => this.productsService.searchProducts(query))
).subscribe();

But, if I continue to type it waits for another 500ms and then sends multiple requests (equal to the number of characters typed, for what it seems).

productsChanged = new Subject<Product[]>();

  searchProducts(query: string) {
    return this.http.get<Product[]>(this.baseUrl + '/products/search/' + query)
        .pipe(
          tap(products => {
            this.products = products;
            this.productsChanged.next(this.products.slice());
          }));
   }

It will probably be something very simple, but I can't seem to understand what's happening.

Stackblitz: https://stackblitz.com/edit/angular-ivy-w4mbhm

Solution

I have found the problem.

I was listening to (ngModelChange):

  <input
name="searchQuery"
type="text"
[(ngModel)]="searchQuery"
(ngModelChange)="onSearch()"
formControlName="searchQuery" />

And inside that listener I was appending a new listener to 'valueChanges'. So on each key stroke, a new listener was created.

As expected, a simple mistake, that made me spend some hours.

Thanks for your help!

Body:
Like I suspected, you are subscribing constantly to your form changes. You should only do this once in your component (or not at all, if you use the async pipe):

working stack

ngOnInit(): void {
  this.searchForm = new FormGroup({
    searchQuery: new FormControl()
  });

  this.searchForm
    .get("searchQuery")
    .valueChanges.pipe(
      filter(data => data?.trim().length > 0),
      debounceTime(500),
      switchMap((query: string) => this.productsService.searchProducts(query).pipe(
        catchError((e) => of([])
      )))
    )
    .subscribe((e) => {
      console.log(e)
    });
}

You can also do:

ngOnInit(): void {
  this.products$ = this.searchForm.get("searchQuery").valueChanges.pipe(
    // ...
  )
}

and use the async pipe. This way you don't have to unsubscribe on destroy


来源: stackexchange

问:
Typescript function overloading: typescript does not analyze function code
Consider following function overloading and implementation with bugs.

function foo(param: number): boolean;
function foo(param: string): string;

function foo(param) {
  if (typeof param === "number") {
    // typescript does not complain that 12 is not boolean
    return 12;
  } else if (typeof param === "string") {
    // typescript does not complain that {} is not string
    return {};
  }
}
```

Here is how one can interpret it:

if function foo takes numeric param it should return boolean

if function foo takes string param it should return string

another calls should be prohibited

Sure it is possible for type checker to verify 1&2 by analyzing function code.
But typescript does not do this - it only does 3.

Is it possible to achieve in typescript above mentioned behavior?

答:
Remove function foo(param). This adds a third overload with param typed as any.

```<code>function foo(param: number): boolean;
function foo(param: string): string {
  if (typeof param === "number") {
    return 12;
  } else if (typeof param === "string") {
    return {};
  }
}
</code>```

Code in TypeScript Playground

ContentLicense: CC BY-SA 4.0

Body:
Consider following function overloading and implementation with bugs.

function foo(param: number): boolean;
function foo(param: string): string;

function foo(param) {
  if (typeof param === "number") {
    // typescript does not complain that 12 is not boolean
    return 12;
  } else if (typeof param === "string") {
    // typescript does not complain that {} is not string
    return {};
  }
}

Here is how one can interpret it:

if function foo takes numeric param it should return boolean

if function foo takes string param it should return string

another calls should be prohibited

Sure it is possible for type checker to verify 1&2 by analyzing function code.
But typescript does not do this - it only does 3.

Is it possible to achieve in typescript above mentioned behavior?

Body:
Remove function foo(param). This adds a third overload with param typed as any.

function foo(param: number): boolean;
function foo(param: string): string {
  if (typeof param === "number") {
    return 12;
  } else if (typeof param === "string") {
    return {};
  }
}

Code in TypeScript Playground


问:
How can I separate arrays by nested child objects in javascript?
I would like to separate the nested objects whose condition is courses and take it to the beginning and then relate it to the object to which each course of the following array belongs, I have an idea of how to do it with map, please friends I will thank you in advance

```<code>[
   {
      "id":41,
      "escuela_id":1,
      "ciclo":1,
      "descripcion":"Primer ciclo",
      "cursos":[
         {
            "id":1,
            "ciclo_id":41,
            "nombre":"Introducción a la danza",
            "tipo":"obligatorio",
         },
         {
            "id":3,
            "ciclo_id":41,
            "nombre":"Fundamento de la danza",
            "tipo":"obligatorio",
         },

      ],
      "escuela":{
         "id":1,
         "facultad_id":1,
         "nombre":"DANZA",
      }
   },
   {
      "id":46,
      "escuela_id":1,
      "ciclo":2,
      "descripcion":"Segundo ciclo",
      "cursos":[
        {
            "id":4,
            "ciclo_id":46,
            "nombre":"Danza moderna",
            "tipo":"obligatorio",
         }
      ],
      "escuela":{
         "id":1,
         "facultad_id":1,
         "nombre":"DANZA",
      }
   }
]
</code>```

As a result I would like the following array some way to do with map or reduce

```<code>[
   {
      "id":1,
      "ciclo_id":41,
      "nombre":"Introducción a la danza",
      "tipo":"obligatorio",
      "ciclo":{
         "id":41,
         "escuela_id":1,
         "ciclo":1,
         "descripcion":"Primer ciclo"
      },
      "escuela":{
         "id":1,
         "facultad_id":1,
         "nombre":"DANZA"
      }
   },
   {
      "id":3,
      "ciclo_id":41,
      "nombre":"Fundamento de la danza",
      "tipo":"obligatorio",
      "ciclo":{
         "id":41,
         "escuela_id":1,
         "ciclo":1,
         "descripcion":"Primer ciclo"
      },
      "escuela":{
         "id":1,
         "facultad_id":1,
         "nombre":"DANZA"
      }
   },
   {
      "id":4,
      "ciclo_id":46,
      "nombre":"Danza moderna",
      "tipo":"obligatorio",
      "ciclo":{
         "id":46,
         "escuela_id":1,
         "ciclo":2,
         "descripcion":"Segundo ciclo"
      },
      "escuela":{
         "id":1,
         "facultad_id":1,
         "nombre":"DANZA"
      }
   }
]
</code>```

答:
We can solve your specific problem like this, with reduce and map. (To make it more generic would be possible, but also add a bit of work.)

const myInput = [
   {
      "id":41,
      "escuela_id":1,
      "ciclo":1,
      "descripcion":"Primer ciclo",
      "cursos":[
         {
            "id":1,
            "ciclo_id":41,
            "nombre":"Introducción a la danza",
            "tipo":"obligatorio",
         },
         {
            "id":3,
            "ciclo_id":41,
            "nombre":"Fundamento de la danza",
            "tipo":"obligatorio",
         },
      ],
      "escuela":{
         "id":1,
         "facultad_id":1,
         "nombre":"DANZA",
      }
   },
   {
      "id":46,
      "escuela_id":1,
      "ciclo":2,
      "descripcion":"Segundo ciclo",
      "cursos":[
        {
            "id":4,
            "ciclo_id":46,
            "nombre":"Danza moderna",
            "tipo":"obligatorio",
         }
      ],
      "escuela":{
         "id":1,
         "facultad_id":1,
         "nombre":"DANZA",
      }
   }
]

const myOutput = myInput.reduce((aggArr, item) => {

  const cursos = item.cursos.map(curso => {
    const tempItem = {...item};
    const tempEscuela = {...tempItem.escuela};
    delete tempItem.cursos;
    delete tempItem.escuela;

    return {...curso, 'ciclo': tempItem, 'escuela': tempEscuela};
  })

  return [...aggArr, ...cursos]
}, [])

console.log(myOutput)```
</div>
</div>
</p>

<p>OUTPUT:</p>

<pre class="lang-js prettyprint-override"><code>[
  {
    "id": 1,
    "ciclo_id": 41,
    "nombre": "Introducción a la danza",
    "tipo": "obligatorio",
    "ciclo": {
      "id": 41,
      "escuela_id": 1,
      "ciclo": 1,
      "descripcion": "Primer ciclo"
    },
    "escuela": {
      "id": 1,
      "facultad_id": 1,
      "nombre": "DANZA"
    }
  },
  {
    "id": 3,
    "ciclo_id": 41,
    "nombre": "Fundamento de la danza",
    "tipo": "obligatorio",
    "ciclo": {
      "id": 41,
      "escuela_id": 1,
      "ciclo": 1,
      "descripcion": "Primer ciclo"
    },
    "escuela": {
      "id": 1,
      "facultad_id": 1,
      "nombre": "DANZA"
    }
  },
  {
    "id": 4,
    "ciclo_id": 46,
    "nombre": "Danza moderna",
    "tipo": "obligatorio",
    "ciclo": {
      "id": 46,
      "escuela_id": 1,
      "ciclo": 2,
      "descripcion": "Segundo ciclo"
    },
    "escuela": {
      "id": 1,
      "facultad_id": 1,
      "nombre": "DANZA"
    }
  }
]
</code>```

Body:
I would like to separate the nested objects whose condition is courses and take it to the beginning and then relate it to the object to which each course of the following array belongs, I have an idea of how to do it with map, please friends I will thank you in advance

[
   {
      "id":41,
      "escuela_id":1,
      "ciclo":1,
      "descripcion":"Primer ciclo",
      "cursos":[
         {
            "id":1,
            "ciclo_id":41,
            "nombre":"Introducción a la danza",
            "tipo":"obligatorio",
         },
         {
            "id":3,
            "ciclo_id":41,
            "nombre":"Fundamento de la danza",
            "tipo":"obligatorio",
         },

      ],
      "escuela":{
         "id":1,
         "facultad_id":1,
         "nombre":"DANZA",
      }
   },
   {
      "id":46,
      "escuela_id":1,
      "ciclo":2,
      "descripcion":"Segundo ciclo",
      "cursos":[
        {
            "id":4,
            "ciclo_id":46,
            "nombre":"Danza moderna",
            "tipo":"obligatorio",
         }
      ],
      "escuela":{
         "id":1,
         "facultad_id":1,
         "nombre":"DANZA",
      }
   }
]

As a result I would like the following array some way to do with map or reduce

[
   {
      "id":1,
      "ciclo_id":41,
      "nombre":"Introducción a la danza",
      "tipo":"obligatorio",
      "ciclo":{
         "id":41,
         "escuela_id":1,
         "ciclo":1,
         "descripcion":"Primer ciclo"
      },
      "escuela":{
         "id":1,
         "facultad_id":1,
         "nombre":"DANZA"
      }
   },
   {
      "id":3,
      "ciclo_id":41,
      "nombre":"Fundamento de la danza",
      "tipo":"obligatorio",
      "ciclo":{
         "id":41,
         "escuela_id":1,
         "ciclo":1,
         "descripcion":"Primer ciclo"
      },
      "escuela":{
         "id":1,
         "facultad_id":1,
         "nombre":"DANZA"
      }
   },
   {
      "id":4,
      "ciclo_id":46,
      "nombre":"Danza moderna",
      "tipo":"obligatorio",
      "ciclo":{
         "id":46,
         "escuela_id":1,
         "ciclo":2,
         "descripcion":"Segundo ciclo"
      },
      "escuela":{
         "id":1,
         "facultad_id":1,
         "nombre":"DANZA"
      }
   }
]

Body:
We can solve your specific problem like this, with reduce and map. (To make it more generic would be possible, but also add a bit of work.)

const myInput = [
   {
      "id":41,
      "escuela_id":1,
      "ciclo":1,
      "descripcion":"Primer ciclo",
      "cursos":[
         {
            "id":1,
            "ciclo_id":41,
            "nombre":"Introducción a la danza",
            "tipo":"obligatorio",
         },
         {
            "id":3,
            "ciclo_id":41,
            "nombre":"Fundamento de la danza",
            "tipo":"obligatorio",
         },
      ],
      "escuela":{
         "id":1,
         "facultad_id":1,
         "nombre":"DANZA",
      }
   },
   {
      "id":46,
      "escuela_id":1,
      "ciclo":2,
      "descripcion":"Segundo ciclo",
      "cursos":[
        {
            "id":4,
            "ciclo_id":46,
            "nombre":"Danza moderna",
            "tipo":"obligatorio",
         }
      ],
      "escuela":{
         "id":1,
         "facultad_id":1,
         "nombre":"DANZA",
      }
   }
]

const myOutput = myInput.reduce((aggArr, item) => {

  const cursos = item.cursos.map(curso => {
    const tempItem = {...item};
    const tempEscuela = {...tempItem.escuela};
    delete tempItem.cursos;
    delete tempItem.escuela;

    return {...curso, 'ciclo': tempItem, 'escuela': tempEscuela};
  })

  return [...aggArr, ...cursos]
}, [])

console.log(myOutput)

OUTPUT:

[
  {
    "id": 1,
    "ciclo_id": 41,
    "nombre": "Introducción a la danza",
    "tipo": "obligatorio",
    "ciclo": {
      "id": 41,
      "escuela_id": 1,
      "ciclo": 1,
      "descripcion": "Primer ciclo"
    },
    "escuela": {
      "id": 1,
      "facultad_id": 1,
      "nombre": "DANZA"
    }
  },
  {
    "id": 3,
    "ciclo_id": 41,
    "nombre": "Fundamento de la danza",
    "tipo": "obligatorio",
    "ciclo": {
      "id": 41,
      "escuela_id": 1,
      "ciclo": 1,
      "descripcion": "Primer ciclo"
    },
    "escuela": {
      "id": 1,
      "facultad_id": 1,
      "nombre": "DANZA"
    }
  },
  {
    "id": 4,
    "ciclo_id": 46,
    "nombre": "Danza moderna",
    "tipo": "obligatorio",
    "ciclo": {
      "id": 46,
      "escuela_id": 1,
      "ciclo": 2,
      "descripcion": "Segundo ciclo"
    },
    "escuela": {
      "id": 1,
      "facultad_id": 1,
      "nombre": "DANZA"
    }
  }
]


问:
JavaSound: Extract one channel of stereo audio
I have a stereo wave file that I need to read and play back only the selected channel. What is the best way to accomplish this? </p>

答:
Here is a simple method to extract single channels from a multi channel direct audio line (JavaSound). In tried it with my Line6(r) Helix(r) guitar sound effect board (8 channels) and it works pretty fine. I guess it works with any kind of DataTargetLine. In this case we process data based on an AudioFormat bearing 16 bits samples. Hope it helps.</p>

```<code>    public ArrayList<byte[]> extract16BitsSingleChannels(byte[] audioBuffer, int channels) {

    /* Parameters :
     *
     * audioBuffer : the buffer that has just been produced by
     * your targetDataLine.read();
     * channels : the number of channels defined in the AudioFormat you
     * use with the line
     *
     *  the AudioFormat which I tested :
     *       float sampleRate = 44100;
     *       int sampleSizeInBits = 16;
     *       int channels = 8;
     *       boolean signed = true;
     *       boolean bigEndian = true;
     */

    /* let's create a container which will receive our "per channel" buffers */

    ArrayList<byte[]> channelsData = new ArrayList<byte[]>();

    /* take care of adjusting the size of the audioBuffer so that
     * audioBuffer % channels == 0 is true ... because :
     */

    final int channelLength=audioBuffer.length/channels;

    /* let's create one buffer per channel and place them in the
     * container
     */

    for (int c=0 ; c < channels ; c++)

    {
        byte[] channel=new byte[channelLength];
        channelsData.add(channel);
    }

    /* then process bytes from audioBuffer and copy each channels byte
     * in its dedicated buffer
     */

    int byteIndex=0;

    for(int i = 0; i < channelLength; i+=2) //i+=2 for 16 bits=2 Bytes samples
    {
        for (int c=0 ; c < channels ; c++) {
            channelsData.get(c)[i]=audioBuffer[byteIndex];   // 1st Byte
            byteIndex++;
            channelsData.get(c)[i+1]=audioBuffer[byteIndex]; // 2nd Byte
            byteIndex++;
        }

    }

    /* Returns each set of bytes from each channel in its buffer you can use to
       write on whatever Byte streamer you like. */

    return channelsData;

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is a simple method to extract single channels from a multi channel direct audio line (JavaSound). In tried it with my Line6(r) Helix(r) guitar sound effect board (8 channels) and it works pretty fine. I guess it works with any kind of DataTargetLine. In this case we process data based on an AudioFormat bearing 16 bits samples. Hope it helps.

    public ArrayList<byte[]> extract16BitsSingleChannels(byte[] audioBuffer, int channels) {

    /* Parameters :
     *
     * audioBuffer : the buffer that has just been produced by
     * your targetDataLine.read();
     * channels : the number of channels defined in the AudioFormat you
     * use with the line
     *
     *  the AudioFormat which I tested :
     *       float sampleRate = 44100;
     *       int sampleSizeInBits = 16;
     *       int channels = 8;
     *       boolean signed = true;
     *       boolean bigEndian = true;
     */

    /* let's create a container which will receive our "per channel" buffers */

    ArrayList<byte[]> channelsData = new ArrayList<byte[]>();

    /* take care of adjusting the size of the audioBuffer so that
     * audioBuffer % channels == 0 is true ... because :
     */

    final int channelLength=audioBuffer.length/channels;

    /* let's create one buffer per channel and place them in the
     * container
     */

    for (int c=0 ; c < channels ; c++)

    {
        byte[] channel=new byte[channelLength];
        channelsData.add(channel);
    }

    /* then process bytes from audioBuffer and copy each channels byte
     * in its dedicated buffer
     */

    int byteIndex=0;

    for(int i = 0; i < channelLength; i+=2) //i+=2 for 16 bits=2 Bytes samples
    {
        for (int c=0 ; c < channels ; c++) {
            channelsData.get(c)[i]=audioBuffer[byteIndex];   // 1st Byte
            byteIndex++;
            channelsData.get(c)[i+1]=audioBuffer[byteIndex]; // 2nd Byte
            byteIndex++;
        }

    }

    /* Returns each set of bytes from each channel in its buffer you can use to
       write on whatever Byte streamer you like. */

    return channelsData;

}


问:
The "fire" is returning to (X 0) after it hits the right edge
I'm coding a game where you're a spider and you're trying to avoid fire. I'm coding the fire and when it hits the right edge it returns to the left edge and goes up and down it ad infinitum. I'm using the code from school free software as a base with some modification "bouncing ball animation".

test1.xdest and test1.ydest aren't being called anywhere else but in sub bounce and in the main do loop. I'm not sure why it's doing it.

```<code>SCREEN _NEWIMAGE(640, 480, 32)
RANDOMIZE TIMER
TYPE test 'player info
    x AS INTEGER
    y AS INTEGER
END TYPE

TYPE test1 'fire info
    x AS INTEGER
    y AS INTEGER
    xdest AS INTEGER
    ydest AS INTEGER
    number AS INTEGER
    fire AS LONG
END TYPE

DIM SHARED spider AS test
DIM SHARED test1 AS test1
test1.x = 0 'fire x chord
test1.y = 0 'fire y chord

test1.xdest = 1 '1 if fire is moving right 0 left
test1.ydest = 0 '1 up 0 down
test1.fire = _LOADIMAGE("./fire.png")

DO
    PCOPY 1, _DISPLAY
    CLS
    IF _KEYDOWN(18432) THEN spider.y = spider.y - 5
    IF _KEYDOWN(20480) THEN spider.y = spider.y + 5

    IF _KEYDOWN(19200) THEN spider.x = spider.x - 5
    IF _KEYDOWN(19712) THEN spider.x = spider.x + 5
    CIRCLE (spider.x, spider.y), 5, _RGB(177, 83, 127)
    _PUTIMAGE (test1.x, test1.y), test1.fire
    IF test1.xdest = 1 THEN test1.x = test1.x + 5
    IF test1.xdest = 0 THEN test1.x = text1.x - 5

    IF test1.ydest = 1 THEN test1.y = test1.y - 5
    IF test1.ydest = 0 THEN test1.y = test1.y + 5

    bounce
    border

    WAIT &H3DA, &H3DA
    WAIT &H3DA, &H3DA, 8
    _DISPLAY
    PCOPY _DISPLAY, 1
LOOP

SUB bounce 'makes the fire bounce
    IF test1.x >= 628 THEN
        test1.xdest = 0
    END IF
    IF test1.x <= 0 THEN
        text1.xdest = 1
    END IF
    IF test1.y >= 468 THEN
        test1.ydest = 1
    END IF
    IF test1.y <= 0 THEN
        test1.ydest = 0
    END IF
END SUB
SUB border 'prevents palyer from going OOB
    IF spider.x > 630 THEN spider.x = spider.x - 5
    IF spider.x < 0 THEN spider.x = spider.x + 5
    IF spider.y > 470 THEN spider.y = spider.y - 5
    IF spider.y < 0 THEN spider.y = spider.y + 5
END SUB
</code>```

答: i figured it out, on line 37, i misspelled one of my variables, i put text1.x instead of test1.x

Body:
I'm coding a game where you're a spider and you're trying to avoid fire. I'm coding the fire and when it hits the right edge it returns to the left edge and goes up and down it ad infinitum. I'm using the code from school free software as a base with some modification "bouncing ball animation".

test1.xdest and test1.ydest aren't being called anywhere else but in sub bounce and in the main do loop. I'm not sure why it's doing it.

SCREEN _NEWIMAGE(640, 480, 32)
RANDOMIZE TIMER
TYPE test 'player info
    x AS INTEGER
    y AS INTEGER
END TYPE

TYPE test1 'fire info
    x AS INTEGER
    y AS INTEGER
    xdest AS INTEGER
    ydest AS INTEGER
    number AS INTEGER
    fire AS LONG
END TYPE

DIM SHARED spider AS test
DIM SHARED test1 AS test1
test1.x = 0 'fire x chord
test1.y = 0 'fire y chord

test1.xdest = 1 '1 if fire is moving right 0 left
test1.ydest = 0 '1 up 0 down
test1.fire = _LOADIMAGE("./fire.png")

DO
    PCOPY 1, _DISPLAY
    CLS
    IF _KEYDOWN(18432) THEN spider.y = spider.y - 5
    IF _KEYDOWN(20480) THEN spider.y = spider.y + 5

    IF _KEYDOWN(19200) THEN spider.x = spider.x - 5
    IF _KEYDOWN(19712) THEN spider.x = spider.x + 5
    CIRCLE (spider.x, spider.y), 5, _RGB(177, 83, 127)
    _PUTIMAGE (test1.x, test1.y), test1.fire
    IF test1.xdest = 1 THEN test1.x = test1.x + 5
    IF test1.xdest = 0 THEN test1.x = text1.x - 5

    IF test1.ydest = 1 THEN test1.y = test1.y - 5
    IF test1.ydest = 0 THEN test1.y = test1.y + 5

    bounce
    border

    WAIT &H3DA, &H3DA
    WAIT &H3DA, &H3DA, 8
    _DISPLAY
    PCOPY _DISPLAY, 1
LOOP

SUB bounce 'makes the fire bounce
    IF test1.x >= 628 THEN
        test1.xdest = 0
    END IF
    IF test1.x <= 0 THEN
        text1.xdest = 1
    END IF
    IF test1.y >= 468 THEN
        test1.ydest = 1
    END IF
    IF test1.y <= 0 THEN
        test1.ydest = 0
    END IF
END SUB
SUB border 'prevents palyer from going OOB
    IF spider.x > 630 THEN spider.x = spider.x - 5
    IF spider.x < 0 THEN spider.x = spider.x + 5
    IF spider.y > 470 THEN spider.y = spider.y - 5
    IF spider.y < 0 THEN spider.y = spider.y + 5
END SUB


问:
Multiple datasources migrations using Flyway in a Spring Boot application
We use Flyway for db migration in our Spring Boot based app and now we have a requirement to introduce multi tenancy support while using multiple datasources strategy. As part of that we also need to support migration of multiple data sources. All data sources should maintain the same structure so same migration scripts should be used for migrating of all data sources. Also, migrations should occur upon application startup (as opposed to build time, whereas it seems that the maven plugin can be configured to migrate multiple data sources). What is the best approach to use in order to achieve this? The app already has data source beans defined but Flyway executes the migration only for the primary data source.</p>

答:
Found an easy solution for that - I added the step during the creation of my emf:

```<code>@Qualifier(EMF2)
@Bean(name = EMF2)
public LocalContainerEntityManagerFactoryBean entityManagerFactory2(
    final EntityManagerFactoryBuilder builder
) {
    final DataSource dataSource = dataSource2();
    Flyway.configure()
          .dataSource(dataSource)
          .locations("db/migration/ds2")
          .load()
          .migrate();
    return builder
        .dataSource(dataSource)
        .packages(Role.class)
        .properties(jpaProperties2().getProperties())
        .persistenceUnit("domain2")
        .build();
}
</code>```

I disabled spring.flyway.enabled for that.

SQL files live in resources/db/migration/ds1/... and resources/db/migration/ds2/...

Body:
Found an easy solution for that - I added the step during the creation of my emf:

@Qualifier(EMF2)
@Bean(name = EMF2)
public LocalContainerEntityManagerFactoryBean entityManagerFactory2(
    final EntityManagerFactoryBuilder builder
) {
    final DataSource dataSource = dataSource2();
    Flyway.configure()
          .dataSource(dataSource)
          .locations("db/migration/ds2")
          .load()
          .migrate();
    return builder
        .dataSource(dataSource)
        .packages(Role.class)
        .properties(jpaProperties2().getProperties())
        .persistenceUnit("domain2")
        .build();
}

I disabled spring.flyway.enabled for that.

SQL files live in resources/db/migration/ds1/... and resources/db/migration/ds2/...


问:
accessing sqlite file in android
I have a sqlite file. I want to use it in my application.
Can anyone share proper example as how I can do that.

I was not sure if .sqlite file can be used so I have also made .db file.

答:
I think you need this..
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/</p>

Title: accessing sqlite file in android


问:
Redux: Alternative way of clearing Object of Array
I have a state that could look like this:

```<code> [
  0: {
    "id": "8e9x23x2wto",
    "name": "test-player",
    "currentFrame": 1,
    "rolls": {
      "1": [1,3],
      "2": [1,6],
      "3": [1,6],
      "4": [3,8],
      "5": [4,5],
      "6": [7,6],
      "7": [8,1],
      "8": [5,2],
      "9": [2,1],
      "10": [1,1]
    },
    "totalWins": 0
  }
]
</code>```

I am clearing the rolls Object and resetting currentFrame like so:

```<code>case RESET_GAME:
  return {
    ...state,
    players: state.players.map((player) => {
      return {
        ...player,
        currentFrame: 1,
        rolls: Object.assign(player.rolls, Object.values(player.rolls).map(() => []))
      }
    }),
  }
</code>```

However, sometimes random Arrays within rolls don't get cleared - could be the second one, could be the last one...I have no idea way.

Is there any alternative way to clear rolls so that it only consists of empty Arrays or does someone have an explanation why that might happen?
Any input is much appreciated!

答:
I'm not 100% sure, but looking at this, I would wager that these problems are coming about due to mutations to the player.rolls object rather than creating a clean version of it.

Right now, your code with the objects is creating a new object and filling in that new object with keys/values from the old object. This maintains immutability of your objects rather than mutating the original object. React/Redux tends not to do well with mutable objects.

General examples

Mutable example:

const x = {};
Object.assign(x, {'a': 1, 'b': 2});
// x is now {'a': 1, 'b': 2}
```

<p>In this example, we took x, and we mutated it. Notice, it's a bit tricky here that we also used <code>const</code> with x, which just means that we cannot re-assign the "pointer" that x is, but we can still change the values that that pointer is pointing to. So saying</p>

<pre class="lang-js prettyprint-override"><code>const x = {};
x = 2; // Will not work
</code>```

Immutable example:

var x = {};
x = {...x, ...{'a': 1, 'b': 2}}; // assign x to a new object populated by the previous x and the new stuff
```

<p>In this case, we did not mutate our x object, but instead assigned x to a new object that was populated using the keys/values from our old x object and the new object key/values we wanted to have in there (though in this case it's unnecessary as x doesn't have any key/values within it initially).</p>

<h2>Your code</h2>

<pre class="lang-js prettyprint-override"><code>return { // not mutating
    ...state,
    players: state.players.map((player) => { // not mutating
      return { // not mutating
        ...player,
        currentFrame: 1,
        rolls: Object.assign( // mutating player.rolls rather than making a new rolls object.
          player.rolls,
          Object.values(player.rolls).map(() => [])
        )
      }
    }),
  }
</code>```

I'd recommend doing something like...

return {
    ...state,
    players: state.players.map((player) => {
      return {
        ...player,
        currentFrame: 1,
        rolls: []
      }
    }),
  }
```

<p>which is simpler, cleaner, and as you said, you're just clearing the whole <code>rolls</code> key anyways... unless I misunderstood?</p>

<p>See also Object.assign's MDN page where it states
<em>The target object — what to apply the sources’ properties to, which is returned <strong>after it is modified.</strong></em> (Bolding my own).</p>

<p>I can't think of many cases where you'd want to use Object.assign over the using the spread operator (the <code>{...{'a': 1}, ...{'b': 2}}</code> one).</p>

<h2>Edit</h2>

<p>Looking this over again, I realize you want to remake the 10 entries in the <code>rolls</code> object and not lose them entirely.</p>

<p>I think a better solution would be to just make a fresh object with empty entries in it. i.e.</p>

<pre class="lang-js prettyprint-override"><code>return {
    ...state,
    players: state.players.map((player) => {
      return {
        ...player,
        currentFrame: 1,
        rolls: {
           "1": [0,0],
           "2": [0,0],
           "3": [0,0],
           "4": [0,0],
           "5": [0,0],
           "6": [0,0],
           "7": [0,0],
           "8": [0,0],
           "9": [0,0],
           "10": [0,0]
        }
      }
    }),
  }
</code>```

I'm not sure why you use an object with numeric keys over a list, but yeah.

Body:
I have a state that could look like this:

 [
  0: {
    "id": "8e9x23x2wto",
    "name": "test-player",
    "currentFrame": 1,
    "rolls": {
      "1": [1,3],
      "2": [1,6],
      "3": [1,6],
      "4": [3,8],
      "5": [4,5],
      "6": [7,6],
      "7": [8,1],
      "8": [5,2],
      "9": [2,1],
      "10": [1,1]
    },
    "totalWins": 0
  }
]

I am clearing the rolls Object and resetting currentFrame like so:

case RESET_GAME:
  return {
    ...state,
    players: state.players.map((player) => {
      return {
        ...player,
        currentFrame: 1,
        rolls: Object.assign(player.rolls, Object.values(player.rolls).map(() => []))
      }
    }),
  }

However, sometimes random Arrays within rolls don't get cleared - could be the second one, could be the last one...I have no idea way.

Is there any alternative way to clear rolls so that it only consists of empty Arrays or does someone have an explanation why that might happen?
Any input is much appreciated!

Body:
I'm not 100% sure, but looking at this, I would wager that these problems are coming about due to mutations to the player.rolls object rather than creating a clean version of it.

Right now, your code with the objects is creating a new object and filling in that new object with keys/values from the old object. This maintains immutability of your objects rather than mutating the original object. React/Redux tends not to do well with mutable objects.

General examples

Mutable example:

const x = {};
Object.assign(x, {'a': 1, 'b': 2});
// x is now {'a': 1, 'b': 2}

In this example, we took x, and we mutated it. Notice, it's a bit tricky here that we also used const with x, which just means that we cannot re-assign the "pointer" that x is, but we can still change the values that that pointer is pointing to. So saying

const x = {};
x = 2; // Will not work

Immutable example:

var x = {};
x = {...x, ...{'a': 1, 'b': 2}}; // assign x to a new object populated by the previous x and the new stuff

In this case, we did not mutate our x object, but instead assigned x to a new object that was populated using the keys/values from our old x object and the new object key/values we wanted to have in there (though in this case it's unnecessary as x doesn't have any key/values within it initially).

Your code

return { // not mutating
    ...state,
    players: state.players.map((player) => { // not mutating
      return { // not mutating
        ...player,
        currentFrame: 1,
        rolls: Object.assign( // mutating player.rolls rather than making a new rolls object.
          player.rolls,
          Object.values(player.rolls).map(() => [])
        )
      }
    }),
  }

I'd recommend doing something like...

return {
    ...state,
    players: state.players.map((player) => {
      return {
        ...player,
        currentFrame: 1,
        rolls: []
      }
    }),
  }

which is simpler, cleaner, and as you said, you're just clearing the whole rolls key anyways... unless I misunderstood?

See also Object.assign's MDN page where it states
The target object — what to apply the sources’ properties to, which is returned after it is modified. (Bolding my own).

I can't think of many cases where you'd want to use Object.assign over the using the spread operator (the {...{'a': 1}, ...{'b': 2}} one).

Edit

Looking this over again, I realize you want to remake the 10 entries in the rolls object and not lose them entirely.

I think a better solution would be to just make a fresh object with empty entries in it. i.e.

return {
    ...state,
    players: state.players.map((player) => {
      return {
        ...player,
        currentFrame: 1,
        rolls: {
           "1": [0,0],
           "2": [0,0],
           "3": [0,0],
           "4": [0,0],
           "5": [0,0],
           "6": [0,0],
           "7": [0,0],
           "8": [0,0],
           "9": [0,0],
           "10": [0,0]
        }
      }
    }),
  }

I'm not sure why you use an object with numeric keys over a list, but yeah.


问:
Windows must now restart because the [our service name] service terminated unexpectedly
as a disclaimer, I am posting this here because I have only seen comments referring to this type of behavior where people have indicated a possible problem going on with the system.  If this is not the correct place to post this, please let me know and I will post where people ask coding questions.

Having said that, I have seen many posts that say "windows must now restart because the  service terminated unexpectedly".  My situation is different in that the complaint is regarding a proprietary service that my company wrote.

My company builds machines and currently one of them, running as a release build in the field, has had some service crashes.  The proprietary service is written for this machine and has been extensively tested.  It is running on Win7 32 bit, with Windows updates turned off.  The service is written in C++ using VS2010.

On 5/28/20, between 5:05 and 5:16 pm, we had 5 different crashes of this service.  Each time the system showed the error message "Windows must now restart because the [our service name] service terminated unexpectedly".  When I look at the crash dumps, each time it is sitting at a call to sprintf() where the call stack ends at _invoke_watson().  When I first open the crash dump the error dialog for the crash says "Unhandled exception ... : An invalid parameter was passed to a C runtime function."  When I look at the sprintf call, the associated lines are:

```<code>char buff[10];
if (sprintf_s(buff, sizeof(buff)/sizeof(buff[0]), "%04d%02d%02d", iyear, imonth, iday) < 0)
</code>```

These crashes are on the sprintf_s() call.  The iyear, imonth, iday are all ints, so they have to have value, but they are the values that were retrieved from a FILETIME struct (populated by a call to GetSystemTimeAsFileTime()) that was converted to a SYSTEMTIME struct (populated by a call to FileTimeToSystemTime()).  But either way, an int should be an int.

When I look in the system Event Viewer, for each crash it gives an exception code of 0xc0000417, and a system event ID of 1000 (which of course means crashed due to unknown event).

I am thrown by the fact that, other than during the span of these 13 minutes, this has never happened before and has not happened since.  I am trying to dig further into this issue, but I have no idea why a simple sprintf call would do this, and only during a span of 15 minutes.

Does anyone have any suggestions as to questions I should be "asking" of the system?  I am very adept with system work, but am not a system guy.  Any suggestions for me to continue forward would be highly appreciated.

Again, please let me know if this is the wrong place to be posting this question.

答:
You must be overrunning buff.  A format specifier such as %04d does not guarantee that the string placed in the buffer will be no longer than 4 characters, so if iyear somehow contains a value > 9999 then you will write more than the 4 characters you have allowed space for.  Similarly for imonth and iday.

So I would add some bounds checking on these values to ensure that you don't overrun your buffer.  You might also output them to some kind of debugging log if they are out of range (such as the Application Event Log) to help you track the problem down.

As for bringing down Windows when the service crashes, see: https://devblogs.microsoft.com/oldnewthing/20180216-00/?p=98035 (if you didn't know about that already).

OwnerDisplayName: bmahf

Body:
as a disclaimer, I am posting this here because I have only seen comments referring to this type of behavior where people have indicated a possible problem going on with the system.  If this is not the correct place to post this, please let me know and I will post where people ask coding questions.

Having said that, I have seen many posts that say "windows must now restart because the  service terminated unexpectedly".  My situation is different in that the complaint is regarding a proprietary service that my company wrote.

My company builds machines and currently one of them, running as a release build in the field, has had some service crashes.  The proprietary service is written for this machine and has been extensively tested.  It is running on Win7 32 bit, with Windows updates turned off.  The service is written in C++ using VS2010.

On 5/28/20, between 5:05 and 5:16 pm, we had 5 different crashes of this service.  Each time the system showed the error message "Windows must now restart because the [our service name] service terminated unexpectedly".  When I look at the crash dumps, each time it is sitting at a call to sprintf() where the call stack ends at _invoke_watson().  When I first open the crash dump the error dialog for the crash says "Unhandled exception ... : An invalid parameter was passed to a C runtime function."  When I look at the sprintf call, the associated lines are:

char buff[10];
if (sprintf_s(buff, sizeof(buff)/sizeof(buff[0]), "%04d%02d%02d", iyear, imonth, iday) < 0)

These crashes are on the sprintf_s() call.  The iyear, imonth, iday are all ints, so they have to have value, but they are the values that were retrieved from a FILETIME struct (populated by a call to GetSystemTimeAsFileTime()) that was converted to a SYSTEMTIME struct (populated by a call to FileTimeToSystemTime()).  But either way, an int should be an int.

When I look in the system Event Viewer, for each crash it gives an exception code of 0xc0000417, and a system event ID of 1000 (which of course means crashed due to unknown event).

I am thrown by the fact that, other than during the span of these 13 minutes, this has never happened before and has not happened since.  I am trying to dig further into this issue, but I have no idea why a simple sprintf call would do this, and only during a span of 15 minutes.

Does anyone have any suggestions as to questions I should be "asking" of the system?  I am very adept with system work, but am not a system guy.  Any suggestions for me to continue forward would be highly appreciated.

Again, please let me know if this is the wrong place to be posting this question.


问:
SwiftUI 2 View Models in a View
I have this view which takes as a param its own View Model. Inside this view I need to show another view which in order for it to be displayed, needs its own View Model. So I present the Purchase view and then inside the Purchase view I need to display the details of the actual item which was purchased. So I pass as a parameter also the ItemViewModel. Both PurchaseViewModel and ItemViewModel are used on other views also.

It could happen in the feature that I would also need ClientViewModel which would be used to display data about the actual buyer of this item. Does this mean that I would need to pass also @ObservedObject var clientViewModel: ClientViewModel as a parameter?

My question is: Is this approach good or there is a better way to do this ?

```<code>struct PurchaseView: View {
    @ObservedObject var purchaseViewModel: PurchaseViewModel
    @ObservedObject var itemViewModel: ItemViewModel

    var body: some View {
        VStack {
            Text(purchaseViewModel.title)
            ItemView(itemViewModel: itemViewModel)
        }
    }
}

class Purchase {
    let senderID: String
    let receiverID: String
    var status: PurchaseStatus
    var item: Item?
}
</code>```

答:
You should start by considering the relationship of the models, not the view models.

For example, you could make a case that a Purchase involves one or more items (Item) and a purchaser (Client).  In this case you would actually create a model something like:

```<code>class Purchase {
    var items = [Item]()
    var client: Client
    ...
}
</code>```

And your PurchaseViewModel would reflect this, containing the ItemViewModel and ClientViewModel

```<code>    let clientViewModel: ClientViewModel
    let itemsViewModels: [ItemViewModel]

    init(purchase: Purchase) {
        self.clientViewModel = ClientViewModel(client:purchase.client)
        self.itemsViewModels = purchase.items.map { ItemViewModel(item:$0) }
    }
</code>```

If you have a hierarchy of views that need some unrelated models then you can consider using the environment, especially for models that are "global"

For example, say that the user was looking at an item detail, but they were not yet making a purchase (So there is no Purchase yet) and you want to have a button that shows them their Client detail.

You could pass the ItemViewModel explicitly to the ItemDetailView:

```<code>struct ItemListView {
   ...

   Button(action: { ItemDetailView(item:someItemView) })
       { ... }

}

struct ItemDetailView {
    ...
    Button(action: { ClientView() }) {
        Text("Client detail")
    }
}

struct ClientDetailView {

   @EnvironmentObject client: ClientViewModel
   ...
}
</code>```

You can inject the ClientViewModel into the environment at a suitable point, such as the root view or even scene delegate.

If you have a hierarchy of views that need these models, but not all views need all models, you could use the environment to provide the various models rather than directly injecting them via initialiser parameters.

Title: SwiftUI 2 View Models in a View

Body:
I have this view which takes as a param its own View Model. Inside this view I need to show another view which in order for it to be displayed, needs its own View Model. So I present the Purchase view and then inside the Purchase view I need to display the details of the actual item which was purchased. So I pass as a parameter also the ItemViewModel. Both PurchaseViewModel and ItemViewModel are used on other views also.

It could happen in the feature that I would also need ClientViewModel which would be used to display data about the actual buyer of this item. Does this mean that I would need to pass also @ObservedObject var clientViewModel: ClientViewModel as a parameter?

My question is: Is this approach good or there is a better way to do this ?

struct PurchaseView: View {
    @ObservedObject var purchaseViewModel: PurchaseViewModel
    @ObservedObject var itemViewModel: ItemViewModel

    var body: some View {
        VStack {
            Text(purchaseViewModel.title)
            ItemView(itemViewModel: itemViewModel)
        }
    }
}

class Purchase {
    let senderID: String
    let receiverID: String
    var status: PurchaseStatus
    var item: Item?
}

Body:
You should start by considering the relationship of the models, not the view models.

For example, you could make a case that a Purchase involves one or more items (Item) and a purchaser (Client).  In this case you would actually create a model something like:

class Purchase {
    var items = [Item]()
    var client: Client
    ...
}

And your PurchaseViewModel would reflect this, containing the ItemViewModel and ClientViewModel

    let clientViewModel: ClientViewModel
    let itemsViewModels: [ItemViewModel]

    init(purchase: Purchase) {
        self.clientViewModel = ClientViewModel(client:purchase.client)
        self.itemsViewModels = purchase.items.map { ItemViewModel(item:$0) }
    }

If you have a hierarchy of views that need some unrelated models then you can consider using the environment, especially for models that are "global"

For example, say that the user was looking at an item detail, but they were not yet making a purchase (So there is no Purchase yet) and you want to have a button that shows them their Client detail.

You could pass the ItemViewModel explicitly to the ItemDetailView:

struct ItemListView {
   ...

   Button(action: { ItemDetailView(item:someItemView) })
       { ... }

}

struct ItemDetailView {
    ...
    Button(action: { ClientView() }) {
        Text("Client detail")
    }
}

struct ClientDetailView {

   @EnvironmentObject client: ClientViewModel
   ...
}

You can inject the ClientViewModel into the environment at a suitable point, such as the root view or even scene delegate.

If you have a hierarchy of views that need these models, but not all views need all models, you could use the environment to provide the various models rather than directly injecting them via initialiser parameters.


问:
in django template unable to show content inside if block
when i write if statement nothing show in html but when i remove the  if statement the code show all items what is wrong  </p>

```<code>  {% for catagory in catagory_list %}
      {% for item in product_list %}
           {% if item.catagory == "Fruits" %}
                <p>{{item.catagory}}</p>
                <p>{{item.name}}</p>
                <p>{{item.price}}</p>
                <img src="{{item.image.url}}" alt="">
           {% endif %}

        {% endfor %}
    {% endfor %}
</code>```

答:
Because catagory is an Object, Try:

```<code>{% if item.catagory.name == "Fruits" %}
</code>```

assuming that catagory model has an attribute "name"

Body:
when i write if statement nothing show in html but when i remove the  if statement the code show all items what is wrong

  {% for catagory in catagory_list %}
      {% for item in product_list %}
           {% if item.catagory == "Fruits" %}

{{item.catagory}}

{{item.name}}

{{item.price}}

           {% endif %}

        {% endfor %}
    {% endfor %}

Body:
Because catagory is an Object, Try:

{% if item.catagory.name == "Fruits" %}

assuming that catagory model has an attribute "name"


问:
C Programming: malloc() inside another function
I need help with malloc() inside another function.

I'm passing a pointer and size to the function from my main() and I would like to allocate memory for that pointer dynamically using malloc() from inside that called function, but what I see is that.... the memory, which is getting allocated, is for the pointer declared within my called function and not for the pointer which is inside the main().

How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?

I have written the following code and I get the output as shown below.

SOURCE:

```<code>int main()
{
   unsigned char *input_image;
   unsigned int bmp_image_size = 262144;

   if(alloc_pixels(input_image, bmp_image_size)==NULL)
     printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image));
   else
     printf("\nPoint3: Memory not allocated");
   return 0;
}

signed char alloc_pixels(unsigned char *ptr, unsigned int size)
{
    signed char status = NO_ERROR;
    ptr = NULL;

    ptr = (unsigned char*)malloc(size);

    if(ptr== NULL)
    {
        status = ERROR;
        free(ptr);
        printf("\nERROR: Memory allocation did not complete successfully!");
    }

    printf("\nPoint1: Memory allocated: %d bytes",_msize(ptr));

    return status;
}
</code>```

PROGRAM OUTPUT:

```<code>Point1: Memory allocated ptr: 262144 bytes
Point2: Memory allocated input_image: 0 bytes
</code>```

答:
As mentioned in the other answers, we need a pointer to the pointer. But why?

We need to pass the value by a pointer in order to be able to modify the value. If you want to modify an int, you need to pass it by the int*.

In this question, the value we want to modify is a pointer int* (pointer changed from NULL to the address of the allocated memory), so we need to pass a pointer to the pointer int**.

By doing followed, pInt inside foo(int*) is a copy of the argument. When we allocate memory to the local variable, the one in the main() is intact.

```<code>void foo(int* pInt)
{
   pInt = malloc(...);
}
int main()
{
   int* pInt;
   foo(pInt);
   return 0;
}
</code>```

So we need a pointer to pointer,

```<code>void foo(int** pInt)
{
   *pInt = malloc(...);
}
int main()
{
   int* pInt;
   foo(&pInt);
   return 0;
}
</code>```

Body:
I need help with malloc() inside another function.

I'm passing a pointer and size to the function from my main() and I would like to allocate memory for that pointer dynamically using malloc() from inside that called function, but what I see is that.... the memory, which is getting allocated, is for the pointer declared within my called function and not for the pointer which is inside the main().

How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?

I have written the following code and I get the output as shown below.

SOURCE:

int main()
{
   unsigned char *input_image;
   unsigned int bmp_image_size = 262144;

   if(alloc_pixels(input_image, bmp_image_size)==NULL)
     printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image));
   else
     printf("\nPoint3: Memory not allocated");
   return 0;
}

signed char alloc_pixels(unsigned char *ptr, unsigned int size)
{
    signed char status = NO_ERROR;
    ptr = NULL;

    ptr = (unsigned char*)malloc(size);

    if(ptr== NULL)
    {
        status = ERROR;
        free(ptr);
        printf("\nERROR: Memory allocation did not complete successfully!");
    }

    printf("\nPoint1: Memory allocated: %d bytes",_msize(ptr));

    return status;
}

PROGRAM OUTPUT:

Point1: Memory allocated ptr: 262144 bytes
Point2: Memory allocated input_image: 0 bytes

Body:
As mentioned in the other answers, we need a pointer to the pointer. But why?

We need to pass the value by a pointer in order to be able to modify the value. If you want to modify an int, you need to pass it by the int*.

In this question, the value we want to modify is a pointer int* (pointer changed from NULL to the address of the allocated memory), so we need to pass a pointer to the pointer int**.

By doing followed, pInt inside foo(int*) is a copy of the argument. When we allocate memory to the local variable, the one in the main() is intact.

void foo(int* pInt)
{
   pInt = malloc(...);
}
int main()
{
   int* pInt;
   foo(pInt);
   return 0;
}

So we need a pointer to pointer,

void foo(int** pInt)
{
   *pInt = malloc(...);
}
int main()
{
   int* pInt;
   foo(&pInt);
   return 0;
}


问:
Is getBean() supposed to delay bean instantiation?
I would expect getBean() to immediately call the configuration's @Bean method and create a new instance of the bean with SCOPE_PROTOTYPE. However, this doesn't seem to occur until a bean's method is invoked. Why is the loading delayed? What can be done to make the instance created immediately?</p>

```<code>@Configuration
public class ViewModelConfig {
  @Autowired MyService service;

  @Bean
  @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
  public MyModel getModel() {
    return new MyModel(service);
  }
}

@Route
public class MyView extends FormLayout {
  @Autowired private ApplicationContext context;
  private MyModel model;

  @PostConstruct
  private void init() {
    model = context.getBean(IntegrationViewModel.class); // Bean is retrieved but ViewModelConfig.getModel() not called and new instance from MyModel(MyService) not created yet
    MyTreeGrid grid = new MyTreeGrid(model);
    this.add(grid);
  }
}

public class MyTreeGrid extends TreeGrid<MyTreeGridItem> {
    private static final long serialVersionUID = -3198476593716788388L;
    private MyModel model;

    public MyTreeGrid(MyModel model){
        this.model = model;
        this.setItems(model.getItems()); // Before invoking model.getItems(), ViewModelConfig.getModel() is invoked, however the previous assignment of this.model is not updated with the new instance. Why is the loading delayed?

        this.addItemClickListener(
          new ComponentEventListener<ItemClickEvent<MyTreeGridItem>>() {
            private static final long serialVersionUID = 8287268114264478411L;

            @Override
            public void onComponentEvent(ItemClickEvent<MyTreeGridItem> event) {
              // event.getItem() never returns null
             IntegrationTreeGrid.this.model.setSelectedItem(event.getItem()); // DOES NOT WORK!?! Appears to set the value when stepping through the function call, but after exiting the function call IntegrationTreeGrid.this.model.selectedItem remains null
            }
        });
  }
}

public class MyModel {

  private MyTreeGridItem selectedItem = null;

  public void setSelectedItem(MyTreeGridItem item) {
    this.selectedItem = item;
  }
}
</code>```

答:
The lazy init is because of proxyMode = ScopedProxyMode.TARGET_CLASS, which ends up with a proxy that holds a reference to the original bean definition and creates/reuses the actual target based on the context.

Since your bean has scope "prototype", this means you'll get a new instance every time you invoke a method on that proxy, which is most likely not what you want. Anything you do to that instance "gets lost", as a new one will be created on every method invocation (which explains what you saw). To test this, set a breakpoint in the MyModel constructor.

Scoped proxies make most sense in web contexts where you want to bind some component to the request or session but use/inject it as if it was a singleton.

Body:
I would expect getBean() to immediately call the configuration's @Bean method and create a new instance of the bean with SCOPE_PROTOTYPE. However, this doesn't seem to occur until a bean's method is invoked. Why is the loading delayed? What can be done to make the instance created immediately?

@Configuration
public class ViewModelConfig {
  @Autowired MyService service;

  @Bean
  @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
  public MyModel getModel() {
    return new MyModel(service);
  }
}

@Route
public class MyView extends FormLayout {
  @Autowired private ApplicationContext context;
  private MyModel model;

  @PostConstruct
  private void init() {
    model = context.getBean(IntegrationViewModel.class); // Bean is retrieved but ViewModelConfig.getModel() not called and new instance from MyModel(MyService) not created yet
    MyTreeGrid grid = new MyTreeGrid(model);
    this.add(grid);
  }
}

public class MyTreeGrid extends TreeGrid<MyTreeGridItem> {
    private static final long serialVersionUID = -3198476593716788388L;
    private MyModel model;

    public MyTreeGrid(MyModel model){
        this.model = model;
        this.setItems(model.getItems()); // Before invoking model.getItems(), ViewModelConfig.getModel() is invoked, however the previous assignment of this.model is not updated with the new instance. Why is the loading delayed?

        this.addItemClickListener(
          new ComponentEventListener<ItemClickEvent<MyTreeGridItem>>() {
            private static final long serialVersionUID = 8287268114264478411L;

            @Override
            public void onComponentEvent(ItemClickEvent<MyTreeGridItem> event) {
              // event.getItem() never returns null
             IntegrationTreeGrid.this.model.setSelectedItem(event.getItem()); // DOES NOT WORK!?! Appears to set the value when stepping through the function call, but after exiting the function call IntegrationTreeGrid.this.model.selectedItem remains null
            }
        });
  }
}

public class MyModel {

  private MyTreeGridItem selectedItem = null;

  public void setSelectedItem(MyTreeGridItem item) {
    this.selectedItem = item;
  }
}


问:
How do I combine multiple SQL rows into one in a select query?
Let's say I have data like so:

```<code>PersonID    Goal
--------    ----
1           one
1           two
1           three
2           alpha
2           beta

PersonID    Note
--------    ----
1           hello
1           world
2           i
2           like
2           squirrels
</code>```

And I want to put all the goals and notes for each person into a single row:

```<code>PersonID    Goal 1  Goal 2  Goal 3  Note 1  Note 2  Note 3
--------    ------  ------  ------  ------  ------  ------
1           one     two     three   hello   world
2           alpha   beta            i       like    squirrels
</code>```

With the maximum goal and note numbers computed to be equal to the maximum count of goals and notes belonging to any one person - so if I add a third person who has five goals then two more goal columns will be added, for instance.

Is there any way to write a SQL query that combines the rows in this fashion? Or do I have to do that sort of data manipulation in the application itself (as I am currently), which is slower?

edit: I'm using SQL Server and it would be OK to instead have a delimited list, e.g.

```<code>PersonID    Goals           Notes
--------    ------          ------
1           one|two|three   hello|world
2           alpha|beta      i|like|squirrels
</code>```

答:
It's impossible to return an unknown amount of columns in sql.

What you CAN do is use is GROUP_CONCAT if you use mysql (other databases have other solutions)
https://www.geeksforgeeks.org/mysql-group_concat-function/
You will end up with data like this.

```<code>PersonID    Goal            Note
--------    --------------  ------------------
1           one,two,three   hello,world
2           alpha,beta      i,like,squirrels
</code>```

Body:
Let's say I have data like so:

PersonID    Goal
--------    ----
1           one
1           two
1           three
2           alpha
2           beta

PersonID    Note
--------    ----
1           hello
1           world
2           i
2           like
2           squirrels

And I want to put all the goals and notes for each person into a single row:

PersonID    Goal 1  Goal 2  Goal 3  Note 1  Note 2  Note 3
--------    ------  ------  ------  ------  ------  ------
1           one     two     three   hello   world
2           alpha   beta            i       like    squirrels

With the maximum goal and note numbers computed to be equal to the maximum count of goals and notes belonging to any one person - so if I add a third person who has five goals then two more goal columns will be added, for instance.

Is there any way to write a SQL query that combines the rows in this fashion? Or do I have to do that sort of data manipulation in the application itself (as I am currently), which is slower?

edit: I'm using SQL Server and it would be OK to instead have a delimited list, e.g.

PersonID    Goals           Notes
--------    ------          ------
1           one|two|three   hello|world
2           alpha|beta      i|like|squirrels

Body:
It's impossible to return an unknown amount of columns in sql.

What you CAN do is use is GROUP_CONCAT if you use mysql (other databases have other solutions)
https://www.geeksforgeeks.org/mysql-group_concat-function/
You will end up with data like this.

PersonID    Goal            Note
--------    --------------  ------------------
1           one,two,three   hello,world
2           alpha,beta      i,like,squirrels


问:
Visual Paradigm: Invalid Syntax Highlighting without acutal syntax mistake (as far as I can see)
I think I have encountered an error message that is not necessarily valid or helpful. If it is valid, please tell me what the mistake I encounter is triggered by.

答:
You do not follows UML notation and you exchanged the parameter and its type, your operations must be

create(entity : E) : Result<E>

create(entities : iterable<E>) : ResultCollection<E>

Your create(E : entity) : Result<E> was accepted 'syntactically' because the var can be E and its type entity, but in the second case the var name iterable<E> is illegal and the tool refuses that.

From formal/2017-12-05 §9.6.4 page 117 and 118 :

If shown in a diagram, an Operation is shown as a text string of the form:

[<visibility>] <name> ‘(‘ [<parameter-list>] ‘)’

        [‘:’ [<return-type>] [‘[‘ <multiplicity-range> ‘]’]

        [‘{‘ <oper-property> [‘,’ <oper-property>]* ‘}’]]

and <parameter-list> is a list of Parameters of the Operation in the following format:

<parameter-list> ::= <parameter> [‘,’<parameter>]*

and § 9.4.4 page 110 :

<parameter> ::= [<direction>] <parameter-name> ’:’ <type-expression>

       [’[’<multiplicity-range>’]’] [’=’ <default>]

       [’{’ <parm-property> [’,’ <parm-property>]* ’}’]

So it must be <parameter-name> ’:’ <type-expression> rather than <type-expression> ’:’ <parameter-name> as you did


问:
How do I convert HTML to XHTML using JavaScript?
I need to add slashes to the end of all the image tags in a string. I'm using JavaScript regular expressions. Here is what I have so far:

strInput = strInput.replace(//gm, "");

But I'm not sure what to replace it with? I'm taking the value of a text area and parsing it as XML, but the image tags generate errors because they're HTML. Thanks.

答:
you should let the browser do the 'heavy lifting'; obviously, the browser can parse HTML - after all, how else should it show us web pages? You can use JavaScript to make the browser parse HTML for you by setting .innerHTML of some dom node to your HTML string, or by using .insertAdjacentHTML. Then you have transformed your HTML string to a tree of DOM nodes, i.e., you have it parsed.

And there are browser builtin ways to turn your DOM tree into an XHTML string. You simply create an XHTML document programmatically, then you add any DOM tree to it (which can come from an HTML (non-XHTML) document, that is perfectly fine) with .appendChild, and then the .outerHTML and .innerHTML methods of your DOM tree (which now have an XHTML document as owner document) will give XHTML.

If you're starting with a DOM node, you can use the following 2 functions:

```<code>var nsx = "http://www.w3.org/1999/xhtml";
function outerXHTML(node){
    var xdoc = document.implementation.createDocument(nsx, 'html');
    xdoc.documentElement.appendChild(node);
    return node.outerHTML;
}
function innerXHTML(node){
    var xdoc = document.implementation.createDocument(nsx, 'html');
    xdoc.documentElement.appendChild(node);
    return node.innerHTML;
}
</code>```

(note that the node will be owned by the newly created XHTML document, so it will vanish from your original document. If it should remain there, then clone it before calling one of the above functions.)

And if you're starting with a string, we'll just have to set innerHTML of a newly created node before calling the above. For you convenience, here is a snippet. With 3 examples. 2 for html to xhtml, and one for xhtml to html.

function html2xhtml(html){
    var nsx = "http://www.w3.org/1999/xhtml";
    var body = document.createElement('body');
    body.innerHTML = html;
    var xdoc = document.implementation.createDocument(nsx, 'html');
    xdoc.documentElement.appendChild(body);
    return body.innerHTML;
}
function xhtml2html(xhtml){
    var body = document.createElement('body');
    body.innerHTML = xhtml;
    var doc = document.implementation.createHTMLDocument();
    doc.documentElement.appendChild(body);
    return body.innerHTML;
}
var html1 = '
loremipsumdolor sit amet

';
var html2 = '

<svg><rect width="100" height="100"></rect></svg>

';
var html3x = '';
var node1  = document.getElementById('node1');
var node1x = document.getElementById('node1x');
var node2  = document.getElementById('node2');
var node2x = document.getElementById('node2x');
var node3  = document.getElementById('node3');
var node3x = document.getElementById('node3x');
node1.textContent = html1;
node2.textContent = html2;
node3x.textContent = html3x;

node1x.textContent = html2xhtml(html1);
node2x.textContent = html2xhtml(html2);
node3.textContent = xhtml2html(html3x);```
<pre class="snippet-code-html lang-html prettyprint-override"><code>html<br><pre id='node1'>```xhtml

```<hr>
html<br><pre id='node2'>```xhtml

```<hr><hr>
xhtml<br><pre id='node3x'>```html

```</code>```

code older version

you can also do it with XMLSerializer (for the toString part not the fromString part), credit @Kaiido.

Body:
you should let the browser do the 'heavy lifting'; obviously, the browser can parse HTML - after all, how else should it show us web pages? You can use JavaScript to make the browser parse HTML for you by setting .innerHTML of some dom node to your HTML string, or by using .insertAdjacentHTML. Then you have transformed your HTML string to a tree of DOM nodes, i.e., you have it parsed.

And there are browser builtin ways to turn your DOM tree into an XHTML string. You simply create an XHTML document programmatically, then you add any DOM tree to it (which can come from an HTML (non-XHTML) document, that is perfectly fine) with .appendChild, and then the .outerHTML and .innerHTML methods of your DOM tree (which now have an XHTML document as owner document) will give XHTML.

If you're starting with a DOM node, you can use the following 2 functions:

var nsx = "http://www.w3.org/1999/xhtml";
function outerXHTML(node){
    var xdoc = document.implementation.createDocument(nsx, 'html');
    xdoc.documentElement.appendChild(node);
    return node.outerHTML;
}
function innerXHTML(node){
    var xdoc = document.implementation.createDocument(nsx, 'html');
    xdoc.documentElement.appendChild(node);
    return node.innerHTML;
}

(note that the node will be owned by the newly created XHTML document, so it will vanish from your original document. If it should remain there, then clone it before calling one of the above functions.)

And if you're starting with a string, we'll just have to set innerHTML of a newly created node before calling the above. For you convenience, here is a snippet. With 3 examples. 2 for html to xhtml, and one for xhtml to html.

function html2xhtml(html){
    var nsx = "http://www.w3.org/1999/xhtml";
    var body = document.createElement('body');
    body.innerHTML = html;
    var xdoc = document.implementation.createDocument(nsx, 'html');
    xdoc.documentElement.appendChild(body);
    return body.innerHTML;
}
function xhtml2html(xhtml){
    var body = document.createElement('body');
    body.innerHTML = xhtml;
    var doc = document.implementation.createHTMLDocument();
    doc.documentElement.appendChild(body);
    return body.innerHTML;
}
var html1 = '<div>lorem<img>ipsum<img>dolor sit amet<br></div>';
var html2 = '<ul><li><svg><rect width="100" height="100"></rect></svg></li></ul>';
var html3x = '<img />';
var node1  = document.getElementById('node1');
var node1x = document.getElementById('node1x');
var node2  = document.getElementById('node2');
var node2x = document.getElementById('node2x');
var node3  = document.getElementById('node3');
var node3x = document.getElementById('node3x');
node1.textContent = html1;
node2.textContent = html2;
node3x.textContent = html3x;

node1x.textContent = html2xhtml(html1);
node2x.textContent = html2xhtml(html2);
node3.textContent = xhtml2html(html3x);

html<br><pre id='node1'></pre>xhtml<br><pre id='node1x'></pre><hr>
html<br><pre id='node2'></pre>xhtml<br><pre id='node2x'></pre><hr><hr>
xhtml<br><pre id='node3x'></pre>html<br><pre id='node3'></pre>

code older version

you can also do it with XMLSerializer (for the toString part not the fromString part), credit @Kaiido.


问:
How do I generate a single bundle when I'm generating two binaries? For archiving
When I try to archive the mac application we wrote, instead of getting a Mac App Archive I'm getting a Generic Xcode Archive:

I wast told it might be the case because we generate two bundles. One is a screensaver, Ninja.saver, and one is an app, Screensaver Ninja.app. Ninja.saver is copied to Screensaver Ninja.app's resources. These are the contents of that archive:

To try to figure it out, I removed Ninja.saver from my main app, so it's not built at all and lo and behold, now the archiver seems to work:

As an alternative I wrote a script that would remove the Ninja.saver just after copying it, that was not good enough.

How do I make the archiver work under this situation?

答: For the 2nd binary, make sure it's Build Settings, has Skip Install set to Yes.


问:
Vanilla JS - How To Stop Sub-Element's OnClick Method From Calling Parent Elements OnClick Method
Having to use VanillaJS (don't ask me why).

Struggling to wrap my head around this simple thing.

Here is my code:

```<code><script>
function chooseImage() {
  alert("chooseImage");
}

function deleteImage() {
  alert("deleteImage");
}
</script>

<style>
body {
  background: black;
}
</style>

<div class="mod-c-tab-col">
    <div class="mod-c-tab-img del-option" onclick="chooseImage()">
        <input type="radio" id="img-1" name="images" checked="">
        <label for="img-1"></label>
        <img src="https://public-assets.envato-static.com/assets/logos/envato_market-a5ace93f8482e885ae008eb481b9451d379599dfed24868e52b6b2d66f5cf633.svg" alt="">
        <button class="mod-del-btn" onclick="deleteImage()">>Delete</button>
    </div><!-- /.mod-c-tab-img -->
</div>
</code>```

And view it on a codepen here: https://codepen.io/jacksonjack/pen/MWKgQQK

Now two things should happen:

user should click image and it should popup with an alert "chooseImage".

This works as expected.

However the second thing does not work as expected.

user should click image and it should popup with an alert "deleteImage".

However it shows "deleteImage" then the "chooseImage".

How do I stop this?

答:
Like I already wrote in my comment, you may use stopPropagation() to stop the bubbling of events.

However, in this case it would suffice to just put the click event from the div to the img, which brings both events to separate siblings.

function chooseImage() {
  alert("chooseImage");
}

function deleteImage() {
  alert("deleteImage");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: black;
}</code>```

        <input type="radio" id="img-1" name="images" checked="">

        <button class="mod-del-btn" onclick="deleteImage()">>Delete</button>

```

Body:
Having to use VanillaJS (don't ask me why).

Struggling to wrap my head around this simple thing.

Here is my code:

        <input type="radio" id="img-1" name="images" checked="">

        <button class="mod-del-btn" onclick="deleteImage()">>Delete</button>

And view it on a codepen here: https://codepen.io/jacksonjack/pen/MWKgQQK

Now two things should happen:

user should click image and it should popup with an alert "chooseImage".

This works as expected.

However the second thing does not work as expected.

user should click image and it should popup with an alert "deleteImage".

However it shows "deleteImage" then the "chooseImage".

How do I stop this?

Body:
Like I already wrote in my comment, you may use stopPropagation() to stop the bubbling of events.

However, in this case it would suffice to just put the click event from the div to the img, which brings both events to separate siblings.

function chooseImage() {
  alert("chooseImage");
}

function deleteImage() {
  alert("deleteImage");
}

body {
  background: black;
}

<div class="mod-c-tab-col">
    <div class="mod-c-tab-img del-option">
        <input type="radio" id="img-1" name="images" checked="">
        <label for="img-1"></label>
        <img src="https://public-assets.envato-static.com/assets/logos/envato_market-a5ace93f8482e885ae008eb481b9451d379599dfed24868e52b6b2d66f5cf633.svg" alt="" onclick="chooseImage()">
        <button class="mod-del-btn" onclick="deleteImage()">>Delete</button>
    </div><!-- /.mod-c-tab-img -->
</div>


问:
Virtual overloaded operators >> and <<
I need an interface that would require its subclasses to overload << and >>, but I'm not quite sure how since these operators aren't overloaded as member functions:

```<code>std::istream& operator>> (std::istream& in, Student& student) {
    in >> student.name >> student.group;
    for (int& i : student.marks) { in >> i; }
    return in;
}
</code>```

Maybe there's a way to make it a member function?

答:
You could do something like this:

class StudentInterface
{
public:
    virtual void readSelfFrom(std::istream& in) = 0;
};

std::istream& operator>> (std::istream& in, StudentInteface& student)
{
    student.readSelfFrom(in);
    return in;
}
```

<p>And then let users derive from <code>StudentInterface</code>, eg:</p>

<pre class="lang-cpp prettyprint-override"><code>class Student: public StudentInterface
{
public:
    void readSelfFrom(std::istream& in) override
    {
        in >> name >> group;
        for (int& i : marks) { in >> i; }
    }
};
</code>```

Title: Virtual overloaded operators >> and <<

Body:
I need an interface that would require its subclasses to overload << and >>, but I'm not quite sure how since these operators aren't overloaded as member functions:

std::istream& operator>> (std::istream& in, Student& student) {
    in >> student.name >> student.group;
    for (int& i : student.marks) { in >> i; }
    return in;
}

Maybe there's a way to make it a member function?

Body:
You could do something like this:

class StudentInterface
{
public:
    virtual void readSelfFrom(std::istream& in) = 0;
};

std::istream& operator>> (std::istream& in, StudentInteface& student)
{
    student.readSelfFrom(in);
    return in;
}

And then let users derive from StudentInterface, eg:

class Student: public StudentInterface
{
public:
    void readSelfFrom(std::istream& in) override
    {
        in >> name >> group;
        for (int& i : marks) { in >> i; }
    }
};


问:
Disable or properly install git LFS per remote
I have a git repository with two remotes configured.

One of those remotes is a local bare git repository, accessed over ssh (its url is ssh://username@host:/home/username/repo.git) and it does not support git LFS.

Is it possible to disable LFS for that remote and make git push send original content of tracked files, instead of pointers?

I've followed advises from these articles, but they don't help:

Disable Git LFS for a remote

https://github.com/git-lfs/git-lfs/issues/3665#issuecomment-496549743

Command git push succeeds, but I've got pointer files instead of original content:

```<code>$ head ./src/LARGE-file.bin
version https://git-lfs.github.com/spec/v1
oid sha256:e4790eb8aeb78cc79ace0f3d9719875d95091fe97969302d6816f64b9f0f8850
size 1430976
</code>```

To summarize, my goal is to enable git LFS for one remote and disable it for another.

Alternatively, it is also possible to configure LFS for that pure ssh remote, and I'd appreciate recommendations on how to do that.

答:
The issue here is that what's actually in Git is the content-pointer files.

If you disable LFS for a remote, what you are really doing is saying when I send to the given remote, I don't want to send the real files to the LFS server, I just want to send the content pointers to the Git server.

To send the real files as part of a commit, they must actually be part of the commit.  Remember that git push operates on commits, not files.  Git-LFS operates on individual files whose content-pointers are stored in the underlying Git repository.

If you make commits that contain the actual files instead of content pointers, and send those commits instead of the commits that contain only content pointers, that would work; but note that this is a different / independent history that cannot easily be reconciled with the LFS-pointer-based history.  There is probably no support built in to Git-LFS itself for this, as it would be kind of a nightmare to handle well.

Body:
I have a git repository with two remotes configured.

One of those remotes is a local bare git repository, accessed over ssh (its url is ssh://username@host:/home/username/repo.git) and it does not support git LFS.

Is it possible to disable LFS for that remote and make git push send original content of tracked files, instead of pointers?

I've followed advises from these articles, but they don't help:

Disable Git LFS for a remote

https://github.com/git-lfs/git-lfs/issues/3665#issuecomment-496549743

Command git push succeeds, but I've got pointer files instead of original content:

$ head ./src/LARGE-file.bin
version https://git-lfs.github.com/spec/v1
oid sha256:e4790eb8aeb78cc79ace0f3d9719875d95091fe97969302d6816f64b9f0f8850
size 1430976

To summarize, my goal is to enable git LFS for one remote and disable it for another.

Alternatively, it is also possible to configure LFS for that pure ssh remote, and I'd appreciate recommendations on how to do that.


问:
Running a Flask app within a Docker container results in "./boot.sh: 2: exec: gunicorn: not found"
I am trying to create a Flask app running within a Docker container but I have some complex dependencies so I am building from this image https://hub.docker.com/r/continuumio/anaconda/.

I build the image (goes fine... environment works...):

```<code>docker build -t my_image:latest .
</code>```

Then try to run it

```<code>docker run --name my_image -p 80:5000 --rm my_image:latest
</code>```

I get this error:

```<code>./boot.sh: 2: exec: gunicorn: not found
</code>```

Here is my directory I am building from:

```<code>my_template
--api.py
--boot.sh
--environment.yml
--Dockerfile
</code>```

I have a very simple flask app.
api.py

from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/', methods=['GET'])
def hello_world():
    return jsonify({'message': 'Hello World'})

@app.route('/test', methods=['GET'])
def test():
    return jsonify({'test': 'test'})

if __name__ == "__main__":
    app.run(debug=True) # remember to set debug to False
```

<p><code>environment.yml</code> is as follows:</p>

```name: ox
channels:
  - conda-forge
  - defaults
dependencies:
  {---OMITTED FOR BREVITY---}
prefix: /home/me/anaconda3/envs/ox
```

<p><code>Dockerfile</code> is as follows: </p>

```FROM continuumio/miniconda:latest

WORKDIR /home/conda_flask_docker

COPY environment.yml ./
COPY api.py ./
COPY boot.sh ./

RUN chmod +x boot.sh

RUN conda env create -f environment.yml

RUN echo "source activate ox" > ~/.bashrc
ENV PATH /opt/conda/envs/ox/bin:$PATH

EXPOSE 5000

ENTRYPOINT ["./boot.sh"]
```

<p>And... <code>boot.sh</code> </p>

```#!/bin/sh
exec gunicorn -b :5000 --access-logfile - --error-logfile - api:app
```

答:
Solved this on my own...

I needed to add

```<code> - flask=1.1.2=pyh9f0ad1d_0
 - gunicorn=20.0.4=py38h32f6830_1
</code>```

to the dependencies section of environment.yml. I had used conda env export > environment.yml to build my environment.yml BEFORE I had added Flask and gunicorn.

If that doesn't do it, adding gunicorn via RUN command in the Dockerfile should do.

Body:
I am trying to create a Flask app running within a Docker container but I have some complex dependencies so I am building from this image https://hub.docker.com/r/continuumio/anaconda/.

I build the image (goes fine... environment works...):

docker build -t my_image:latest .

Then try to run it

docker run --name my_image -p 80:5000 --rm my_image:latest

I get this error:

./boot.sh: 2: exec: gunicorn: not found

Here is my directory I am building from:

my_template
--api.py
--boot.sh
--environment.yml
--Dockerfile

I have a very simple flask app.
api.py

from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/', methods=['GET'])
def hello_world():
    return jsonify({'message': 'Hello World'})

@app.route('/test', methods=['GET'])
def test():
    return jsonify({'test': 'test'})

if __name__ == "__main__":
    app.run(debug=True) # remember to set debug to False

environment.yml is as follows:

name: ox
channels:
  - conda-forge
  - defaults
dependencies:
  {---OMITTED FOR BREVITY---}
prefix: /home/me/anaconda3/envs/ox

Dockerfile is as follows:

FROM continuumio/miniconda:latest

WORKDIR /home/conda_flask_docker

COPY environment.yml ./
COPY api.py ./
COPY boot.sh ./

RUN chmod +x boot.sh

RUN conda env create -f environment.yml

RUN echo "source activate ox" > ~/.bashrc
ENV PATH /opt/conda/envs/ox/bin:$PATH

EXPOSE 5000

ENTRYPOINT ["./boot.sh"]

And... boot.sh

#!/bin/sh
exec gunicorn -b :5000 --access-logfile - --error-logfile - api:app

Body:
Solved this on my own...

I needed to add

 - flask=1.1.2=pyh9f0ad1d_0
 - gunicorn=20.0.4=py38h32f6830_1

to the dependencies section of environment.yml. I had used conda env export > environment.yml to build my environment.yml BEFORE I had added Flask and gunicorn.

If that doesn't do it, adding gunicorn via RUN command in the Dockerfile should do.


问:
Xcode 11.5 giving "could not execute support code to read Objective-C class data"
I just updated to 11.5 and now my existing Swift program (no Objective-C, never had it) is giving this message.  To those who actually solved this problem: What is the solution? I will try reinstalling 11.5. Thanks!</p>

答: Matt, I reinstalled and deleted Derived Data and it works again.  Just a glitch. Thanks for the tip!</p>


问:
Getting "Insufficient Permission" error while storing data into GCS from docker container in kubernetes engine
I have configured gcloud with the project, service account and other configurations. Enabled google api and runs the application on GKE clusters.

I am getting the following error logs,

```<code>Exception in thread "Thread-10" com.google.cloud.storage.StorageException: Insufficient Permission
    at com.google.cloud.storage.spi.v1.HttpStorageRpc.translate(HttpStorageRpc.java:227)
    at com.google.cloud.storage.spi.v1.HttpStorageRpc.create(HttpStorageRpc.java:308)
    at com.google.cloud.storage.StorageImpl$3.call(StorageImpl.java:203)
    at com.google.cloud.storage.StorageImpl$3.call(StorageImpl.java:200)
    at com.google.api.gax.retrying.DirectRetryingExecutor.submit(DirectRetryingExecutor.java:105)
    at com.google.cloud.RetryHelper.run(RetryHelper.java:76)
    at com.google.cloud.RetryHelper.runWithRetries(RetryHelper.java:50)
    at com.google.cloud.storage.StorageImpl.internalCreate(StorageImpl.java:199)
    at com.google.cloud.storage.StorageImpl.create(StorageImpl.java:161)
    at java.lang.Thread.run(Thread.java:748)
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
POST https://storage.googleapis.com/upload/storage/v1/b/my-bucket/o?projection=full&uploadType=multipart
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Insufficient Permission",
    "reason" : "insufficientPermissions"
  } ],
  "message" : "Insufficient Permission"
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:150)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:555)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:475)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:592)
    at com.google.cloud.storage.spi.v1.HttpStorageRpc.create(HttpStorageRpc.java:305)
    ... 12 more
</code>```

答:
this is not an rbac related error. You just don't have access to GCS.
  May be scopes? Go to any node, and check if your nodes have GCS scope.
  – suren May 15 at 18:20

It looks like @suren is right and most probably it is the issue related to GCS scopes as the 403 error can be related with authorization problems. You can check the scopes set for particular Compute Engine VM by running on it:

```<code>curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/?recursive=true" -H "Metadata-Flavor: Google"
</code>```

It will retrieve this information from metadata server.
You will probably see only storage-ro scope when it comes to GCS as it is the default setting:

```<code>"scopes":["https://www.googleapis.com/auth/devstorage.read_only"
</code>```

and as you can see here, you will need to set:

```<code>storage-rw  https://www.googleapis.com/auth/devstorage.read_write
</code>```

which on Compute Engine instances can be done as follows:

```<code>$ gcloud beta compute instances set-scopes example-instance \
      --scopes=storage-rw --zone=us-central1-b \
      --service-account=example-account
</code>```

It requires however shutting down the instance to be able to apply changes to service-account. Otherwise you'll get the following error message:

```<code>ERROR: (gcloud.beta.compute.instances.set-scopes) Could not fetch resource:
 - The instance must be stopped before the service account can be changed.
</code>```

But when using GKE you cannot simply stop individual worker node as it is part of a managed instance group.

However you can set scopes when creating new GKE cluster e.g. like this:

```<code>gcloud container clusters create test --scopes=storage-rw --service-account default --zone europe-west3-c
</code>```

Body:
I have configured gcloud with the project, service account and other configurations. Enabled google api and runs the application on GKE clusters.

I am getting the following error logs,

Exception in thread "Thread-10" com.google.cloud.storage.StorageException: Insufficient Permission
    at com.google.cloud.storage.spi.v1.HttpStorageRpc.translate(HttpStorageRpc.java:227)
    at com.google.cloud.storage.spi.v1.HttpStorageRpc.create(HttpStorageRpc.java:308)
    at com.google.cloud.storage.StorageImpl$3.call(StorageImpl.java:203)
    at com.google.cloud.storage.StorageImpl$3.call(StorageImpl.java:200)
    at com.google.api.gax.retrying.DirectRetryingExecutor.submit(DirectRetryingExecutor.java:105)
    at com.google.cloud.RetryHelper.run(RetryHelper.java:76)
    at com.google.cloud.RetryHelper.runWithRetries(RetryHelper.java:50)
    at com.google.cloud.storage.StorageImpl.internalCreate(StorageImpl.java:199)
    at com.google.cloud.storage.StorageImpl.create(StorageImpl.java:161)
    at java.lang.Thread.run(Thread.java:748)
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
POST https://storage.googleapis.com/upload/storage/v1/b/my-bucket/o?projection=full&uploadType=multipart
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Insufficient Permission",
    "reason" : "insufficientPermissions"
  } ],
  "message" : "Insufficient Permission"
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:150)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:555)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:475)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:592)
    at com.google.cloud.storage.spi.v1.HttpStorageRpc.create(HttpStorageRpc.java:305)
    ... 12 more

Body:
this is not an rbac related error. You just don't have access to GCS.
  May be scopes? Go to any node, and check if your nodes have GCS scope.
  – suren May 15 at 18:20

It looks like @suren is right and most probably it is the issue related to GCS scopes as the 403 error can be related with authorization problems. You can check the scopes set for particular Compute Engine VM by running on it:

curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/?recursive=true" -H "Metadata-Flavor: Google"

It will retrieve this information from metadata server.
You will probably see only storage-ro scope when it comes to GCS as it is the default setting:

"scopes":["https://www.googleapis.com/auth/devstorage.read_only"

and as you can see here, you will need to set:

storage-rw  https://www.googleapis.com/auth/devstorage.read_write

which on Compute Engine instances can be done as follows:

$ gcloud beta compute instances set-scopes example-instance \
      --scopes=storage-rw --zone=us-central1-b \
      --service-account=example-account

It requires however shutting down the instance to be able to apply changes to service-account. Otherwise you'll get the following error message:

ERROR: (gcloud.beta.compute.instances.set-scopes) Could not fetch resource:
 - The instance must be stopped before the service account can be changed.

But when using GKE you cannot simply stop individual worker node as it is part of a managed instance group.

However you can set scopes when creating new GKE cluster e.g. like this:

gcloud container clusters create test --scopes=storage-rw --service-account default --zone europe-west3-c


问:
Different results trying to solve the same problem using for and while loops in python
Hi! I am new to coding and was trying to solve I tried to solve a problem that required me to sum all of the negative integers in a list using loops. I tried to solve the problem using both for and while loops but got different answers.

For Loop Code

```<code>glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in glist3:
    if glist3[i]<0:
        total3+=glist3[i]
print(total3)
</code>```

While Loop Code

```<code>glist4 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
i2=0
total4=0
while i2 < len(glist4):
    if glist4[i2] < 0:
        total4+=glist4[i2]
    i2+=1
print (total4)
</code>```

The Result I got for the for loop is -12 (which is incorrect), but the while loop did give back the correct answer which is -13. Just wanted to ask for possible causes for this discrepancy. Thank you!

答:
The error is in your for loop. You're saying for i in glist3, meaning that the variable i is taking the value of each number rather than incrementing by one yet you're indexing the list using it...

Replace glist3[i] with just i, so that you're adding the ACTUAL numbers rather than the numbers at thier index in the list, as seen below, and this will work...

```<code>glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in glist3:
    if i<0:
        total3+=i
print(total3)
</code>```

Or if you wanted to index... using a range will also work.

```<code>glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in range(len(glist3)):
    if glist3[i]<0:
        total3+=glist3[i]
print(total3)
</code>```

Both should now return -13 as intended.

Hope this helps, good luck!!

Body:
Hi! I am new to coding and was trying to solve I tried to solve a problem that required me to sum all of the negative integers in a list using loops. I tried to solve the problem using both for and while loops but got different answers.

For Loop Code

glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in glist3:
    if glist3[i]<0:
        total3+=glist3[i]
print(total3)

While Loop Code

glist4 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
i2=0
total4=0
while i2 < len(glist4):
    if glist4[i2] < 0:
        total4+=glist4[i2]
    i2+=1
print (total4)

The Result I got for the for loop is -12 (which is incorrect), but the while loop did give back the correct answer which is -13. Just wanted to ask for possible causes for this discrepancy. Thank you!

Body:
The error is in your for loop. You're saying for i in glist3, meaning that the variable i is taking the value of each number rather than incrementing by one yet you're indexing the list using it...

Replace glist3[i] with just i, so that you're adding the ACTUAL numbers rather than the numbers at thier index in the list, as seen below, and this will work...

glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in glist3:
    if i<0:
        total3+=i
print(total3)

Or if you wanted to index... using a range will also work.

glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in range(len(glist3)):
    if glist3[i]<0:
        total3+=glist3[i]
print(total3)

Both should now return -13 as intended.

Hope this helps, good luck!!


问:
Redux: Alternative way of clearing Object of Array
I have a state that could look like this:

```<code> [
  0: {
    "id": "8e9x23x2wto",
    "name": "test-player",
    "currentFrame": 1,
    "rolls": {
      "1": [1,3],
      "2": [1,6],
      "3": [1,6],
      "4": [3,8],
      "5": [4,5],
      "6": [7,6],
      "7": [8,1],
      "8": [5,2],
      "9": [2,1],
      "10": [1,1]
    },
    "totalWins": 0
  }
]
</code>```

I am clearing the rolls Object and resetting currentFrame like so:

```<code>case RESET_GAME:
  return {
    ...state,
    players: state.players.map((player) => {
      return {
        ...player,
        currentFrame: 1,
        rolls: Object.assign(player.rolls, Object.values(player.rolls).map(() => []))
      }
    }),
  }
</code>```

However, sometimes random Arrays within rolls don't get cleared - could be the second one, could be the last one...I have no idea way.

Is there any alternative way to clear rolls so that it only consists of empty Arrays or does someone have an explanation why that might happen?
Any input is much appreciated!

答:
It's common to have:

const initialState = {...}

use it as initial state for your store, createStore(myReducer, initialState)

and use it in your reset action, case RESET_GAME: return initialState

Body:
I have a state that could look like this:

 [
  0: {
    "id": "8e9x23x2wto",
    "name": "test-player",
    "currentFrame": 1,
    "rolls": {
      "1": [1,3],
      "2": [1,6],
      "3": [1,6],
      "4": [3,8],
      "5": [4,5],
      "6": [7,6],
      "7": [8,1],
      "8": [5,2],
      "9": [2,1],
      "10": [1,1]
    },
    "totalWins": 0
  }
]

I am clearing the rolls Object and resetting currentFrame like so:

case RESET_GAME:
  return {
    ...state,
    players: state.players.map((player) => {
      return {
        ...player,
        currentFrame: 1,
        rolls: Object.assign(player.rolls, Object.values(player.rolls).map(() => []))
      }
    }),
  }

However, sometimes random Arrays within rolls don't get cleared - could be the second one, could be the last one...I have no idea way.

Is there any alternative way to clear rolls so that it only consists of empty Arrays or does someone have an explanation why that might happen?
Any input is much appreciated!


答:
A general approach in such a case is to declare in the base class a virtual member function like

```<code>virtual std::ostream & out( std::ostream &os = std::cout ) const;
</code>```

In derived classes the function will be overriden.

Then the operator << can look like

```<code>std::ostream & operator <<( std::ostream &os, const Base &obj )
{
    return obj.out( os );
}
</code>```

A similar way can be defined the operator >> only in this case the virtual member function will not be constant..

Title: Virtual overloaded operators >> and <<

Body:
A general approach in such a case is to declare in the base class a virtual member function like

virtual std::ostream & out( std::ostream &os = std::cout ) const;

In derived classes the function will be overriden.

Then the operator << can look like

std::ostream & operator <<( std::ostream &os, const Base &obj )
{
    return obj.out( os );
}

A similar way can be defined the operator >> only in this case the virtual member function will not be constant..