问:
Cloud Functions problem, query resulting in an Array?
I need to get inside of itens to go into some item, than into product to get the "ean" field and
check if some product have the "ean" from the body request.

My database is organized like that:

```<code>"cart": {
  "itens": {
    "0": {info here},
    "1": {info here}
    "2": {
      "more info here",
      "product": {
         "avaliable": true"
         "quantity": 231,
         "ean": "0000001312"
      }
    continue listing until 47
</code>```

But when I execute my cloud function:

```<code>exports.getItemByEan = functions.https.onRequest(async (request, response) => {
  const db = admin.database();
  const itens = db.ref();
  const eanRef = itens.child('carrinho').child('itens');
  const query = eanRef.orderByKey();

  try {
    const dataSnapshot = await eanRef.once('value');
    response.send(dataSnapshot.val());
  } catch (error) {
    console.log(error)
  }
  })

});
</code>```

But i need to get inside of an iten, and then inside "product" field and than get the "ean", but the result of this is like an Array insted of an object, and without the keys appearing:

```<code>[
    {,
        "product": {
            "avaliable": true,
            "quantity": 9183
            "ean": "0000000000017",
    },
    {

   "product": {
            "avaliable": true,
            "quantity": 131
            "ean": "0000000044790",
        },
    },
    .....continues

</code>```

I want to things, understand why the result of the query is an Array and not an Object with the Keys before the itens like in the Firebase Database, and then how is the better way to find the specific product by Ean.

I can't even do like

```<code>const db = admin.database();
const itens = db.ref();
const eanRef = itens.child('cart').child('itens').child('product'); // This doesnt works, just returns nothing, why ?????
// Isn't "product" field inside the item ?
</code>```

答: If your database keys are all numbers, then instead of an object, you will get an array with the same items, where the indexes of the array are the same as the keys of the nodes in the database.  Your code needs to be prepared for this.  So, if you want the client to receive an object instead of an array, you will have to convert it yourself.</p>

Body:
I need to get inside of itens to go into some item, than into product to get the "ean" field and
check if some product have the "ean" from the body request.

My database is organized like that:

"cart": {
  "itens": {
    "0": {info here},
    "1": {info here}
    "2": {
      "more info here",
      "product": {
         "avaliable": true"
         "quantity": 231,
         "ean": "0000001312"
      }
    continue listing until 47

But when I execute my cloud function:

exports.getItemByEan = functions.https.onRequest(async (request, response) => {
  const db = admin.database();
  const itens = db.ref();
  const eanRef = itens.child('carrinho').child('itens');
  const query = eanRef.orderByKey();

  try {
    const dataSnapshot = await eanRef.once('value');
    response.send(dataSnapshot.val());
  } catch (error) {
    console.log(error)
  }
  })

});

But i need to get inside of an iten, and then inside "product" field and than get the "ean", but the result of this is like an Array insted of an object, and without the keys appearing:

[
    {,
        "product": {
            "avaliable": true,
            "quantity": 9183
            "ean": "0000000000017",
    },
    {

   "product": {
            "avaliable": true,
            "quantity": 131
            "ean": "0000000044790",
        },
    },
    .....continues

I want to things, understand why the result of the query is an Array and not an Object with the Keys before the itens like in the Firebase Database, and then how is the better way to find the specific product by Ean.

I can't even do like

const db = admin.database();
const itens = db.ref();
const eanRef = itens.child('cart').child('itens').child('product'); // This doesnt works, just returns nothing, why ?????
// Isn't "product" field inside the item ?


来源: stackexchange

问:
NASM Assembler question marks in console
I have a problem with my NASM program. At the moment I'm trying to connect two strings.
That works pretty well, but when I'm write in line 15: mov rsi, msg2 instead of mov rsi, 30h the program prints weird output and I don't know why.

The first print on console window is with mov rsi, msg2 and the second with mov rsi, 30h.

Console output:

```<code>simon@simon:~/Projekte/NASM$ bash ./run.sh
Ich verbinde mich mit �`

simon@simon:~/Projekte/NASM$ bash ./run.sh
Ich verbinde mich mit 0
</code>```

Code:

```<code>%include 'functions.asm'

SECTION .data
msg1    db      'Ich verbinde mich mit ', 0h;23
msg2    db      '0';2

SECTION .bss
name:   RESB  255

SECTION .text
global  _start

_start:
  mov     rax, msg1
  mov     rsi, 30h ;so it will work and so   mov     rsi, msg2 not!

  push    rax
  call    strlen
  mov     rdi, rax;rdi ist jetzt die Länge
  pop     rax
  mov     [rax + rdi], rsi;Ursprungsstring + Länge

  call    print
  call    exit
</code>```

functions.asm

```<code>strlen:
  push    rbx;Auf den Stack werfen
  mov     rbx, rax

nextchar:
  cmp     byte [rax], 0
  jz      finished
  inc     rax
  jmp     nextchar

finished:
  sub     rax, rbx
  pop     rbx;Aus dem Stack ziehen
  ret

exit:
  push    rax
  push    rbx
  mov     rax, 1;op code 1
  mov     rbx, 0;0 errors
  int     80h
  pop     rax
  pop     rbx
  ret

printstrlen:;rbx repräsentiert Nachricht, rax die Länge.
  push    rcx
  push    rdx
  push    rax
  push    rbx
  mov     rcx, rbx
  mov     rdx, rax
  mov     rax, 4
  mov     rbx, 1
  int     80h
  pop     rcx
  pop     rdx
  pop     rax
  pop     rbx
  ret

print:
  push    rbx
  mov     rbx, rax
  call    strlen
  call    printstrlen
  pop     rbx
  ret
</code>```

Thanks you for help.

Best regards

答:
```<code>mov rsi, msg2
</code>```

loads the address of msg2 into rsi. You want to load the value. Use

```<code>movzx rsi, byte [msg2]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem with my NASM program. At the moment I'm trying to connect two strings.
That works pretty well, but when I'm write in line 15: mov rsi, msg2 instead of mov rsi, 30h the program prints weird output and I don't know why.

The first print on console window is with mov rsi, msg2 and the second with mov rsi, 30h.

Console output:

simon@simon:~/Projekte/NASM$ bash ./run.sh
Ich verbinde mich mit �`

simon@simon:~/Projekte/NASM$ bash ./run.sh
Ich verbinde mich mit 0

Code:

%include 'functions.asm'

SECTION .data
msg1    db      'Ich verbinde mich mit ', 0h;23
msg2    db      '0';2

SECTION .bss
name:   RESB  255

SECTION .text
global  _start

_start:
  mov     rax, msg1
  mov     rsi, 30h ;so it will work and so   mov     rsi, msg2 not!

  push    rax
  call    strlen
  mov     rdi, rax;rdi ist jetzt die Länge
  pop     rax
  mov     [rax + rdi], rsi;Ursprungsstring + Länge

  call    print
  call    exit

functions.asm

strlen:
  push    rbx;Auf den Stack werfen
  mov     rbx, rax

nextchar:
  cmp     byte [rax], 0
  jz      finished
  inc     rax
  jmp     nextchar

finished:
  sub     rax, rbx
  pop     rbx;Aus dem Stack ziehen
  ret

exit:
  push    rax
  push    rbx
  mov     rax, 1;op code 1
  mov     rbx, 0;0 errors
  int     80h
  pop     rax
  pop     rbx
  ret

printstrlen:;rbx repräsentiert Nachricht, rax die Länge.
  push    rcx
  push    rdx
  push    rax
  push    rbx
  mov     rcx, rbx
  mov     rdx, rax
  mov     rax, 4
  mov     rbx, 1
  int     80h
  pop     rcx
  pop     rdx
  pop     rax
  pop     rbx
  ret

print:
  push    rbx
  mov     rbx, rax
  call    strlen
  call    printstrlen
  pop     rbx
  ret

Thanks you for help.

Best regards

Body:
mov rsi, msg2

loads the address of msg2 into rsi. You want to load the value. Use

movzx rsi, byte [msg2]


问:
Print the key/value types of a Golang map
I am trying to print the type of a map, eg: map[int]string

```<code>func handleMap(m reflect.Value) string {

    keys := m.MapKeys()
    n := len(keys)

    keyType := reflect.ValueOf(keys).Type().Elem().String()
    valType := m.Type().Elem().String()

    return fmt.Sprintf("map[%s]%s>", keyType, valType)
}
</code>```

so if I do:

```<code>log.Println(handleMap(make(map[int]string)))
</code>```

I want to get "map[int]string"

but I can't figure out the right calls to make.

答:
Try not to use reflect.  But if you must use reflect:

A reflect.Value value has a Type() function, which returns a reflect.Type value.

If that type's Kind() is reflect.Map, that reflect.Value is a value of type map[T1]T2 for some types T1 and T2, where T1 is the key type and T2 is the element type.

Therefore, when using reflect, we can pull apart the pieces like this:

```<code>func show(m reflect.Value) {
    t := m.Type()
    if t.Kind() != reflect.Map {
        panic("not a map")
    }
    kt := t.Key()
    et := t.Elem()
    fmt.Printf("m = map from %s to %s\n", kt, et)
}
</code>```

See a more complete example on the Go Playground.  (Note that both maps are actually nil, so there are no keys and values to enumerate.)

Body:
I am trying to print the type of a map, eg: map[int]string

func handleMap(m reflect.Value) string {

    keys := m.MapKeys()
    n := len(keys)

    keyType := reflect.ValueOf(keys).Type().Elem().String()
    valType := m.Type().Elem().String()

    return fmt.Sprintf("map[%s]%s>", keyType, valType)
}

so if I do:

log.Println(handleMap(make(map[int]string)))

I want to get "map[int]string"

but I can't figure out the right calls to make.

Body:
Try not to use reflect.  But if you must use reflect:

A reflect.Value value has a Type() function, which returns a reflect.Type value.

If that type's Kind() is reflect.Map, that reflect.Value is a value of type map[T1]T2 for some types T1 and T2, where T1 is the key type and T2 is the element type.

Therefore, when using reflect, we can pull apart the pieces like this:

func show(m reflect.Value) {
    t := m.Type()
    if t.Kind() != reflect.Map {
        panic("not a map")
    }
    kt := t.Key()
    et := t.Elem()
    fmt.Printf("m = map from %s to %s\n", kt, et)
}

See a more complete example on the Go Playground.  (Note that both maps are actually nil, so there are no keys and values to enumerate.)


问:
Angular setTimeout() with external lambda with parameter
I want to solve two problems simultaneously: 1) use setTimeout( #action#, timeMillis) with #action# as lambda 2) supply lambda with a parameter.

A popular approach with setTimeout( ()=>{ #callback# }, timeMillis) works perfectly when I extract ()=>{ #callback# } to lambda (and this case lambda has no parameters).
 But if I try to pass a lambda with parameter to setTimeout - this function stops working properly - callback fires immediately.

Here  is my code:

```<code>let lambda = (text: string) : TimerHandler => {
    alert(text)
    return ""
}

 .  .  .  .

lambda('text1')                     // value passes to lambda (show 'text1')         - OK  |  no delay - X
setTimeout(lambda, 3000);           // value don't pass to lambda (show 'undefined') - X   |  delay    - OK
setTimeout(lambda('text3'), 3000);  // value passes to lambda (show 'text1')         - OK  |  no delay - X
</code>```

Note: Accordingly to setTimeout docs, first #action# parameter is of type TimerHandler, and this type is extension of string. Thats why I have to return "empty_string" inside lambda's body.

Maybe this behaviour occurs because of an empty string in return statement? But I don't know what to set there

答:
The call setTimeout(lambda('text3'), 3000); fires immediately because the function is called and it's return value is scheduled with the timeout.

Either pass parameters as described in @bjdose's answer, or use the callback form setTimeout(() => { this.lambda('text4') }, 3000);.

Working example: Stackblitz

Body:
I want to solve two problems simultaneously: 1) use setTimeout( #action#, timeMillis) with #action# as lambda 2) supply lambda with a parameter.

A popular approach with setTimeout( ()=>{ #callback# }, timeMillis) works perfectly when I extract ()=>{ #callback# } to lambda (and this case lambda has no parameters).
 But if I try to pass a lambda with parameter to setTimeout - this function stops working properly - callback fires immediately.

Here  is my code:

let lambda = (text: string) : TimerHandler => {
    alert(text)
    return ""
}

 .  .  .  .

lambda('text1')                     // value passes to lambda (show 'text1')         - OK  |  no delay - X
setTimeout(lambda, 3000);           // value don't pass to lambda (show 'undefined') - X   |  delay    - OK
setTimeout(lambda('text3'), 3000);  // value passes to lambda (show 'text1')         - OK  |  no delay - X

Note: Accordingly to setTimeout docs, first #action# parameter is of type TimerHandler, and this type is extension of string. Thats why I have to return "empty_string" inside lambda's body.

Maybe this behaviour occurs because of an empty string in return statement? But I don't know what to set there


问:
How to return namespaces by regex in clojure?
Suppose I want to unmap all the namespaces loaded in my repl (all-ns) that match the regex myproject\..*stuff. So I want to do something like (unmap #"myproject\..*stuff"), which doesn't work because unmap takes functions and not regexes.

答:
This should get you started:

```<code>(->> (all-ns) (mapcat #(ns-publics %)) (map second))
</code>```

Gives you a list of all symbols across all namespaces.
Next steps, add a filter for the var's you want unmapped and then call (ns-unmap)

Body:
This should get you started:

(->> (all-ns) (mapcat #(ns-publics %)) (map second))

Gives you a list of all symbols across all namespaces.
Next steps, add a filter for the var's you want unmapped and then call (ns-unmap)


问:
Flume Kafka integration error "producer.SyncProducer: Disconnecting from localhost:2181"
I am getting the following error:</p>

```<code>s20/02/15 07:31:33 INFO producer.SyncProducer: Connected to localhost:2181 for producing
20/02/15 07:31:33 INFO producer.SyncProducer: Disconnecting from localhost:2181
20/02/15 07:31:33 WARN client.ClientUtils$: Fetching topic metadata with correlation id 0 for topics [Set(flkf)] from broker [id:0,host:localhost,port:2181] failed
java.io.EOFException: Received -1 when reading from channel, socket has likely been closed.
</code>```

答: You've pointed flume at Zookeeper, not a broker. Try port 9092

Body:
I am getting the following error:

s20/02/15 07:31:33 INFO producer.SyncProducer: Connected to localhost:2181 for producing
20/02/15 07:31:33 INFO producer.SyncProducer: Disconnecting from localhost:2181
20/02/15 07:31:33 WARN client.ClientUtils$: Fetching topic metadata with correlation id 0 for topics [Set(flkf)] from broker [id:0,host:localhost,port:2181] failed
java.io.EOFException: Received -1 when reading from channel, socket has likely been closed.


问:
Flutter OnSelected - how to access "this"
I need to know how to access "this" when using the onSelected function within my button.

Using latest flutter I have the following code:

```<code>                        FilterChip(
                          backgroundColor: _colorNavFilter,
                          padding: EdgeInsets.only(
                              top: 8, right: 4, bottom: 8, left: 12),
                          elevation: 2,
                          avatar: CircleAvatar(
                            backgroundColor: Colors.transparent,
                            child: _filter[index]['icon'],
                          ),
                          label: Text(
                            _filter[index]['title'],
                            style: TextStyle(color: _colorNav),
                          ),
                          onSelected: (bool value) {
                            setState(() {
                              if (postCategory == 'false') {
                                postCategory = _filter[index]['title'];
                                _colorNav = Colors.black; // This will end up coloring all buttons in the list - but I want only this specific one
                                _colorNavFilter = Colors.black;
                              } else {
                                postCategory = 'false';
                                _colorNav = _colorBlue;
                                _colorNavFilter = Colors.white;
                              }
                            });
                          },
                        );
</code>```

The problem is that it will color all buttons having that variable in black. I'm aware I could define a dedicated variable for every button and then modify this one with index but that seems rather ugly. Can I not do something like "this.color = Colors.black"?

答:
onSelected is correct, but you should use it in combination with selected. Try this:

```<code>bool selectedValue = false;

FilterChip(
  backgroundColor: selectedValue? Colors.black : Colors.white,
  selected: selectedValue, // This is important
  padding: EdgeInsets.only(
  top: 8, right: 4, bottom: 8, left: 12),
  elevation: 2,
  avatar: CircleAvatar(
    backgroundColor: Colors.transparent,
    child: _filter[index]['icon'],
    ),
  label: Text(
    _filter[index]['title'],
    style: TextStyle(color: selectedValue? Colors.black : _colorBlue),
  ),
  onSelected: (bool value) {
    setState(() {
      if (postCategory == 'false') {
        postCategory = _filter[index]['title'];
        selectedValue = true;
      } else {
        postCategory = 'false';
        selectedValue = false;
      }
    });
  },
);
</code>```

Body:
I need to know how to access "this" when using the onSelected function within my button.

Using latest flutter I have the following code:

                        FilterChip(
                          backgroundColor: _colorNavFilter,
                          padding: EdgeInsets.only(
                              top: 8, right: 4, bottom: 8, left: 12),
                          elevation: 2,
                          avatar: CircleAvatar(
                            backgroundColor: Colors.transparent,
                            child: _filter[index]['icon'],
                          ),
                          label: Text(
                            _filter[index]['title'],
                            style: TextStyle(color: _colorNav),
                          ),
                          onSelected: (bool value) {
                            setState(() {
                              if (postCategory == 'false') {
                                postCategory = _filter[index]['title'];
                                _colorNav = Colors.black; // This will end up coloring all buttons in the list - but I want only this specific one
                                _colorNavFilter = Colors.black;
                              } else {
                                postCategory = 'false';
                                _colorNav = _colorBlue;
                                _colorNavFilter = Colors.white;
                              }
                            });
                          },
                        );

The problem is that it will color all buttons having that variable in black. I'm aware I could define a dedicated variable for every button and then modify this one with index but that seems rather ugly. Can I not do something like "this.color = Colors.black"?

Body:
onSelected is correct, but you should use it in combination with selected. Try this:

bool selectedValue = false;

FilterChip(
  backgroundColor: selectedValue? Colors.black : Colors.white,
  selected: selectedValue, // This is important
  padding: EdgeInsets.only(
  top: 8, right: 4, bottom: 8, left: 12),
  elevation: 2,
  avatar: CircleAvatar(
    backgroundColor: Colors.transparent,
    child: _filter[index]['icon'],
    ),
  label: Text(
    _filter[index]['title'],
    style: TextStyle(color: selectedValue? Colors.black : _colorBlue),
  ),
  onSelected: (bool value) {
    setState(() {
      if (postCategory == 'false') {
        postCategory = _filter[index]['title'];
        selectedValue = true;
      } else {
        postCategory = 'false';
        selectedValue = false;
      }
    });
  },
);


问:
the closest Sunday before given date with JavaScript
I need to know the date for last Sunday for given date in php & javascript

Let's have a function give_me_last_Sunday

```<code>give_me_last_Sunday('20110517') is 20110515
give_me_last_Sunday('20110604') is 20110529
</code>```

The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.

My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.

答: Yup and strtotime has been ported to JS for eg http://phpjs.org/functions/strtotime:554 here.</p>

ContentLicense: CC BY-SA 3.0

Body:
I need to know the date for last Sunday for given date in php & javascript

Let's have a function give_me_last_Sunday

give_me_last_Sunday('20110517') is 20110515
give_me_last_Sunday('20110604') is 20110529

The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.

My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.


问:
C++: std::vector - std::find & std::distance query
To give context to my question I will describe what it is I am ultimately trying to achieve - I am developing a game, I have a .obj model that I am using as my terrain and I must update the players height as they traverse the terrain (because the terrain is far from flat). I am achieving this currently by doing the following - when I load the mesh (terrain.obj) I store all its vertices (each vertex is a Vector3f object that has an x y and z value) in a std::vector<Vector3f> meshVertices, then every second in the "main game loop" I loop through every one of the Vector3f objects in meshVertices and check its x and z value against the players x and z value, if they are colliding I set the players height as the y value of the matched Vector3f object.

This system actually works and updates my players height as they traverse through the terrain, the only issue is this - my approach of checking every single mesh vertex against player position every second kills my frame rate, I need a much better system.

I will now describe my new optimized approach in the attempt of saving my frame rate - Firstly, when creating the mesh I don't just store each Vector3f vertex in a single std::vector<Vector3f>, I store the x y and z values of each Vector3f vertex of the mesh in three seperate std::vector<Vector3f>'s, named meshVerticesX, mechVerticesY and meshVerticesZ. These std::vector's can be seen in the following code:

```<code>for (Vector3f currentVertex : meshVertices) {
            meshVerticesX.push_back((int)currentVertex.GetX());
}
for (Vector3f currentVertex : meshVertices) {
            meshVerticesZ.push_back((int)currentVertex.GetZ());
}
for (Vector3f currentVertex : meshVertices) {
            meshVerticesY.push_back((int)currentVertex.GetY());
}
</code>```

Now every second I get the x and z value of the players position (casted to an int because I feel like making this system work with int values and not float values will be much easier for comparisons later) and then send them to functions that check to see if they exist in the before mentioned meshVerticesX and mechVerticesZ by returning a bool, the code responsible for this is as follows:

```<code>int playerPosX = (int) freeMoveObjects[0]->GetParent()->GetTransform()->GetPos()->GetX();
int playerPosZ = (int) freeMoveObjects[0]->GetParent()->GetTransform()->GetPos()->GetZ();
bool x = meshObjects[0]->checkMeshVerticesX(playerPosX);
bool z = meshObjects[0]->checkMeshVerticesZ(playerPosZ);
</code>```

The functions checkMeshVerticesX and checkMeshVerticesZ are as follows:

```<code>bool Mesh::checkMeshVerticesX(int playerPosX)
{
    return std::find(meshVerticesX.begin(), meshVerticesX.end(), playerPosX) != meshVerticesX.end();
}
</code>```

```<code>bool Mesh::checkMeshVerticesZ(int playerPosZ)
{
    return std::find(meshVerticesZ.begin(), meshVerticesZ.end(), playerPosZ) != meshVerticesZ.end();
}
</code>```

Using the returned boolean values (true if the players position was in the respective std::vector or false if it was not) I then call another function (getMeshYHeight) that also gets passed the players x and z position that then checks the index of the respective std::vector's (meshVerticesX & meshVerticesZ) were the match was found, then checks if these indexes are equal and if so returns an int of that index from the meshVerticesY std::vector mentioned earlier, this code can be seen in the following:

```<code>if (x == true & z == true) {// boolean values returned by checkMeshVerticesX & checkMeshVerticesZ
        int terrainVertexYHeight = meshObjects[0]->getMeshYHeight(playerPosX, playerPosZ);
        freeMoveObjects[0]->GetParent()->GetTransform()->GetPos()->SetY(terrainVertexYHeight);
    }
</code>```

The function getMeshYHeight is as follows:

```<code>int Mesh::getMeshYHeight(int playerXPos, int playerZPos) {//15/2/20
    auto iterX = std::find(meshVerticesX.begin(), meshVerticesX.end(), playerXPos) != meshVerticesX.end();
    auto iterZ = std::find(meshVerticesZ.begin(), meshVerticesZ.end(), playerZPos) != meshVerticesZ.end();
    int indexX = std::distance(meshVerticesX.begin(), iterX);
    int indexZ = std::distance(meshVerticesZ.begin(), iterZ);
    if (indexX == indexZ)
    {
        return meshVerticesY[indexX];
    }
}
</code>```

The idea here is that if the index from the meshVerticesX and meshVerticesZ std::vectors's for the original check match, then they must be the x and z values from an original Vector3f object when I first made the mesh as described earlier, and so that same index in meshVerticesY must contain that same Vector3f's objects y value, therefore return it and use it to set the players height.

The issue is that I cant even test if this works because the line of code int indexX = std::distance(meshVerticesX.begin(), iterX); gives an error saying the arguments supplied to std::distance are wrong (it says iterX is a bool instead of an int which is what I thought it would be).

So my question is - Firstly, if I diden't have this error would my approach even work? and if so, how can I fix the error?

答:
I kind of lost track of your logic somewhere in the middle there, but to address the issue at hand: iterX is a bool!

```<code>auto iterX = std::find(...) != meshVerticesX.end();
</code>```

In this statement, find returns an iterator, which you compare to another iterator, meshVerticesX.end(). The result of that expression (the comparison operator) is a bool, which is then assigned to iterX, so auto deduces that iterX needs to be of type bool.

Body:
To give context to my question I will describe what it is I am ultimately trying to achieve - I am developing a game, I have a .obj model that I am using as my terrain and I must update the players height as they traverse the terrain (because the terrain is far from flat). I am achieving this currently by doing the following - when I load the mesh (terrain.obj) I store all its vertices (each vertex is a Vector3f object that has an x y and z value) in a std::vector<Vector3f> meshVertices, then every second in the "main game loop" I loop through every one of the Vector3f objects in meshVertices and check its x and z value against the players x and z value, if they are colliding I set the players height as the y value of the matched Vector3f object.

This system actually works and updates my players height as they traverse through the terrain, the only issue is this - my approach of checking every single mesh vertex against player position every second kills my frame rate, I need a much better system.

I will now describe my new optimized approach in the attempt of saving my frame rate - Firstly, when creating the mesh I don't just store each Vector3f vertex in a single std::vector<Vector3f>, I store the x y and z values of each Vector3f vertex of the mesh in three seperate std::vector<Vector3f>'s, named meshVerticesX, mechVerticesY and meshVerticesZ. These std::vector's can be seen in the following code:

for (Vector3f currentVertex : meshVertices) {
            meshVerticesX.push_back((int)currentVertex.GetX());
}
for (Vector3f currentVertex : meshVertices) {
            meshVerticesZ.push_back((int)currentVertex.GetZ());
}
for (Vector3f currentVertex : meshVertices) {
            meshVerticesY.push_back((int)currentVertex.GetY());
}

Now every second I get the x and z value of the players position (casted to an int because I feel like making this system work with int values and not float values will be much easier for comparisons later) and then send them to functions that check to see if they exist in the before mentioned meshVerticesX and mechVerticesZ by returning a bool, the code responsible for this is as follows:

int playerPosX = (int) freeMoveObjects[0]->GetParent()->GetTransform()->GetPos()->GetX();
int playerPosZ = (int) freeMoveObjects[0]->GetParent()->GetTransform()->GetPos()->GetZ();
bool x = meshObjects[0]->checkMeshVerticesX(playerPosX);
bool z = meshObjects[0]->checkMeshVerticesZ(playerPosZ);

The functions checkMeshVerticesX and checkMeshVerticesZ are as follows:

bool Mesh::checkMeshVerticesX(int playerPosX)
{
    return std::find(meshVerticesX.begin(), meshVerticesX.end(), playerPosX) != meshVerticesX.end();
}

bool Mesh::checkMeshVerticesZ(int playerPosZ)
{
    return std::find(meshVerticesZ.begin(), meshVerticesZ.end(), playerPosZ) != meshVerticesZ.end();
}

Using the returned boolean values (true if the players position was in the respective std::vector or false if it was not) I then call another function (getMeshYHeight) that also gets passed the players x and z position that then checks the index of the respective std::vector's (meshVerticesX & meshVerticesZ) were the match was found, then checks if these indexes are equal and if so returns an int of that index from the meshVerticesY std::vector mentioned earlier, this code can be seen in the following:

if (x == true & z == true) {// boolean values returned by checkMeshVerticesX & checkMeshVerticesZ
        int terrainVertexYHeight = meshObjects[0]->getMeshYHeight(playerPosX, playerPosZ);
        freeMoveObjects[0]->GetParent()->GetTransform()->GetPos()->SetY(terrainVertexYHeight);
    }

The function getMeshYHeight is as follows:

int Mesh::getMeshYHeight(int playerXPos, int playerZPos) {//15/2/20
    auto iterX = std::find(meshVerticesX.begin(), meshVerticesX.end(), playerXPos) != meshVerticesX.end();
    auto iterZ = std::find(meshVerticesZ.begin(), meshVerticesZ.end(), playerZPos) != meshVerticesZ.end();
    int indexX = std::distance(meshVerticesX.begin(), iterX);
    int indexZ = std::distance(meshVerticesZ.begin(), iterZ);
    if (indexX == indexZ)
    {
        return meshVerticesY[indexX];
    }
}

The idea here is that if the index from the meshVerticesX and meshVerticesZ std::vectors's for the original check match, then they must be the x and z values from an original Vector3f object when I first made the mesh as described earlier, and so that same index in meshVerticesY must contain that same Vector3f's objects y value, therefore return it and use it to set the players height.

The issue is that I cant even test if this works because the line of code int indexX = std::distance(meshVerticesX.begin(), iterX); gives an error saying the arguments supplied to std::distance are wrong (it says iterX is a bool instead of an int which is what I thought it would be).

So my question is - Firstly, if I diden't have this error would my approach even work? and if so, how can I fix the error?

Body:
I kind of lost track of your logic somewhere in the middle there, but to address the issue at hand: iterX is a bool!

auto iterX = std::find(...) != meshVerticesX.end();

In this statement, find returns an iterator, which you compare to another iterator, meshVerticesX.end(). The result of that expression (the comparison operator) is a bool, which is then assigned to iterX, so auto deduces that iterX needs to be of type bool.


问:
visual studio code looks blurry
Folks, this is not a code question but I dont know where else to post this. the website of VS Code linked me here so here goes.

Here are my visual studio code version details

Version: 1.26.1
Commit: 493869ee8e8a846b0855873886fc79d480d342de
Date: 2018-08-16T18:38:57.434Z
Electron: 2.0.5
Chrome: 61.0.3163.100
Node.js: 8.9.3
V8: 6.1.534.41
Architecture: x64

Once I updated to this version, the entire app started looking blurry. It was fine before the update and has been looking fine on this windows 10 machine.

I got other Microsoft Apps - Office Word, Excel and the rest, and they all fine. Visual Studio (regular) looks fine. Its this software and only since the latest update to 1.26.1

Note: There is one other software which always had a blurry appearance, and that is Postman. I assumed that it is a Postman issue so never got around to fixing it or try fixing. adding this here if there is a connection but the question is primarily about Code, and how I could fix the appearance problem.

Update 1 :

So, I opened Postman and that also has stopped being blurry. So, looks like the blame does fall on AMD Radeon rather than MS or Postman developers.

答:
I know this is late but just in case it didn't work for someone, here is another solution:

Right click on VsCode and go to properties.
Copy this command

```<code>--disable-gpu --enable-use-zoom-for-dsf
</code>```

and append it to the target path n the shortcut properties dialog.
Click apply and the reopen VScode.

Here is the article that I am referencing  https://medium.com/kasun-kodagoda/fix-text-becomes-blurry-when-vs-code-application-loses-focus-issue-on-windows-d95697b2f927

Title: visual studio code looks blurry

Body:
I know this is late but just in case it didn't work for someone, here is another solution:

Right click on VsCode and go to properties.
Copy this command

--disable-gpu --enable-use-zoom-for-dsf

and append it to the target path n the shortcut properties dialog.
Click apply and the reopen VScode.

Here is the article that I am referencing  https://medium.com/kasun-kodagoda/fix-text-becomes-blurry-when-vs-code-application-loses-focus-issue-on-windows-d95697b2f927


问:
Have the parent execute something while waiting for child
I am trying to have two things execute at the same time. I have some code to run a PWM module, and I have some code to read from an ADC and both work. I want to now read from the ADC while waiting for the pwm module to finish. I thought of forking, but wasn't sure how to get the parent to wait for the child to finish.

I'd like to have something like the following:

```<code>pid = os.fork()
if(pid > 0):
     while(child not done):
         adc code
else:
    pwm code
</code>```

答:
Using multiprocessing I was able to do it.</p>

```<code>pwm_p = Process(target=my_pwm, args=(my_args,))
pmw_p.start()
while(pwm_p.is_alive()):
    read_from_adc()
</code>```

Body:
I am trying to have two things execute at the same time. I have some code to run a PWM module, and I have some code to read from an ADC and both work. I want to now read from the ADC while waiting for the pwm module to finish. I thought of forking, but wasn't sure how to get the parent to wait for the child to finish.

I'd like to have something like the following:

pid = os.fork()
if(pid > 0):
     while(child not done):
         adc code
else:
    pwm code

Body:
Using multiprocessing I was able to do it.

pwm_p = Process(target=my_pwm, args=(my_args,))
pmw_p.start()
while(pwm_p.is_alive()):
    read_from_adc()


问:
Excel: Email workbook as attachment without VBA code
I use the following code assigned to a CommandButton to automatically attach the workbook to an email so users can send it out.  Is there a way to attach the workbook without the code, so the people receiving the email do not have the full code, but the sender keeps it in their copy? (The recipients only need to see the data, they do not interact with the form, but the sender interacts with it several times a day.) When I save the Workbook as .xlsx, it gives me an yes/no/help MsgBox that I would like to avoid during the sending - to keep it as a "one-click" operation.</p>

```<code>Source_File = ThisWorkbook.FullName
myMail.Attachments.Add Source_File
</code>```

答:
```<code>Option Explicit

Sub CDO_Mail_Workbook()
    Dim wb As Workbook
    Dim TempFilePath As String
    Dim TempFileName As String
    Dim FileExtStr As String
    Dim iMsg As Object
    Dim iConf As Object
    Dim Flds As Variant
    Dim MyDate
    MyDate = Format(Now(), "dd-mmm-yy")

    Set wb = ActiveWorkbook

    If Val(Application.Version) >= 12 Then
        If wb.FileFormat = 51 And wb.HasVBProject = True Then
            MsgBox "There is VBA code in this xlsx file, there will be no VBA code in the file you send." & vbNewLine & _
                   "Save the file first as xlsm and then try the macro again.", vbInformation
            Exit Sub
        End If
    End If

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Make a copy of the file/Mail it/Delete it
    'If you want to change the file name then change only TempFileName
    TempFilePath = Environ$("temp") & "\"
    'TempFileName = wb.Name & " " & Format(Now, "yyyy-mmm-dd")
    TempFileName = "Test" & "-" & Format(Now, "yyyy-mmm-dd")

    'FileExtStr = "." & LCase(Right(wb.Name, Len(wb.Name) - InStrRev(wb.Name, ".", , 1)))
    FileExtStr = ".xlsm"

    Application.DisplayAlerts = False
    ' wb.SaveAs Filename:=TempFilePath & TempFileName & FileExtStr, FileFormat:=51, AccessMode:=xlExclusive, ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges

    ActiveWorkbook.SaveCopyAs Filename:=TempFilePath & TempFileName & "Copy" & FileExtStr

    Workbooks.Open (TempFilePath & TempFileName & "Copy" & FileExtStr)
    ActiveWorkbook.SaveAs Filename:=TempFilePath & TempFileName & "-email" & ".xlsx", FileFormat:=51, AccessMode:=xlExclusive, ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
    ActiveWorkbook.Close False

    'wb.SaveCopyAs TempFilePath & TempFileName & FileExtStr

    Application.DisplayAlerts = True

    Set iMsg = CreateObject("CDO.Message")
    Set iConf = CreateObject("CDO.Configuration")

    iConf.Load -1    ' CDO Source Defaults
    Set Flds = iConf.Fields
    With Flds
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.office365.com"
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "noone@noone.com"
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = "1"
        .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
        .Update
    End With

    With iMsg
        Set .Configuration = iConf
        '.To = "noone@noone.com"
        '.CC = ""
        .BCC = ""
        .From = "noone@noone.com"
        .Subject = "Test - " & MyDate
        .TextBody = ""
        .AddAttachment TempFilePath & TempFileName & "-email" & ".xlsx"
        .Send
    End With

    'If you not want to delete the file you send delete this line
    Kill TempFilePath & TempFileName & "-email" & ".xlsx"

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With

     Application.DisplayAlerts = False
    Set wb = Nothing

    For Each wb In Application.Workbooks
        wb.Save
    Next wb

    Application.Quit

End Sub

To send a single worksheet with the vba code removed, I've used this:

Option Explicit

'This procedure will send the ActiveSheet in a new workbook
'For more sheets use : Sourcewb.Sheets(Array("Sheet1", "Sheet3")).Copy

Sub CDO_Mail_ActiveSheet_Or_Sheets()
'Working in 97-2007
    Dim FileExtStr As String
    Dim FileFormatNum As Long
    Dim Sourcewb As Workbook
    Dim Destwb As Workbook
    Dim TempFilePath As String
    Dim TempFileName As String
    Dim iMsg As Object
    Dim iConf As Object
    Dim sh As Worksheet
    Dim Flds As Variant
    Dim MyDate
    MyDate = Format(Now(), "dd-mmm-yy")
    Dim wb As Workbook

    Set wb = ActiveWorkbook

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    Set Sourcewb = ActiveWorkbook

    'Copy the ActiveSheet to a new workbook
    ActiveSheet.Copy

    'Or if you want to copy more then one sheet use:
    'Sourcewb.Sheets(Array("Sheet1", "Sheet3")).Copy

    Set Destwb = ActiveWorkbook

    'Determine the Excel version and file extension/format
    With Destwb
        If Val(Application.Version) < 12 Then
            'You use Excel 97-2003
            FileExtStr = ".xls": FileFormatNum = -4143
        Else
            'You use Excel 2007
            'We exit the sub when your answer is NO in the security dialog that you only
            'see  when you copy a sheet from a xlsm file with macro's disabled.
            If Sourcewb.Name = .Name Then
                With Application
                    .ScreenUpdating = True
                    .EnableEvents = True
                End With
                MsgBox "Your answer is NO in the security dialog"
                Exit Sub
            Else
                Select Case Sourcewb.FileFormat
                Case 51: FileExtStr = ".xlsx": FileFormatNum = 51
                Case 52:
                    If .HasVBProject Then
                        FileExtStr = ".xlsm": FileFormatNum = 52
                    Else
                        FileExtStr = ".xlsx": FileFormatNum = 51
                    End If
                Case 56: FileExtStr = ".xls": FileFormatNum = 56
                Case Else: FileExtStr = ".xlsb": FileFormatNum = 50
                End Select
            End If
        End If
    End With

    'Change all cells in Destwb to values if you want
    For Each sh In Destwb.Worksheets
        sh.Select
        With sh.UsedRange
            .Cells.Copy
            .Cells.PasteSpecial xlPasteValues
            .Cells(1).Select
        End With
        Application.CutCopyMode = False
    Next sh
    Destwb.Worksheets(1).Select

    'Save the new workbook/Mail it/Delete it
    TempFilePath = Environ$("temp") & "\"
    TempFileName = "Test" & "-" & Format(Now, "yyyy-mmm-dd")

    Application.DisplayAlerts = False

    With Destwb
        .SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum
        .Close savechanges:=False
    End With

    Application.DisplayAlerts = True

    Set iMsg = CreateObject("CDO.Message")
    Set iConf = CreateObject("CDO.Configuration")

    iConf.Load -1    ' CDO Source Defaults
    Set Flds = iConf.Fields
    With Flds
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.office365.com"
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "noone@noone.com"
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = "1"
        .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
        .Update
    End With

    With iMsg
        Set .Configuration = iConf
        .To = "noone@noone.com"
'.CC = ""
        '.BCC = ""
        .From = "noone@noone.com"
        .Subject = "Test-" & MyDate
        .TextBody = ""
        .AddAttachment TempFilePath & TempFileName & FileExtStr
        .Send
    End With

    'If you not want to delete the file you send delete this line
    Kill TempFilePath & TempFileName & FileExtStr

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With

     Application.DisplayAlerts = False
    Set wb = Nothing

    For Each wb In Application.Workbooks
        wb.Save
    Next wb

    Application.Quit

End Sub
</code>```

Body:
I use the following code assigned to a CommandButton to automatically attach the workbook to an email so users can send it out.  Is there a way to attach the workbook without the code, so the people receiving the email do not have the full code, but the sender keeps it in their copy? (The recipients only need to see the data, they do not interact with the form, but the sender interacts with it several times a day.) When I save the Workbook as .xlsx, it gives me an yes/no/help MsgBox that I would like to avoid during the sending - to keep it as a "one-click" operation.

Source_File = ThisWorkbook.FullName
myMail.Attachments.Add Source_File


问:
can anyone explain this Java gotcha to me?
This little annoyance caused me to lose an hour of sleep, and I don't understand why.

I have an ArrayList array which I want to iterate over and conditionally remove items.  This was my first attempt:

```<code>for (int i = 0; i < array.size(); i++) {
   if (array.get(i) == conditionMet) array.remove(i);
}
</code>```

And that did not work.  The following did:

```<code>for (Iterator<T> i = array.iterator(); i.hasNext();) {
   if (i.next() == conditionMet) i.remove();
}
</code>```

Why?

答:
In the first for loop,

```<code>for (int i = 0; i < array.size(); i++) {
   if (array.get(i) == conditionMet) array.remove(i);
}
</code>```

the condition ; i < array.size(); is evaluated in the very beginning which will take the size of the original list. So while iterating over it, if you remove any element from it, the size has reduced, but you are still iterating up to the original size, which is obviously wrong.

In the for second loop,

```<code>for (Iterator<T> i = array.iterator(); i.hasNext();) {
   if (i.next() == conditionMet) i.remove();
}
</code>```

since you are using iterator, you are checking if there is anymore element is left in the list or not. hence you do not overstep and it works properly.

(You should have included the exception in the question. "Exception in thread "main" java.lang.IndexOutOfBoundsException")

Body:
This little annoyance caused me to lose an hour of sleep, and I don't understand why.

I have an ArrayList array which I want to iterate over and conditionally remove items.  This was my first attempt:

for (int i = 0; i < array.size(); i++) {
   if (array.get(i) == conditionMet) array.remove(i);
}

And that did not work.  The following did:

for (Iterator<T> i = array.iterator(); i.hasNext();) {
   if (i.next() == conditionMet) i.remove();
}

Why?

Body:
In the first for loop,

for (int i = 0; i < array.size(); i++) {
   if (array.get(i) == conditionMet) array.remove(i);
}

the condition ; i < array.size(); is evaluated in the very beginning which will take the size of the original list. So while iterating over it, if you remove any element from it, the size has reduced, but you are still iterating up to the original size, which is obviously wrong.

In the for second loop,

for (Iterator<T> i = array.iterator(); i.hasNext();) {
   if (i.next() == conditionMet) i.remove();
}

since you are using iterator, you are checking if there is anymore element is left in the list or not. hence you do not overstep and it works properly.

(You should have included the exception in the question. "Exception in thread "main" java.lang.IndexOutOfBoundsException")


问:
'The following gems are missing'
I am trying to create a Rails app that can be copied to another hard drive without having to reinstall its gems.

One thing I've tried is bundle install the gems into vendor/bundle, then copy the entire app over to the new location.

At the new location:

```<code>bundle config set path 'vendor/bundle'
bundle check
# which returns...
The following gems are missing
 * nokogiri (1.10.8)
 * nio4r (2.5.2)
 * websocket-driver (0.7.1)
 * bcrypt (3.1.7)
 * ffi (1.12.2)
 * sassc (2.2.1)
 * pg (1.2.2)
 * puma (4.3.1)
Install missing gems with `bundle install`
</code>```

However, when I go to vendor/bundle/ruby/2.7.0/gems, I see every one of those gems listed.

Try to follow the instruction using the gems in the folder above:

```<code>bundle install --local
=> Could not find nokogiri-1.10.8 in any of the sources
</code>```

Bundle configuration:

```<code>~/myapp/.bundle/config:
---
BUNDLE_PATH: "vendor/bundle"
</code>```

What's going on here?

答:
Either delete or check your bundle config file for conflicting settings and paths that refer to the old location

Check for differences between your local and global bundle config files and resolve any conflicts

Try reinstalling your gems using the --local argument

Sources: Here, here, and here

Title: 'The following gems are missing'

Body:
I am trying to create a Rails app that can be copied to another hard drive without having to reinstall its gems.

One thing I've tried is bundle install the gems into vendor/bundle, then copy the entire app over to the new location.

At the new location:

bundle config set path 'vendor/bundle'
bundle check
# which returns...
The following gems are missing
 * nokogiri (1.10.8)
 * nio4r (2.5.2)
 * websocket-driver (0.7.1)
 * bcrypt (3.1.7)
 * ffi (1.12.2)
 * sassc (2.2.1)
 * pg (1.2.2)
 * puma (4.3.1)
Install missing gems with `bundle install`

However, when I go to vendor/bundle/ruby/2.7.0/gems, I see every one of those gems listed.

Try to follow the instruction using the gems in the folder above:

bundle install --local
=> Could not find nokogiri-1.10.8 in any of the sources

Bundle configuration:

~/myapp/.bundle/config:
---
BUNDLE_PATH: "vendor/bundle"

What's going on here?


问:
How to catch a value and tell the user to input again?
I'm trying to create a game character, and the user is asked to input a number between 0-18. I input 19 to see if the code will tell me to try again, but it just ignores it and then prints out the character. It also does the same thing for the magic amount. The user should enter between 0 & 50, but if I enter a number higher than 50, it will also still print it. I want the code to tell me the input was wrong and try again. Is there a way I could ask the user to try again without using an exception?</p>

```<code>public class Character {

    private String name;
    private int strength;

    public Character() {
        name = "TBD";
        strength = 15;
    }

    public Character(String name, int strength) {
        this.name = name;
        this.strength = strength;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getStrength() {
        return strength;
    }

    public void setStrength(int strength) {
        int count = 1;
        while (true) {
            if (strength >= 0 && strength <= 18) {
                System.out.println("Value is out of range 0-18");
                System.out.println("Please try again");
                break;
            }
            else {
                this.strength = strength;
                count = 0;
            }
        }
    }

    public String toString() {
        return "Name: " + name + ", Strength: " + strength;
    }
}
</code>```

```<code>public class Human extends Character {

    private String name;
    private int strength;
    private String weapon;
    private int magicAmount;

    public Human(String name, int strength, String weapon, int magicAmount) {
        this.name = name;
        this.strength = strength;
        this.weapon = weapon;
        this.magicAmount = magicAmount;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getStrength() {
        return strength;
    }

    public void setStrength(int strength) {
        this.strength = strength;
    }

    public String getWeapon() {
        return weapon;
    }

    public void setWeapon(String weapon) {
        this.weapon = weapon;
    }

    public int getMagicAmount() {
        return magicAmount;
    }

    public void setMagicAmount(int magicAmount) {
        int count = 1;
        while (count != 0) {
            if ((magicAmount >= 0 && magicAmount <= 50)) {
                System.out.println("Value is out of range 0-50");
                System.out.println("Please try again");
                break;
            }
            else {
                this.magicAmount = magicAmount;
                count = 0;
            }
        }
    }

    public String toString() {
        return "Human [Name: " + name + ", Strength: " + strength + ", Weapon: "
                + weapon + ", Magic Amount: " + magicAmount + "]";
    }
}

</code>```

```<code>    ArrayList<Character> characters = new ArrayList<Character>();

    String keepLooping = "y";

    do {
        System.out.println("Which character would you like to create (Human, Robot, or Animal): ");
        String choice = input.nextLine();

        if (choice.equalsIgnoreCase("Human")) {

            System.out.println("Enter a name for the Human: ");
            String name = input.next();

            System.out.println("Enter the amount of stength for Human (0-18): ");
            int strength = input.nextInt();

            input.nextLine();
            System.out.println("Enter a weapon for Human (Sword or Dagger): ");
            String weapon = input.nextLine();

            System.out.println("Enter the magic amount for your selected weapon (0-50): ");
            int magicAmount = input.nextInt();

            Human charH = new Human(name, strength, weapon, magicAmount);
            characters.add(charH);
        }

        input.nextLine();
        System.out.println("Would you like to create more characters - y or n");
        keepLooping = input.nextLine();
    }

    while (keepLooping.equalsIgnoreCase("y"));

    for (int i = 0; i < characters.size(); i++) {
        Character c = characters.get(i);
        System.out.println(c);
    }
}
</code>```

```<code>
</code>```

答:
There is several issues with your code regarding the creation of a Human.

Problem 1

First problem is that you create Human with an all args constructor. That way the setStrength(...) and setMagicAmount(...) is never called.

Solution 1

Make use of the setters. Note this will still not work. See problem 2 and 3.

```<code>public Human(String name, int strength, String weapon, int magicAmount) {
    this.name = name;
    //this.strength = strength;
    setStrength(strength); // not this will still not work! Problem 2 and 3
    this.weapon = weapon;
    //this.magicAmount = magicAmount;
    setMagicAmount(magicAmount); // Will still not work. See Problem 3
}
</code>```

Solution 2

Instead of having an all args constructor you can have a no args constructor and then call the setters. Will still not work. Se problem  2 and 3.

```<code>Human human = new Human();
human.setName(name);
human.setStrength(strength); // will not work. See problem 2 and 3
human.setWeapon(weapon);
human.setMagicAmount(magicAmount); // will not work. See problem 3
</code>```

Problem 2

Class Human extends Character but still you are overriding the setStrength(...) method inside human. This method does not have any rules.

Delete this method inside Human and the correct setStrength(...) from Character with the rules will be called because it is inherited. This will still not work. See problem 4.

Problem 3

You have rules inside setStrength(...) and setMagicAmount(...) with range checks. The problem is that the range checks for both methods is wrong and you do not need the loop.

Solution

First check the value. If outside the range tell the user, else set the value.

For setStrength(...) change to

```<code>public void setStrength(int strength) {
    if (strength < 0 || strength > 18) { // less than 0 or more than 18
        throw new IllegalArgumentException("Value is out of range 0-18");
    }
    this.strength = strength;
}
</code>```

For setMagicAmount(...) change to

```<code>public void setMagicAmount(int magicAmount) {
    if (magicAmount < 0 || magicAmount > 50) { // less than 0 or more than 50
        throw new IllegalArgumentException("Value is out of range 0-50");
    }
    this.magicAmount = magicAmount;
}
</code>```

Body:
I'm trying to create a game character, and the user is asked to input a number between 0-18. I input 19 to see if the code will tell me to try again, but it just ignores it and then prints out the character. It also does the same thing for the magic amount. The user should enter between 0 & 50, but if I enter a number higher than 50, it will also still print it. I want the code to tell me the input was wrong and try again. Is there a way I could ask the user to try again without using an exception?

public class Character {

    private String name;
    private int strength;

    public Character() {
        name = "TBD";
        strength = 15;
    }

    public Character(String name, int strength) {
        this.name = name;
        this.strength = strength;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getStrength() {
        return strength;
    }

    public void setStrength(int strength) {
        int count = 1;
        while (true) {
            if (strength >= 0 && strength <= 18) {
                System.out.println("Value is out of range 0-18");
                System.out.println("Please try again");
                break;
            }
            else {
                this.strength = strength;
                count = 0;
            }
        }
    }

    public String toString() {
        return "Name: " + name + ", Strength: " + strength;
    }
}

public class Human extends Character {

    private String name;
    private int strength;
    private String weapon;
    private int magicAmount;

    public Human(String name, int strength, String weapon, int magicAmount) {
        this.name = name;
        this.strength = strength;
        this.weapon = weapon;
        this.magicAmount = magicAmount;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getStrength() {
        return strength;
    }

    public void setStrength(int strength) {
        this.strength = strength;
    }

    public String getWeapon() {
        return weapon;
    }

    public void setWeapon(String weapon) {
        this.weapon = weapon;
    }

    public int getMagicAmount() {
        return magicAmount;
    }

    public void setMagicAmount(int magicAmount) {
        int count = 1;
        while (count != 0) {
            if ((magicAmount >= 0 && magicAmount <= 50)) {
                System.out.println("Value is out of range 0-50");
                System.out.println("Please try again");
                break;
            }
            else {
                this.magicAmount = magicAmount;
                count = 0;
            }
        }
    }

    public String toString() {
        return "Human [Name: " + name + ", Strength: " + strength + ", Weapon: "
                + weapon + ", Magic Amount: " + magicAmount + "]";
    }
}

    ArrayList<Character> characters = new ArrayList<Character>();

    String keepLooping = "y";

    do {
        System.out.println("Which character would you like to create (Human, Robot, or Animal): ");
        String choice = input.nextLine();

        if (choice.equalsIgnoreCase("Human")) {

            System.out.println("Enter a name for the Human: ");
            String name = input.next();

            System.out.println("Enter the amount of stength for Human (0-18): ");
            int strength = input.nextInt();

            input.nextLine();
            System.out.println("Enter a weapon for Human (Sword or Dagger): ");
            String weapon = input.nextLine();

            System.out.println("Enter the magic amount for your selected weapon (0-50): ");
            int magicAmount = input.nextInt();

            Human charH = new Human(name, strength, weapon, magicAmount);
            characters.add(charH);
        }

        input.nextLine();
        System.out.println("Would you like to create more characters - y or n");
        keepLooping = input.nextLine();
    }

    while (keepLooping.equalsIgnoreCase("y"));

    for (int i = 0; i < characters.size(); i++) {
        Character c = characters.get(i);
        System.out.println(c);
    }
}

Body:
There is several issues with your code regarding the creation of a Human.

Problem 1

First problem is that you create Human with an all args constructor. That way the setStrength(...) and setMagicAmount(...) is never called.

Solution 1

Make use of the setters. Note this will still not work. See problem 2 and 3.

public Human(String name, int strength, String weapon, int magicAmount) {
    this.name = name;
    //this.strength = strength;
    setStrength(strength); // not this will still not work! Problem 2 and 3
    this.weapon = weapon;
    //this.magicAmount = magicAmount;
    setMagicAmount(magicAmount); // Will still not work. See Problem 3
}

Solution 2

Instead of having an all args constructor you can have a no args constructor and then call the setters. Will still not work. Se problem  2 and 3.

Human human = new Human();
human.setName(name);
human.setStrength(strength); // will not work. See problem 2 and 3
human.setWeapon(weapon);
human.setMagicAmount(magicAmount); // will not work. See problem 3

Problem 2

Class Human extends Character but still you are overriding the setStrength(...) method inside human. This method does not have any rules.

Delete this method inside Human and the correct setStrength(...) from Character with the rules will be called because it is inherited. This will still not work. See problem 4.

Problem 3

You have rules inside setStrength(...) and setMagicAmount(...) with range checks. The problem is that the range checks for both methods is wrong and you do not need the loop.

Solution

First check the value. If outside the range tell the user, else set the value.

For setStrength(...) change to

public void setStrength(int strength) {
    if (strength < 0 || strength > 18) { // less than 0 or more than 18
        throw new IllegalArgumentException("Value is out of range 0-18");
    }
    this.strength = strength;
}

For setMagicAmount(...) change to

public void setMagicAmount(int magicAmount) {
    if (magicAmount < 0 || magicAmount > 50) { // less than 0 or more than 50
        throw new IllegalArgumentException("Value is out of range 0-50");
    }
    this.magicAmount = magicAmount;
}


问:
Editing MP3/Wav Files in a Flutter App (Dart)
Is it possible in a Flutter App to "concatenate" sound files without calling Swift/Java code to handle it for me? (Partially because I don't know Swift, and partially because I haven't figured out ffmpeg yet) The microphone provides either mp3 or wav files, and either works fine for me.

I'm attempting to make a Recording app that has more functionality than the ones I've previously found. Specifically, I want it to be able to pause the recording for an indefinite amount of time, and start again WITHOUT creating two files for the user to save -- it should combine them and save it later as a single file.

答:
You can take a look about this

medcorder_audio

and for splitting

audiocutter


问:
VsCode VIM - How to open "New Untitled File"
In VsCode VIM (vanilla installation), how would you execute Ctrl + N? When inspecting the keyboard shortcut, it looks like this:

I tried the plain way in VIM by running :new, but it opened a new tab within the same editor instead of a whole new tab.

Ideally, I'm looking for a plain way to do this without having to re-map any keys. I'm a big proponent of using vanilla tooling so I can easily transfer machine without having to carry around my re-mappings.

答: In vim, I use :enew to start a brand new file.


问:
Maven skipping dependency files?
I am using maven for my project. I have 5 local jar files as dependent files which i have specified in pom.xml as follows:

```<code>    <dependency>
    <groupId>EWSAPI</groupId>
    <artifactId>EWSAPI</artifactId>
    <version>1.1</version>
    <scope>system</scope>
    <systemPath>${basedir}/EWSAPI1.1.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>jcifs</groupId>
    <artifactId>jcifs</artifactId>
    <version>1.3.15</version>
    <scope>system</scope>
    <systemPath>${basedir}/jcifs-1.3.15.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.4</version>
    <scope>system</scope>
    <systemPath>${basedir}/commons-codec-1.4.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
    <scope>system</scope>
    <systemPath>${basedir}/commons-httpclient-3.1.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.1</version>
    <scope>system</scope>
    <systemPath>${basedir}/commons-logging-1.1.1.jar</systemPath>
    </dependency>
</code>```

Now, when i try mvn install in command prompt to install the dependencies. I get the following message

```<code>The following files where skipped:
   EWSAPI:EWSAPI:java-source:sources:1.1
   commons-codec:commons-codec:java-source:sources:1.4
   commons-httpclient:commons-httpclient:java-source:sources:3.1
   commons-logging:commons-logging:java-source:sources:1.1.1
</code>```

and also one file jfis was skipped(the same that was mentioned above as a dependency)

I do not understand why maven is doing so? I appreciate your help on this. Thanks

答:
Try something like this:

```<code><repositories>
    <repository>
        <id>my-internal-site</id>
        <url>file:///${basedir}</url>
    </repository>
</repositories>
</code>```

Then remove the system path argument.

Also, are you sure the scope should be system?

Title: Maven skipping dependency files?

Body:
I am using maven for my project. I have 5 local jar files as dependent files which i have specified in pom.xml as follows:

    <dependency>
    <groupId>EWSAPI</groupId>
    <artifactId>EWSAPI</artifactId>
    <version>1.1</version>
    <scope>system</scope>
    <systemPath>${basedir}/EWSAPI1.1.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>jcifs</groupId>
    <artifactId>jcifs</artifactId>
    <version>1.3.15</version>
    <scope>system</scope>
    <systemPath>${basedir}/jcifs-1.3.15.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.4</version>
    <scope>system</scope>
    <systemPath>${basedir}/commons-codec-1.4.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
    <scope>system</scope>
    <systemPath>${basedir}/commons-httpclient-3.1.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.1</version>
    <scope>system</scope>
    <systemPath>${basedir}/commons-logging-1.1.1.jar</systemPath>
    </dependency>

Now, when i try mvn install in command prompt to install the dependencies. I get the following message

The following files where skipped:
   EWSAPI:EWSAPI:java-source:sources:1.1
   commons-codec:commons-codec:java-source:sources:1.4
   commons-httpclient:commons-httpclient:java-source:sources:3.1
   commons-logging:commons-logging:java-source:sources:1.1.1

and also one file jfis was skipped(the same that was mentioned above as a dependency)

I do not understand why maven is doing so? I appreciate your help on this. Thanks

Body:
Try something like this:

<repositories>
    <repository>
        <id>my-internal-site</id>
        <url>file:///${basedir}</url>
    </repository>
</repositories>

Then remove the system path argument.

Also, are you sure the scope should be system?


问:
Twilio Test Credentials phone number not verified
I am busy writing integration tests for Twilio outbound calls.
Code has been written and all works fine, but want to ensure code coverage with tests.

Using Test Credentials provided and phone number: +15005550006 for the from number,

I get the following error: "Unable to create record: The source phone number provided, +15005550006, is not yet verified for your account. You may only make calls from phone numbers that you've verified or purchased from Twilio."

I have verified that I am using the test credentials to make the API call.

答:
I was no able to reproduce the issue. Are you using a non-trial account? If you are, my recommendation would be to open a ticket at help@twilio.com for further investigation of the issue, along with the full details to reproduce the issue.

How To Use Twilio Test Credentials with Magic Phone Numbers


问:
How can I extract three characters at a time from a Python string?
I want to write a function that takes a long string of characters (a protein sequence like 'UGGUGUUAUUAAUGGUUU') and extracts three characters at a time from it (i.e. the codons). It can either return each set of three characters one after another, or a list containing all the sets of three characters. Either way would work. But I'm having some trouble figuring out exactly how to do this cleanly.

Here's what I have so far:

```<code>def get_codon_list(codon_string):
    codon_start = 0
    codon_length = 3
    codon_end = 3
    codon_list = []
    for x in range(len(codon_string) // codon_length):
        codon_list.append(codon_string[codon_start:codon_end])
        codon_start += codon_length
        codon_end += codon_length
    return codon_list
</code>```

It works to return a list of the codons, but it seems very inefficient. I don't like using hard-coded numbers and incrementing variables like that if there is a better way. I also don't like using for loops that don't actually use the variable in the loop. It doesn't seem like a proper use of it.

Any suggestions for how to improve this, either with a specific function/module, or just a better Pythonic technique?

Thanks!

答:
The itertools grouper recipe is perfect for that (https://docs.python.org/3/library/itertools.html#itertools-recipes):

```<code>In [1]: from itertools import zip_longest

In [2]: def grouper(iterable, n, fillvalue=None):
   ...:     "Collect data into fixed-length chunks or blocks"
   ...:     # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
   ...:     args = [iter(iterable)] * n
   ...:     return zip_longest(*args, fillvalue=fillvalue)
   ...:

In [3]: list(grouper('UGGUGUUAUUAAUGGUUU', 3))
Out[3]:
[('U', 'G', 'G'),
 ('U', 'G', 'U'),
 ('U', 'A', 'U'),
 ('U', 'A', 'A'),
 ('U', 'G', 'G'),
 ('U', 'U', 'U')]
</code>```

Body:
I want to write a function that takes a long string of characters (a protein sequence like 'UGGUGUUAUUAAUGGUUU') and extracts three characters at a time from it (i.e. the codons). It can either return each set of three characters one after another, or a list containing all the sets of three characters. Either way would work. But I'm having some trouble figuring out exactly how to do this cleanly.

Here's what I have so far:

def get_codon_list(codon_string):
    codon_start = 0
    codon_length = 3
    codon_end = 3
    codon_list = []
    for x in range(len(codon_string) // codon_length):
        codon_list.append(codon_string[codon_start:codon_end])
        codon_start += codon_length
        codon_end += codon_length
    return codon_list

It works to return a list of the codons, but it seems very inefficient. I don't like using hard-coded numbers and incrementing variables like that if there is a better way. I also don't like using for loops that don't actually use the variable in the loop. It doesn't seem like a proper use of it.

Any suggestions for how to improve this, either with a specific function/module, or just a better Pythonic technique?

Thanks!

Body:
The itertools grouper recipe is perfect for that (https://docs.python.org/3/library/itertools.html#itertools-recipes):

In [1]: from itertools import zip_longest

In [2]: def grouper(iterable, n, fillvalue=None):
   ...:     "Collect data into fixed-length chunks or blocks"
   ...:     # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
   ...:     args = [iter(iterable)] * n
   ...:     return zip_longest(*args, fillvalue=fillvalue)
   ...:

In [3]: list(grouper('UGGUGUUAUUAAUGGUUU', 3))
Out[3]:
[('U', 'G', 'G'),
 ('U', 'G', 'U'),
 ('U', 'A', 'U'),
 ('U', 'A', 'A'),
 ('U', 'G', 'G'),
 ('U', 'U', 'U')]


问:
Sending data from MATLAB to Processing in real time?
Is there any way to send strings from one code to another while they're both running on the same machine? I'm trying to collect information using MATLAB and send a string whenever an event triggers. On Processing, I'm waiting for the string to be received before updating a GUI. I've been able to get both codes to work separately, but I'm having trouble figuring out how to actually send the information. Is it more viable to rebuild the GUI in Matlab?</p>

答:
Depending on the speed requirements of the real time communication, a low tech way of doing this is to use a common file where Matlab writes time-stamped data and Processing periodically checks the file for new data.

This is one way of doing interprocess communication between two independently running processes. Another, more reliable way, is to use some kind of socket communication (tcp or udp sockets, for example) between the two processes. But programming this might be fairly complicated if you are not fluent with both Matlab and Java.

A third way is that Matlab is actually capable of running Java code directly. So if you can call the Processing code from Matlab, then you might be able to pass the strings directly to your Processing code using Java method arguments, etc.


答:
You can use a list comprehension and get a slice of length 3 from the string at each time.</p>

```<code>>>> s="UGGUGUUAUUAAUGGUUU"
>>> res = [s[i:i+3] for i in range(0,len(s),3)]
>>> res
['UGG', 'UGU', 'UAU', 'UAA', 'UGG', 'UUU']
</code>```

Title: How can I extract three characters at a time from a Python string?

Body:
You can use a list comprehension and get a slice of length 3 from the string at each time.

>>> s="UGGUGUUAUUAAUGGUUU"
>>> res = [s[i:i+3] for i in range(0,len(s),3)]
>>> res
['UGG', 'UGU', 'UAU', 'UAA', 'UGG', 'UUU']


问:
GCP - DLP - Regex
Trying to process a BigQuery table with a custom infotype of RegEx variety.

RegEx I am using: ^(\d{5})$

In table below, I am trying to tag only against the "Codes" which are 5 digits. With the above RegEx, there are 0 matches.

With the following RegEx: \d{5}

It matches against all instances of 5 digits (including the two in Other)

How do I get it so that it only matches against 5 digits at the start of a "cell"(?) and ending with the 5th digit? Thanks a lot, been bogged down by this.

```
Name | Other     | Code
Blah | Test12345 | 12345
Bleh | 54311Test | 54311
```

答:
Try following RegEx:</p>

```<code>\b\d{5}\b
</code>```

Title: GCP - DLP - Regex

Body:
Trying to process a BigQuery table with a custom infotype of RegEx variety.

RegEx I am using: ^(\d{5})$

In table below, I am trying to tag only against the "Codes" which are 5 digits. With the above RegEx, there are 0 matches.

With the following RegEx: \d{5}

It matches against all instances of 5 digits (including the two in Other)

How do I get it so that it only matches against 5 digits at the start of a "cell"(?) and ending with the 5th digit? Thanks a lot, been bogged down by this.

Name | Other     | Code
Blah | Test12345 | 12345
Bleh | 54311Test | 54311

Body:
Try following RegEx:

\b\d{5}\b


问:
How to make visual studio highlight keywords
Here is a picture of how it looks now:

I had to reinstall visual studio and when I started programming I noticed something was off.
For example, GameObject and Vector3 used to be the same color as MouseLook. Update and OnDrawGizmos used to be some other color too.
Does anybody know how to revert that? It is so annoying like this. But it's not the only problem.

When I type Vector3. it ussualy lists me its components, for example Vector3.forward or left, right, zero, one and so on. It doesn't do that now.

Please help me with this :/

Thank you in advance.

答: The correct way to "fix" this is to get into unity, go under edit, preferences, external tools and under external script editor choose Visual Studio</p>


问:
How to get data once from firebase by ID
Hello im trying to get the user email of each message. (Each message (chat) have an userid).
I get the whole user data throught getUser on the *ngIf. And then just show the email. It works and on the website there isn't any repeat of data, but the tab soon freezes unless I don't pause with debugger. I don't know why but it makes an infinite loop.
It looks like this: https://i.imgur.com/XBku0uc.png It makes thousands of console logs.

This is getUser:

```<code>  getUser(uid:string){
    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));
    this.userCollection.valueChanges().subscribe(queriedItems => {
      this.userDT=new Usermodel(queriedItems[0].uid,queriedItems[0].email,queriedItems[0].displayName,queriedItems[0].photoURL,queriedItems[0].emailVerified);
    });
    console.log(this.userDT.email)
    return this.userDT;
  }
</code>```

and I get the data in the HTML calling it directly:

```<code><div class="msg_container_other" *ngIf="getUser(chat.uid); let otherUser">
                  {{chat.content}}
                  <span class="msg_time"><i class="fas fa-check-double" style="color: #292929;"></i> {{otherUser.email}}. {{ chat.date | date:'d/M/y H:mm'}}</span>
</div>
</code>```

If you need to see what is chats: https://i.imgur.com/iThi424.png and more context on html:https://i.imgur.com/GRupLAp.png

I've been several days trying things and don't know what else to try.
If I remove the subscription of getUser like this:

```<code>  getUser(uid:string){
    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));

    console.log(this.userDT.email)
    return this.userDT;
  }
</code>```

Then it doesn't loops, but of course can't get data then.

People have told me that isn't the good way to get data once because im subscribing so I tried this way but have same effect infinite loop.

```<code>    getUser(uid:string){

    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));
    this.userCollection.get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data().email);
            return doc.data().email;
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });
}
</code>```

This getUser doesn't works either it also makes infinite loop :/ cant believe i cant find how to get a single data by query

```<code>     return this.db.collection('users', ref => ref.where('uid', '==', uid)).snapshotChanges().subscribe(data => {
    return data.map(e => {
      return {
        id: e.payload.doc.id,
        ...e.payload.doc.data()
      } as User;
    })
  });
</code>```

EDIT:

Okay I think I tried to do it better, this is how I go throught the chats now:
https://i.imgur.com/oJAJDGA.png

```<code>   db.collection('chats', ref => ref.where('groupId', '==', this.pathId).orderBy('date')).snapshotChanges().subscribe(data => {
  this.chatsList = data.map(e => {
    return {
      id: e.payload.doc.id,
      ...e.payload.doc.data()
    } as Chat;
  })
});
</code>```

And this is the html with new change:

```<code>    <div class="card" *ngIf="authService.userData as user">

        <div id="card-box" class="card-box msg_head" ><!--  #scrollMe [scrollTop]="scrollMe.scrollHeight" DA ERROR  -->

            <div id="card-body" class="card-body msg_card_body">
              <div *ngFor="let chat of chatsList">
</code>```

Still can't make it to get the userdata by userid from chat uid without infinite loop tho

EDIT2:
Okay I think I understand better how the asyncronous thing works and I was trying to build a frankenstein, Ill update this when I build it in another way.

EDIT3:
Ok I fixed this by getting everything asyncronous (as it have to be) and doing a JOIN:

```<code>getPages(){
  const item: AngularFirestoreCollection = this.afs.collection(`pages`, (ref) => ref.orderBy('createdAt', 'desc'));
  return item.valueChanges().pipe(
  switchMap(arr => {
   const userObservable = arr.map(user => this._afs.doc(`users/${user.uid}`) .valueChanges().pipe(first()) );
   return combineLatest(...userObservable) .pipe( map((...users) => {
      arr.forEach((author, index) => {
       author['author_avatar'] = users[0][index]['photoURL'];
       author['author_username'] = users[0][index]['displayName'];
      });
      return arr;
      })
      );
    })
    );
   }
</code>```

答:
if you want to just make it work try any of your getUser(id) implementations, but instead of binding function it in the template - call it in ngOnInit, and bind the returned result instead.

```<code>ngOnInit() {
  this.getUser(someId);
}
....
*ngIf="userDT"
</code>```

but really you have problems with understanding js asynchronious concepts and how to handle such situations and simple stackoverflow answer won't help to understand it better

Body:
Hello im trying to get the user email of each message. (Each message (chat) have an userid).
I get the whole user data throught getUser on the *ngIf. And then just show the email. It works and on the website there isn't any repeat of data, but the tab soon freezes unless I don't pause with debugger. I don't know why but it makes an infinite loop.
It looks like this: https://i.imgur.com/XBku0uc.png It makes thousands of console logs.

This is getUser:

  getUser(uid:string){
    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));
    this.userCollection.valueChanges().subscribe(queriedItems => {
      this.userDT=new Usermodel(queriedItems[0].uid,queriedItems[0].email,queriedItems[0].displayName,queriedItems[0].photoURL,queriedItems[0].emailVerified);
    });
    console.log(this.userDT.email)
    return this.userDT;
  }

and I get the data in the HTML calling it directly:

                  {{chat.content}}
                   {{otherUser.email}}. {{ chat.date | date:'d/M/y H:mm'}}

If you need to see what is chats: https://i.imgur.com/iThi424.png and more context on html:https://i.imgur.com/GRupLAp.png

I've been several days trying things and don't know what else to try.
If I remove the subscription of getUser like this:

  getUser(uid:string){
    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));

    console.log(this.userDT.email)
    return this.userDT;
  }

Then it doesn't loops, but of course can't get data then.

People have told me that isn't the good way to get data once because im subscribing so I tried this way but have same effect infinite loop.

    getUser(uid:string){

    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));
    this.userCollection.get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data().email);
            return doc.data().email;
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });
}

This getUser doesn't works either it also makes infinite loop :/ cant believe i cant find how to get a single data by query

     return this.db.collection('users', ref => ref.where('uid', '==', uid)).snapshotChanges().subscribe(data => {
    return data.map(e => {
      return {
        id: e.payload.doc.id,
        ...e.payload.doc.data()
      } as User;
    })
  });

EDIT:

Okay I think I tried to do it better, this is how I go throught the chats now:
https://i.imgur.com/oJAJDGA.png

   db.collection('chats', ref => ref.where('groupId', '==', this.pathId).orderBy('date')).snapshotChanges().subscribe(data => {
  this.chatsList = data.map(e => {
    return {
      id: e.payload.doc.id,
      ...e.payload.doc.data()
    } as Chat;
  })
});

And this is the html with new change:

Still can't make it to get the userdata by userid from chat uid without infinite loop tho

EDIT2:
Okay I think I understand better how the asyncronous thing works and I was trying to build a frankenstein, Ill update this when I build it in another way.

EDIT3:
Ok I fixed this by getting everything asyncronous (as it have to be) and doing a JOIN:

getPages(){
  const item: AngularFirestoreCollection = this.afs.collection(`pages`, (ref) => ref.orderBy('createdAt', 'desc'));
  return item.valueChanges().pipe(
  switchMap(arr => {
   const userObservable = arr.map(user => this._afs.doc(`users/${user.uid}`) .valueChanges().pipe(first()) );
   return combineLatest(...userObservable) .pipe( map((...users) => {
      arr.forEach((author, index) => {
       author['author_avatar'] = users[0][index]['photoURL'];
       author['author_username'] = users[0][index]['displayName'];
      });
      return arr;
      })
      );
    })
    );
   }

Body:
if you want to just make it work try any of your getUser(id) implementations, but instead of binding function it in the template - call it in ngOnInit, and bind the returned result instead.

ngOnInit() {
  this.getUser(someId);
}
....
*ngIf="userDT"

but really you have problems with understanding js asynchronious concepts and how to handle such situations and simple stackoverflow answer won't help to understand it better


问:
How to keep binary values in a Factor Variable?
I'm performing a toy example logistic regression.
What I would like to do is: keep the factor variable a_fac performing as a binary variable.

Here's my code:

```<code>set.seed(8)
a = rbinom( n = 10, size = 1, prob = 0.5)
d = seq(1:length(a))

a_fac = factor(a, labels=c("class1", "class2"))
plot(d, a_fac)

##Logistic Regression
lr = glm(a_fac~d, family=binomial(link="logit"))       ##cannot perform the log regression with factor var.
lr = glm(a~d, family=binomial(link="logit"))

##plotting
plot(d,a_fac, main = "logistic regression",  ylim = c(0,2))
lines(d,lr$fitted.values)

##this is the correct plot i want to obtain with the factor variable
plot(d,a, main = "logistic regression")
lines(d,lr$fitted.values)
</code>```

Can I do this or I have to keep object of the same variable? Thank You

答:
I guess you need to convert factor to numeric for glm, i.e.,

```<code>glm(as.numeric(a_fac)-1~d)
</code>```

such that

```<code>> glm(as.numeric(a_fac)-1~d)

Call:  glm(formula = as.numeric(a_fac) - 1 ~ d)

Coefficients:
(Intercept)            d
    0.13333      0.08485

Degrees of Freedom: 9 Total (i.e. Null);  8 Residual
Null Deviance:      2.4
Residual Deviance: 1.806    AIC: 17.26
</code>```

Body:
I'm performing a toy example logistic regression.
What I would like to do is: keep the factor variable a_fac performing as a binary variable.

Here's my code:

set.seed(8)
a = rbinom( n = 10, size = 1, prob = 0.5)
d = seq(1:length(a))

a_fac = factor(a, labels=c("class1", "class2"))
plot(d, a_fac)

##Logistic Regression
lr = glm(a_fac~d, family=binomial(link="logit"))       ##cannot perform the log regression with factor var.
lr = glm(a~d, family=binomial(link="logit"))

##plotting
plot(d,a_fac, main = "logistic regression",  ylim = c(0,2))
lines(d,lr$fitted.values)

##this is the correct plot i want to obtain with the factor variable
plot(d,a, main = "logistic regression")
lines(d,lr$fitted.values)

Can I do this or I have to keep object of the same variable? Thank You

Body:
I guess you need to convert factor to numeric for glm, i.e.,

glm(as.numeric(a_fac)-1~d)

such that

> glm(as.numeric(a_fac)-1~d)

Call:  glm(formula = as.numeric(a_fac) - 1 ~ d)

Coefficients:
(Intercept)            d
    0.13333      0.08485

Degrees of Freedom: 9 Total (i.e. Null);  8 Residual
Null Deviance:      2.4
Residual Deviance: 1.806    AIC: 17.26


答:
You can simply use the step argument of the range function to avoid maintaining the variables:

```<code>def get_codon_list(codon_string):
    codon_length = 3
    codon_list = []

    for codon_start in range(0, len(codon_string), codon_length):
        codon_end = codon_start + codon_length
        codon_list.append(codon_string[codon_start:codon_end])

    return codon_list
</code>```

And then it can become as a list-comprehension:

```<code>def get_codon_list(codon_string):
    codon_length = 3

    codon_list = [codon_string[x:x+codon_length] for x in range(0, len(codon_string), codon_length)]

    return codon_list
</code>```

Body:
You can simply use the step argument of the range function to avoid maintaining the variables:

def get_codon_list(codon_string):
    codon_length = 3
    codon_list = []

    for codon_start in range(0, len(codon_string), codon_length):
        codon_end = codon_start + codon_length
        codon_list.append(codon_string[codon_start:codon_end])

    return codon_list

And then it can become as a list-comprehension:

def get_codon_list(codon_string):
    codon_length = 3

    codon_list = [codon_string[x:x+codon_length] for x in range(0, len(codon_string), codon_length)]

    return codon_list