问:
'Future<String>' can't be assigned to the parameter type 'String'
I am trying to complete this app that shows the exchange rates for specific cryptocurrencies by calling an async function.
I try to display the exchange rate as a property in a seperate stateless widget.

The argument type 'Future<String>' can't be assigned to the parameter type 'String'.

This is how I am trying to use it.

How can I make this work?

```<code>  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(' Coin Ticker'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            children: [
              TheEntireCard(
                output: getExchange('BTC'),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(18.0, 18.0, 18.0, 0),
                child: Card(
                  color: Colors.lightBlueAccent,
                  elevation: 5.0,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                        vertical: 15.0, horizontal: 28.0),
                    child: Text(
                      '1 BTC = $rate $selectedCurrency',
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                        fontSize: 20.0,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(18.0, 18.0, 18.0, 0),
                child: Card(
                  color: Colors.lightBlueAccent,
                  elevation: 5.0,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                        vertical: 15.0, horizontal: 28.0),
                    child: Text(
                      '1 BTC = $rate $selectedCurrency',
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                        fontSize: 20.0,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
          Container(
            height: 150.0,
            alignment: Alignment.center,
            padding: const EdgeInsets.only(bottom: 30.0),
            color: Colors.lightBlue,
            // For iOS, use the cupertino picker to achieve that iOS specific look on the scroller. https://docs.flutter.dev/development/ui/widgets/cupertino
            child:
                Platform.isIOS ? getCupertinoPickerItems() : getDropDownItems(),
          )
        ],
      ),
    );
  }

Future<String> getExchange(String cryptoName) async {
    var theText;
    try {
      final String data = await CoinData().getExchangeData( //<--getting data from crypto api
        theCurrency: selectedCurrency, //
        theCryptoName: cryptoName,
      );
      setState(() {
        rate = data;
        theText = '1 $cryptoName = $rate $selectedCurrency';
      });
    } catch (e) {
      print(e);
    }
    return theText;
  }

class TheEntireCard extends StatelessWidget {
  const TheEntireCard({
    Key? key,
    required this.output,
  }) : super(key: key);
  final String output;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(18.0, 18.0, 18.0, 0),
      child: Card(
        color: Colors.lightBlueAccent,
        elevation: 5.0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10.0),
        ),
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 15.0, horizontal: 28.0),
          child: Text(
            output,
            textAlign: TextAlign.center,
            style: const TextStyle(
              fontSize: 20.0,
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }
}

</code>```

答:
In an async function the return type it's a Future.

You can add an await in front of the call, as: await getExchange('BTC') and that will return a String instead of a Future<String>.

But you cannot call an async function into the build(). That's why you should use a FutureBuilder.
An example:

```<code>//The code you had above TheEntireCard

FutureBuilder<String>(
  future: getExchange('BTC'),
  builder:
      (BuildContext context, AsyncSnapshot<String> snapshot) {
    if (snapshot.hasData) {
      final theText = snapshot.data
      TheEntireCard(
            output: theText ?? "",
          ),
    }
    return const CircularProgressIndicator() //While awaiting show the loading indicator
  },
),

//The code you had under TheEntireCard
</code>```

Body:
I am trying to complete this app that shows the exchange rates for specific cryptocurrencies by calling an async function.
I try to display the exchange rate as a property in a seperate stateless widget.

The argument type 'Future<String>' can't be assigned to the parameter type 'String'.

This is how I am trying to use it.

How can I make this work?

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(' Coin Ticker'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            children: [
              TheEntireCard(
                output: getExchange('BTC'),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(18.0, 18.0, 18.0, 0),
                child: Card(
                  color: Colors.lightBlueAccent,
                  elevation: 5.0,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                        vertical: 15.0, horizontal: 28.0),
                    child: Text(
                      '1 BTC = $rate $selectedCurrency',
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                        fontSize: 20.0,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(18.0, 18.0, 18.0, 0),
                child: Card(
                  color: Colors.lightBlueAccent,
                  elevation: 5.0,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                        vertical: 15.0, horizontal: 28.0),
                    child: Text(
                      '1 BTC = $rate $selectedCurrency',
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                        fontSize: 20.0,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
          Container(
            height: 150.0,
            alignment: Alignment.center,
            padding: const EdgeInsets.only(bottom: 30.0),
            color: Colors.lightBlue,
            // For iOS, use the cupertino picker to achieve that iOS specific look on the scroller. https://docs.flutter.dev/development/ui/widgets/cupertino
            child:
                Platform.isIOS ? getCupertinoPickerItems() : getDropDownItems(),
          )
        ],
      ),
    );
  }

Future<String> getExchange(String cryptoName) async {
    var theText;
    try {
      final String data = await CoinData().getExchangeData( //<--getting data from crypto api
        theCurrency: selectedCurrency, //
        theCryptoName: cryptoName,
      );
      setState(() {
        rate = data;
        theText = '1 $cryptoName = $rate $selectedCurrency';
      });
    } catch (e) {
      print(e);
    }
    return theText;
  }

class TheEntireCard extends StatelessWidget {
  const TheEntireCard({
    Key? key,
    required this.output,
  }) : super(key: key);
  final String output;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(18.0, 18.0, 18.0, 0),
      child: Card(
        color: Colors.lightBlueAccent,
        elevation: 5.0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10.0),
        ),
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 15.0, horizontal: 28.0),
          child: Text(
            output,
            textAlign: TextAlign.center,
            style: const TextStyle(
              fontSize: 20.0,
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }
}

Body:
In an async function the return type it's a Future.

You can add an await in front of the call, as: await getExchange('BTC') and that will return a String instead of a Future<String>.

But you cannot call an async function into the build(). That's why you should use a FutureBuilder.
An example:

//The code you had above TheEntireCard

FutureBuilder<String>(
  future: getExchange('BTC'),
  builder:
      (BuildContext context, AsyncSnapshot<String> snapshot) {
    if (snapshot.hasData) {
      final theText = snapshot.data
      TheEntireCard(
            output: theText ?? "",
          ),
    }
    return const CircularProgressIndicator() //While awaiting show the loading indicator
  },
),

//The code you had under TheEntireCard


来源: stackexchange

问:
Compiler says variable is undeclared even though it is declared
when i try to run this code i get the error: error: 'list1' undeclared (first use in this function). But i have declared the variable in main(), I also tried declaring it at the top, under text1,text2 and count. But then it said "initialzer element not constant". I've tried googling it but with no luck. btw the code isn't finished yet but i cant get past this error and just want to fix it.
Thank you</p>
```<code>#include <stdio.h>
#include <stdlib.h>

char *text1 = "This is a string.";
char *text2 = "Yet another thing.";
int *count = 0;

void printlist(const int* lst){
  printf("ASCII codes and corresponding characters.\n");
  while(*lst != 0){
    printf("0x%03X '%c' ", *lst, (char)*lst);
    lst++;
  }
  printf("\n");
}

void endian_proof(const char* c){
  printf("\nEndian experiment: 0x%02x,0x%02x,0x%02x,0x%02x\n",
         (int)*c,(int)*(c+1), (int)*(c+2), (int)*(c+3));

}

void copycodes(char *text, int *list, int *counter){
    while(*text != 0){
        *list = *text;
        list++;
        text++;
    }
}

void work(){
    copycodes(&text1, &list1, &count);
}

int main(void){
  int *list1 = (int *)(malloc(80));
  int *list2 = (int *)(malloc(80));
  work();

  printf("\nlist1: ");
  printlist(list1);
  printf("\nlist2: ");
  printlist(list2);
  printf("\nCount = %d\n", count);

  endian_proof((char*) &count);
}
</code>```

答:
As @EugeneSh. said, the variables list1 and list2 are local to main(), and thus aren't in scope for the other functions. While you could make the globals by simply initializing them to NULL and then setting them in main(), it would make more sense to pass list1 as an argument to work():

```<code>void work(int* list){
    copycodes(text1, list, count);
}
</code>```

A few things to take note of:

You do not need or want to cast the return value from malloc() (or calloc() for that matter). This is an exception to the usual rule regarding casting pointers.

As @melonduofromage said, you would need to use the sizeof(int) to tell malloc() how large the elements being allocated are. Conversely, you could use calloc() instead, which is specifically meant to allocate arrays.

list1 = calloc(20, sizeof(int));

When passing a pointer to a function which accepts a pointer argument, you do not want or need to use the reference (&) operator for the pointer in question. That would only be needed if you were passing a pointer to a pointer argument.

As a general rule, it is better to avoid globals unless the alternative is more confusing. In this case, you would need to pass more arguments to various functions, but the improved decomposition would make it worth it IMAO.

Also as a general rule, if you find yourself using the pattern var1, var2, var3... varN, then you should should either bundle the variables into an array if they are related to each other, or else find more descriptive names if they are not.

ContentLicense: CC BY-SA 4.0

Body:
when i try to run this code i get the error: error: 'list1' undeclared (first use in this function). But i have declared the variable in main(), I also tried declaring it at the top, under text1,text2 and count. But then it said "initialzer element not constant". I've tried googling it but with no luck. btw the code isn't finished yet but i cant get past this error and just want to fix it.
Thank you

#include <stdio.h>
#include <stdlib.h>

char *text1 = "This is a string.";
char *text2 = "Yet another thing.";
int *count = 0;

void printlist(const int* lst){
  printf("ASCII codes and corresponding characters.\n");
  while(*lst != 0){
    printf("0x%03X '%c' ", *lst, (char)*lst);
    lst++;
  }
  printf("\n");
}

void endian_proof(const char* c){
  printf("\nEndian experiment: 0x%02x,0x%02x,0x%02x,0x%02x\n",
         (int)*c,(int)*(c+1), (int)*(c+2), (int)*(c+3));

}

void copycodes(char *text, int *list, int *counter){
    while(*text != 0){
        *list = *text;
        list++;
        text++;
    }
}

void work(){
    copycodes(&text1, &list1, &count);
}

int main(void){
  int *list1 = (int *)(malloc(80));
  int *list2 = (int *)(malloc(80));
  work();

  printf("\nlist1: ");
  printlist(list1);
  printf("\nlist2: ");
  printlist(list2);
  printf("\nCount = %d\n", count);

  endian_proof((char*) &count);
}

Body:
As @EugeneSh. said, the variables list1 and list2 are local to main(), and thus aren't in scope for the other functions. While you could make the globals by simply initializing them to NULL and then setting them in main(), it would make more sense to pass list1 as an argument to work():

void work(int* list){
    copycodes(text1, list, count);
}

A few things to take note of:

You do not need or want to cast the return value from malloc() (or calloc() for that matter). This is an exception to the usual rule regarding casting pointers.

As @melonduofromage said, you would need to use the sizeof(int) to tell malloc() how large the elements being allocated are. Conversely, you could use calloc() instead, which is specifically meant to allocate arrays.

list1 = calloc(20, sizeof(int));

When passing a pointer to a function which accepts a pointer argument, you do not want or need to use the reference (&) operator for the pointer in question. That would only be needed if you were passing a pointer to a pointer argument.

As a general rule, it is better to avoid globals unless the alternative is more confusing. In this case, you would need to pass more arguments to various functions, but the improved decomposition would make it worth it IMAO.

Also as a general rule, if you find yourself using the pattern var1, var2, var3... varN, then you should should either bundle the variables into an array if they are related to each other, or else find more descriptive names if they are not.


问:
rules with temporary objects and args by reference
say I have a class:

```<code>class A
{
 public:
 A() {}
};
</code>```

and a function:

```<code>void x(const A & s) {}
</code>```

and I do:

```<code>x(A());
</code>```

could someone please explain to me the rules regarding passing temporary objects by reference? In terms of what the compiler allows, where you need const, if an implicit copy happens, etc. From playing around, it seems like you need the const which makes sense, but is there a formal rule regarding all this?

Thanks!

答: There is a formal rule - the C++ Standard (section 13.3.3.1.4 if you are interested) states that a temporary can only be bound to a const reference - if you try to use a non-const reference the compiler must flag this as an error.</p>

OwnerDisplayName: Steve

ContentLicense: CC BY-SA 2.5

Body:
say I have a class:

class A
{
 public:
 A() {}
};

and a function:

void x(const A & s) {}

and I do:

x(A());

could someone please explain to me the rules regarding passing temporary objects by reference? In terms of what the compiler allows, where you need const, if an implicit copy happens, etc. From playing around, it seems like you need the const which makes sense, but is there a formal rule regarding all this?

Thanks!

OwnerDisplayName: anon


问:
TextField clear button
I have 5 textField popovers that are all dependant on each other. The value in the first field sets what will show in popover for second field and so on...

If the user removes one of the fields, I want to be able to clear all fields following that are linked to this field. I started by using the textFieldShouldClear method, but I can't seem to figure out how to tell it which textField is being cleared. It either clears everything, or doesn't clear at all.

Thanks

答:
It sounds like your textFields are set up in IB, which means you can declare 5 IBOutlet UITextField objects in your header file and hook these up to the fields in IB. Then in your delegate method, you can do something like this:

```<code>- (BOOL)textFieldShouldClear:(UITextField *)textField {
    if([textField isEqual:myField1]) {
        myField2.text=@"";
        myField3.text=@"";
        ...
    }
    else if([textField isEqual:myField2]) {
        myField3.text=@"";
        ...
    }
     //etc....
    return YES;
}
</code>```

Hope this helps!

ContentLicense: CC BY-SA 3.0

Title: TextField clear button

Body:
It sounds like your textFields are set up in IB, which means you can declare 5 IBOutlet UITextField objects in your header file and hook these up to the fields in IB. Then in your delegate method, you can do something like this:

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    if([textField isEqual:myField1]) {
        myField2.text=@"";
        myField3.text=@"";
        ...
    }
    else if([textField isEqual:myField2]) {
        myField3.text=@"";
        ...
    }
     //etc....
    return YES;
}

Hope this helps!


问:
Concatenating Matrices in R
How can I concatenate matrices of same columns but different number of rows? For example, I
want to concatenate a (dim(a) = 15 7000) and b (dim(b) = 16 7000) and I want the result to be a matrix of 31 rows by 7000 columns.

Can I also do this for matrices with a different number of rows and columns? Say I want to combine a matrix of 15 rows and 7000 columns with another of 16 rows and 7500 columns. Can I create one dataset with that?

答:
Others have addressed the matter of concatenating two matrices:

horizontally with cbind (the "c" stands for "column", so you are binding the columns of the two matrices); or

vertically with rbind (the "r" stands for "row", so you are binding the rows of the two matrices).

What others haven't pointed out explicitly is that:

because cbind binds columns, the two matrices have to have the same number of rows: cbind builds a matrix that is wider, but it needs the "height" (# of rows) of the two matrices to match; and

because rbind binds rows, the two matrices have to have the same number of columns: rbind builds a matrix that is taller, but it needs the "width" (# of columns) of the two matrices to match.

Take a look at this:

```<code>> A <- matrix(nrow = 3, ncol = 4)
> B <- matrix(nrow = 3, ncol = 5)
> C <- matrix(nrow = 4, ncol = 5)
> D <- cbind(A, B)  # Works because A and B have same # of rows
> cbind(A, C)       # Fails
Error in cbind(A, C) : number of rows of matrices must match (see arg 2)
> E <- rbind(B, C)  # Works because B and C have same # of columns
> rbind(A, C)       # Fails
Error in rbind(A, C) :
  number of columns of matrices must match (see arg 2)
</code>```

So, no, you cannot put together two matrices if they have a different number of rows and a different number of columns.
You would need to do something to either one of the matrices first, to make sure that their shapes become compatible for concatenation.

Title: Concatenating Matrices in R

Body:
Others have addressed the matter of concatenating two matrices:

horizontally with cbind (the "c" stands for "column", so you are binding the columns of the two matrices); or

vertically with rbind (the "r" stands for "row", so you are binding the rows of the two matrices).

What others haven't pointed out explicitly is that:

because cbind binds columns, the two matrices have to have the same number of rows: cbind builds a matrix that is wider, but it needs the "height" (# of rows) of the two matrices to match; and

because rbind binds rows, the two matrices have to have the same number of columns: rbind builds a matrix that is taller, but it needs the "width" (# of columns) of the two matrices to match.

Take a look at this:

> A <- matrix(nrow = 3, ncol = 4)
> B <- matrix(nrow = 3, ncol = 5)
> C <- matrix(nrow = 4, ncol = 5)
> D <- cbind(A, B)  # Works because A and B have same # of rows
> cbind(A, C)       # Fails
Error in cbind(A, C) : number of rows of matrices must match (see arg 2)
> E <- rbind(B, C)  # Works because B and C have same # of columns
> rbind(A, C)       # Fails
Error in rbind(A, C) :
  number of columns of matrices must match (see arg 2)

So, no, you cannot put together two matrices if they have a different number of rows and a different number of columns.
You would need to do something to either one of the matrices first, to make sure that their shapes become compatible for concatenation.


问:
ERROR: JAVA_HOME is set to an invalid directory: /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home

here is my error that showing when i run ./gradle --version

here is my java -version 17.0.2 that is set.

答: Have a look at the PATH environment variable. It should contain the path to your Java installation. After finding the installation directory set your JAVA_HOME environment variable to this path (but without the trailing /bin).


问:
Kendo UI waterfall custom data
I 'd created a waterfall with similar to waterfall chart given in the demo section. I would like to add a Running time at the end of the chart with value starting from 0.

Please find here the dojo https://dojo.telerik.com/EgABaJiR/2

Required output is like in the image below

答:
Not quite sure about your question. I don't understand what you mean by "I would like to add a net time at the end of the chart with value starting from 0." But based on your image, I'm guessing you want the column upside down and hitting the 0 axis. On that note, you can try these as the last value in your cashFlowData:

{ "name": "Running Time", "summary": "total" }

{ "name": "Running Time", "druation": -12.5 }

{ "name": "Running Time", "summary": "runningTotal" }

All 3 will hit the 0 axis.

Thank you for your quick answer. But my question is to add the running time at the end, i mean after net time. and it has its own value (15hrs according to my demo) and it should start from 0 axis. Moreover, Summary: total and runningtotal will actually sum from previous column(s). I dont want to sum it from the previous columns

Since this is a waterfall chart then you need to make the last column to zero in order for the 15hrs to start at the zero axis. So a trick would be to make the last values of cashFlowData as follows:

```<code>{
  "name": "Net Time",
  "summary": "total"
},
{
  "name": "Running Time",
  "druation": -12.5,
},
{
  "name": "from zero",
  "druation": 15
}
</code>```

With the above, you'll have 15hrs starting from zero. But I'm guessing you don't want -12.5 rendered. So I'd probably implement something in series.visual saying if name equals Running Time then do not draw. You get the idea?

Title: Kendo UI waterfall custom data

Body:
Not quite sure about your question. I don't understand what you mean by "I would like to add a net time at the end of the chart with value starting from 0." But based on your image, I'm guessing you want the column upside down and hitting the 0 axis. On that note, you can try these as the last value in your cashFlowData:

{ "name": "Running Time", "summary": "total" }

{ "name": "Running Time", "druation": -12.5 }

{ "name": "Running Time", "summary": "runningTotal" }

All 3 will hit the 0 axis.

Thank you for your quick answer. But my question is to add the running time at the end, i mean after net time. and it has its own value (15hrs according to my demo) and it should start from 0 axis. Moreover, Summary: total and runningtotal will actually sum from previous column(s). I dont want to sum it from the previous columns

Since this is a waterfall chart then you need to make the last column to zero in order for the 15hrs to start at the zero axis. So a trick would be to make the last values of cashFlowData as follows:

{
  "name": "Net Time",
  "summary": "total"
},
{
  "name": "Running Time",
  "druation": -12.5,
},
{
  "name": "from zero",
  "druation": 15
}

With the above, you'll have 15hrs starting from zero. But I'm guessing you don't want -12.5 rendered. So I'd probably implement something in series.visual saying if name equals Running Time then do not draw. You get the idea?


问:
help with drawing a wedge with opengl es
I'm trying to do some basic opengl es programming to get started on the basics.

I have a drawing function tries to draw a wedge of a circle. Something is going wrong because its actually just drawing a circle.

I'm still just trying to grasp the basics of opengl es here. Heres what I have so far.

```<code>- (void)drawView

{
    [EAGLContext setCurrentContext:context];

    glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
    glViewport(0, 0, 60, 60);

    int i;
    float angle_start=90;
    float angle_stop=180;
    int segments=360;
    float const angle_step = (angle_stop - angle_start)/segments;

    GLfloat *arc_vertices;
    arc_vertices = malloc(2*sizeof(GLfloat) * (segments+2));

    arc_vertices[0] = arc_vertices[1] = 0.0;

    for(i=0; i<segments+1; i++) {
        arc_vertices[2 + 2*i    ] = cos(angle_start + i*angle_step);
        arc_vertices[2 + 2*i + 1] = sin(angle_start + i*angle_step);
    }
    glVertexPointer(2, GL_FLOAT, 0, arc_vertices);
    glEnableClientState(GL_VERTEX_ARRAY);
    glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
    glDrawArrays(GL_TRIANGLE_FAN, 0, segments+2);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
    [context presentRenderbuffer:GL_RENDERBUFFER_OES];
    free(arc_vertices);

}
</code>```

答:
I see something wrong. You access vertices[i] and vertices[i+1], but i always increments by 1.

Try replacing

GLfloat vertices[720];

with

GLfloat vertices[2*720];

and replace

vertices[i]=p1;
  vertices[i+1]=p2;

by

vertices[2*i]=p1;
  vertices[2*i+1]=p2;

Body:
I'm trying to do some basic opengl es programming to get started on the basics.

I have a drawing function tries to draw a wedge of a circle. Something is going wrong because its actually just drawing a circle.

I'm still just trying to grasp the basics of opengl es here. Heres what I have so far.

- (void)drawView

{
    [EAGLContext setCurrentContext:context];

    glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
    glViewport(0, 0, 60, 60);

    int i;
    float angle_start=90;
    float angle_stop=180;
    int segments=360;
    float const angle_step = (angle_stop - angle_start)/segments;

    GLfloat *arc_vertices;
    arc_vertices = malloc(2*sizeof(GLfloat) * (segments+2));

    arc_vertices[0] = arc_vertices[1] = 0.0;

    for(i=0; i<segments+1; i++) {
        arc_vertices[2 + 2*i    ] = cos(angle_start + i*angle_step);
        arc_vertices[2 + 2*i + 1] = sin(angle_start + i*angle_step);
    }
    glVertexPointer(2, GL_FLOAT, 0, arc_vertices);
    glEnableClientState(GL_VERTEX_ARRAY);
    glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
    glDrawArrays(GL_TRIANGLE_FAN, 0, segments+2);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
    [context presentRenderbuffer:GL_RENDERBUFFER_OES];
    free(arc_vertices);

}


问:
Using gglocator() within another function
I'm trying to use gglocator() within a function that looks like this:

```<code>my_function<- function(point_num) {

 x11()

 iris %>%
   ggplot()+
     aes(Sepal.Width,Sepal.Length)+
     geom_point()

 points <- gglocator(n = point_num, mercator = FALSE)

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

which gives me the error: Error in gglocator(n = point_num, mercator = FALSE) :  ggplot graphic not detected in current device

It works fine if I do it line by line outside the function.
What am I missing?

答:
Running ggplot inside a function doesn't automatically print the produced ggplot object the way it does in the console.

Remember that in an interactive session in the console, any object returned by the code you type will be automatically printed: if you type sum(1:5) in the console, then the result [1] 15 is printed to the console. However, if you randomly include the line sum(1:5) in the middle of a function, it will have no effect and the result is not printed. The same is true of ggplot objects.

So the solution is to wrap your plotting code in an explicit call to print:

library(ggmap)

my_function<- function(point_num) {

 x11()

 print(iris %>%
   ggplot()+
     aes(Sepal.Width,Sepal.Length)+
     geom_point())

 points <- gglocator(n = point_num, mercator = FALSE)

 return(points)
}

my_function(1)

#>   Sepal.Width Sepal.Length
#> 1    2.707581     5.196849
```

Body:
I'm trying to use gglocator() within a function that looks like this:

my_function<- function(point_num) {

 x11()

 iris %>%
   ggplot()+
     aes(Sepal.Width,Sepal.Length)+
     geom_point()

 points <- gglocator(n = point_num, mercator = FALSE)

 return(points)
}

which gives me the error: Error in gglocator(n = point_num, mercator = FALSE) :  ggplot graphic not detected in current device

It works fine if I do it line by line outside the function.
What am I missing?


问:
How to transform a string into a list of char and int using a list comprehension in Python
Given the following string:

```<code>"[10,20]"
</code>```

I want to create the following list using a list comprehension in Python:

```<code>['[', 10, ',', 20, ']']
</code>```

Being 10 and 20 integers and the rest of the elements in the list chars.

I assume that I would need a to use something similar to what itertools.groupby(iterable, key=None) provides:

Make an iterator that returns consecutive keys and groups from the
iterable. The key is a function computing a key value for each
element. If not specified or is None, key defaults to an identity
function and returns the element unchanged. Generally, the iterable
needs to already be sorted on the same key function.

However Python's group by returns an iterator with consecutive keys and groups. In my case the keys would change so I guess I'd need a similar iterator that returns the groups based on a filter. Any ideas?

答:
This can also be done with regex with ease.

```<code>import re

NUMCHR = re.compile(r'\d+|[^\d]') #consecutive digits OR one "not-a-digit"
data   = '[10,20]'
out    = [int(m[0]) if m[0].isdigit() else m[0] for m in NUMCHR.finditer(data)]

print(out) #['[', 10, ',', 20, ']']
</code>```

.finditer (in this case) will return either consecutive numbers or only 1 character on each iteration. We just check the return and proceed accordingly.

Body:
Given the following string:

"[10,20]"

I want to create the following list using a list comprehension in Python:

['[', 10, ',', 20, ']']

Being 10 and 20 integers and the rest of the elements in the list chars.

I assume that I would need a to use something similar to what itertools.groupby(iterable, key=None) provides:

Make an iterator that returns consecutive keys and groups from the
iterable. The key is a function computing a key value for each
element. If not specified or is None, key defaults to an identity
function and returns the element unchanged. Generally, the iterable
needs to already be sorted on the same key function.

However Python's group by returns an iterator with consecutive keys and groups. In my case the keys would change so I guess I'd need a similar iterator that returns the groups based on a filter. Any ideas?

Body:
This can also be done with regex with ease.

import re

NUMCHR = re.compile(r'\d+|[^\d]') #consecutive digits OR one "not-a-digit"
data   = '[10,20]'
out    = [int(m[0]) if m[0].isdigit() else m[0] for m in NUMCHR.finditer(data)]

print(out) #['[', 10, ',', 20, ']']

.finditer (in this case) will return either consecutive numbers or only 1 character on each iteration. We just check the return and proceed accordingly.


问:
how to build a json array with custom elements with javascript
I'm using JavaScript, I have an array:

```<code>[
  { "id": "0", "name": "test1", "brand": "brand1" },
  { "id": "0", "name": "test1", "brand": "brand2" },
  { "id": "0", "name": "test1", "brand": "brand3" },
  { "id": "2", "name": "test2", "brand": "brand100" },
  { "id": "2", "name": "test2", "brand": "brand101" },
  { "id": "2", "name": "test2", "brand": "brand102" },
  { "id": "2", "name": "test2", "brand": "brand103" },
  { "id": "2", "name": "test2", "brand": "brand104" }
]
</code>```

I'm using JavaScript to have something like this:

```<code>[
  {
    "id": "0",
    "name": "test1",
    "brand": [
      "brand1",
      "brand2",
      "brand3"
    ]
  },
  {
    "id": "2",
    "name": "test2",
    "brand": [
      "brand100",
      "brand101",
      "brand102",
      "brand103",
      "brand104"
    ]
  }
]
</code>```

The script is:

```<code>let result=[]
for (var i = 0; i < brands.length; i++) {
let id =brands[i].id
    if(i==0){

        result.push(

          {
          "id": brands[i].id,
          "name": brands[i].name,
           } )
 else{
        result.push(
           "id": brands[i].id,
          "name": brands[i].name )
    }
}
</code>```

But it seems that it doesn't work...?

答:
You could take an object for the obj3ects with same id and get all values of it as result;

const
    data = [{ id: "0", name: "test1", brand: "brand1" }, { id: "0", name: "test1", brand: "brand2" }, { id: "0", name: "test1", brand: "brand3" }, { id: "2", name: "test2", brand: "brand100" }, { id: "2", name: "test2", brand: "brand101" }, { id: "2", name: "test2", brand: "brand102" }, { id: "2", name: "test2", brand: "brand103" }, { id: "2", name: "test2", brand: "brand104" }],
    result = Object.values(data.reduce((r, { id, name, brand }) => (
        (r[id] ??= { id, name, brand: [] }).brand.push(brand),
        r
    ), {}));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I'm using JavaScript, I have an array:

[
  { "id": "0", "name": "test1", "brand": "brand1" },
  { "id": "0", "name": "test1", "brand": "brand2" },
  { "id": "0", "name": "test1", "brand": "brand3" },
  { "id": "2", "name": "test2", "brand": "brand100" },
  { "id": "2", "name": "test2", "brand": "brand101" },
  { "id": "2", "name": "test2", "brand": "brand102" },
  { "id": "2", "name": "test2", "brand": "brand103" },
  { "id": "2", "name": "test2", "brand": "brand104" }
]

I'm using JavaScript to have something like this:

[
  {
    "id": "0",
    "name": "test1",
    "brand": [
      "brand1",
      "brand2",
      "brand3"
    ]
  },
  {
    "id": "2",
    "name": "test2",
    "brand": [
      "brand100",
      "brand101",
      "brand102",
      "brand103",
      "brand104"
    ]
  }
]

The script is:

let result=[]
for (var i = 0; i < brands.length; i++) {
let id =brands[i].id
    if(i==0){

        result.push(

          {
          "id": brands[i].id,
          "name": brands[i].name,
           } )
 else{
        result.push(
           "id": brands[i].id,
          "name": brands[i].name )
    }
}

But it seems that it doesn't work...?

Body:
You could take an object for the obj3ects with same id and get all values of it as result;

const
    data = [{ id: "0", name: "test1", brand: "brand1" }, { id: "0", name: "test1", brand: "brand2" }, { id: "0", name: "test1", brand: "brand3" }, { id: "2", name: "test2", brand: "brand100" }, { id: "2", name: "test2", brand: "brand101" }, { id: "2", name: "test2", brand: "brand102" }, { id: "2", name: "test2", brand: "brand103" }, { id: "2", name: "test2", brand: "brand104" }],
    result = Object.values(data.reduce((r, { id, name, brand }) => (
        (r[id] ??= { id, name, brand: [] }).brand.push(brand),
        r
    ), {}));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
create new column on conditions python
I have a ref table df_ref like this:

```<code>col1 col2 ref
a    b    a,b
c    d    c,d
</code>```

I need to create a new column in another table based on ref table.The table like this:

```<code>col1 col2
a    b
a    NULL
NULL b
a    NULL
a    NULL
c    d
c    NULL
NULL NULL
</code>```

The output table df_org looks like:

```<code>col1  col2   ref
a     b      a,b
a     NULL   a,b
NULL  b      a,b
a     NULL   a,b
a     NULL   a,b
c     d      c,d
c     NULL   c,d
NULL  NULL   NULL
</code>```

If any column value in col1 and col2 can find in ref table, it will use the ref col in ref table. If col1 and col2 are NULL, So they cannot find anything in ref table, just return NULL. I use this code, but it doesn't work.

```<code>df_org['ref']=np.where(((df_org['col1'].isin(df_ref['ref'])) |
         (df_org['col2'].isin(df_ref['ref']))
          ), df_ref['ref'], 'NULL')
</code>```

ValueError: operands could not be broadcast together with shapes

答:
```<code>( df.merge(df_ref[['col1', 'ref']], how="left", on='col1' )       # add column for col1 refs
    .merge(df_ref[['col2', 'ref']], how="left", on='col2',        # add column for col2 refs
                                    suffixes=('_col1', '_col2'))  # set suffixes to both ref columns
    .assign(ref=lambda x: x['ref_col1'].fillna(x['ref_col2']))    # add column from 'ref_col1' and fill 'NaN' from 'ref_col2'
    .drop(['ref_col1', 'ref_col2'], axis=1)                       # drop 'ref_col1' and 'ref_col2' columns
)
</code>```

results in

```<code>  col1 col2  ref
0    a    b  a,b
1  NaN    b  a,b
2    a  NaN  a,b
3    a  NaN  a,b
4    a  NaN  a,b
5  NaN  NaN  NaN
6    c  NaN  c,d
7    c    d  c,d
</code>```

Title: create new column on conditions python

Body:
I have a ref table df_ref like this:

col1 col2 ref
a    b    a,b
c    d    c,d

I need to create a new column in another table based on ref table.The table like this:

col1 col2
a    b
a    NULL
NULL b
a    NULL
a    NULL
c    d
c    NULL
NULL NULL

The output table df_org looks like:

col1  col2   ref
a     b      a,b
a     NULL   a,b
NULL  b      a,b
a     NULL   a,b
a     NULL   a,b
c     d      c,d
c     NULL   c,d
NULL  NULL   NULL

If any column value in col1 and col2 can find in ref table, it will use the ref col in ref table. If col1 and col2 are NULL, So they cannot find anything in ref table, just return NULL. I use this code, but it doesn't work.

df_org['ref']=np.where(((df_org['col1'].isin(df_ref['ref'])) |
         (df_org['col2'].isin(df_ref['ref']))
          ), df_ref['ref'], 'NULL')

ValueError: operands could not be broadcast together with shapes

Body:
( df.merge(df_ref[['col1', 'ref']], how="left", on='col1' )       # add column for col1 refs
    .merge(df_ref[['col2', 'ref']], how="left", on='col2',        # add column for col2 refs
                                    suffixes=('_col1', '_col2'))  # set suffixes to both ref columns
    .assign(ref=lambda x: x['ref_col1'].fillna(x['ref_col2']))    # add column from 'ref_col1' and fill 'NaN' from 'ref_col2'
    .drop(['ref_col1', 'ref_col2'], axis=1)                       # drop 'ref_col1' and 'ref_col2' columns
)

results in

  col1 col2  ref
0    a    b  a,b
1  NaN    b  a,b
2    a  NaN  a,b
3    a  NaN  a,b
4    a  NaN  a,b
5  NaN  NaN  NaN
6    c  NaN  c,d
7    c    d  c,d


问:
How do I make a method like int.getRed() in java?
I am making an imaginary number graphing calculator with java (using a+bi={a,b}) and want to make new functions for + - * / and ^ operators, since they don't work on double[] variables. I know how to make normal methods, like File(), but I am having trouble doing things like int.getRed(). Here's my code for the addition method

```<code>private static double[] CPlusC(double[] a, double[] b) {
    double aN = a[1] + b[1];
    double bN = a[2] + b[2];
    double[] ansN = {aN,bN};
    return ansN;
}
</code>```

I have the addition parts correct, I just can't find anything to make the function more "realistic", as in double[].CPlusC(double[])
Could someone please help me out? Once I figure this one out, I should know how to do the others.
Thank you so much!

答:
As I mentioned in my comment, you can't create extension methods like you would do in Kotlin or C#.

But you shouldn't use double[] to handle complex numbers in the first place. A better approach would be to create your own Complex class that contains all necessary methods you need for calculation.

Your class could look like this:

```<code>public class Complex {
    private final double re;
    private final double im;

    public Complex(double re, double im) {
        this.re = re;
        this.im = im;
    }

    // getters and other methods

    public Complex add(Complex other) {
        double addedRe = re + other.re;
        double addedIm = im + other.im;
        return new Complex(addedRe, addedIm);
    }

    public String toString() {
        return String.format("%s %s %si", re, im < 0 ? "-" : "+", Math.abs(im));
    }
}
</code>```

Then you can do your calculations like:

```<code>Complex c1 = new Complex(0, 1);
Complex c2 = new Complex(2.5, 1.3);
Complex c3 = c1.add(c2);
System.out.println(c3) // 2.5 + 2.3i
</code>```

Body:
I am making an imaginary number graphing calculator with java (using a+bi={a,b}) and want to make new functions for + - * / and ^ operators, since they don't work on double[] variables. I know how to make normal methods, like File(), but I am having trouble doing things like int.getRed(). Here's my code for the addition method

private static double[] CPlusC(double[] a, double[] b) {
    double aN = a[1] + b[1];
    double bN = a[2] + b[2];
    double[] ansN = {aN,bN};
    return ansN;
}

I have the addition parts correct, I just can't find anything to make the function more "realistic", as in double[].CPlusC(double[])
Could someone please help me out? Once I figure this one out, I should know how to do the others.
Thank you so much!

Body:
As I mentioned in my comment, you can't create extension methods like you would do in Kotlin or C#.

But you shouldn't use double[] to handle complex numbers in the first place. A better approach would be to create your own Complex class that contains all necessary methods you need for calculation.

Your class could look like this:

public class Complex {
    private final double re;
    private final double im;

    public Complex(double re, double im) {
        this.re = re;
        this.im = im;
    }

    // getters and other methods

    public Complex add(Complex other) {
        double addedRe = re + other.re;
        double addedIm = im + other.im;
        return new Complex(addedRe, addedIm);
    }

    public String toString() {
        return String.format("%s %s %si", re, im < 0 ? "-" : "+", Math.abs(im));
    }
}

Then you can do your calculations like:

Complex c1 = new Complex(0, 1);
Complex c2 = new Complex(2.5, 1.3);
Complex c3 = c1.add(c2);
System.out.println(c3) // 2.5 + 2.3i


问:
Trying to get only cells with certain initials but giving me syntax error? SQL
So my assignment question is to "Get a list of all books withdrawn by people with the initials 'B.W.'. Show a column for the first name, last name, initials, and the title of the book". I am trying to join these 3 tables as it is the only way to get this information, but Im having a hard time only displaying names with initials B.W. I get a syntax error saying:

"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'JOIN withdrawals

When I remove my 'WHERE' statement (all of the second line), my syntax error goes away. How do I make this work?

Below is my code:

```<code> SELECT first_name, last_name, title FROM members
     WHERE first_name LIKE 'B%' AND last_name LIKE 'W%'
      JOIN withdrawals
        ON members.member_id  = withdrawals.member_id
         JOIN books
             ON withdrawals.book_id = books.book_id
</code>```

答:
Try to follow everything in order which goes like:</p>
```<code>SELECT - FROM - JOIN & ON - WHERE - GROUP BY - HAVING - ORDER BY
</code>```

Body:
So my assignment question is to "Get a list of all books withdrawn by people with the initials 'B.W.'. Show a column for the first name, last name, initials, and the title of the book". I am trying to join these 3 tables as it is the only way to get this information, but Im having a hard time only displaying names with initials B.W. I get a syntax error saying:

"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'JOIN withdrawals

When I remove my 'WHERE' statement (all of the second line), my syntax error goes away. How do I make this work?

Below is my code:

 SELECT first_name, last_name, title FROM members
     WHERE first_name LIKE 'B%' AND last_name LIKE 'W%'
      JOIN withdrawals
        ON members.member_id  = withdrawals.member_id
         JOIN books
             ON withdrawals.book_id = books.book_id

Body:
Try to follow everything in order which goes like:

SELECT - FROM - JOIN & ON - WHERE - GROUP BY - HAVING - ORDER BY


问:
Common Lisp structures with dynamically scoped slots
Common Lisp is lexically scoped, but there is a possibility to create dynamic bindings with (declare (special *var*)). What I need, is a way to create a dynamically scoped structure slot, whose value is visible to all other slots. Here is an example:

```<code>(defun start-thread ()
  *delay*) ;; We defer the binding of *delay*
</code>```

This works for a usual lexical environment:

```<code>(let ((*delay* 1))
  (declare (special *delay*))
  (start-thread)) ;; returns 1
</code>```

This does not work:

```<code>(defstruct table
  (*delay* 0)
  (thread (start-thread)))

(make-table) ;; => Error: *delay* is unbound.
</code>```

My questions are

How to refer to the slot delay from other slots?

How to make the slot delay dynamically scoped, so that its value becomes visible
for the function (start-thread) ?

答:
I don't think that this makes sense.  Variables have scope and extent, but values just are, and slots are just parts of values.  Additionally, threads do not inherit dynamic bindings.

If you want to have some kind of object that is dynamically changed (so to speak), you need to put it into a dynamic variable as a whole value, and do re-bindings with modified versions (preferably on the basis of some immutability, i. e. persistent datastructures, e. g. with FSet).

Body:
Common Lisp is lexically scoped, but there is a possibility to create dynamic bindings with (declare (special *var*)). What I need, is a way to create a dynamically scoped structure slot, whose value is visible to all other slots. Here is an example:

(defun start-thread ()
  *delay*) ;; We defer the binding of *delay*

This works for a usual lexical environment:

(let ((*delay* 1))
  (declare (special *delay*))
  (start-thread)) ;; returns 1

This does not work:

(defstruct table
  (*delay* 0)
  (thread (start-thread)))

(make-table) ;; => Error: *delay* is unbound.

My questions are

How to refer to the slot delay from other slots?

How to make the slot delay dynamically scoped, so that its value becomes visible
for the function (start-thread) ?


问:
How do I format numbers as decimals in NextJS
I'm working on a basic website using NextJS, my code is like this

```<code>products: [
 {
   brand: 'example',
   price: 10000,
 },
...
],
</code>```

How do I change the 10000 to 10,000.

答:
You can use toLocaleString() to format the number with commas like this:

var a = 10000000;
console.log(a.toLocaleString())```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = {products: [
 {
   brand: 'example',
   price: 10000,
 }
]
}

obj.products[0].price = obj.products[0].price.toLocaleString()

console.log(obj)</code>```

Body:
I'm working on a basic website using NextJS, my code is like this

products: [
 {
   brand: 'example',
   price: 10000,
 },
...
],

How do I change the 10000 to 10,000.

Body:
You can use toLocaleString() to format the number with commas like this:

var a = 10000000;
console.log(a.toLocaleString())

var obj = {products: [
 {
   brand: 'example',
   price: 10000,
 }
]
}

obj.products[0].price = obj.products[0].price.toLocaleString()

console.log(obj)


问:
Writing pdf data into csv
I am a beginner to python and I am stuck in a critical part of my script. The goal is to get fillable pdf data into one single csv file. I have built a script to do so through pdfminer but I am now stuck in the part where I should get my script to write all of the output data into my csv. Instead, I am only getting one data line written in my csv. Any clue please?

Here is my code:

```<code>import sys, os
import six
import csv
import numpy as np
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdftypes import resolve1

fp = open("C:\\Users\\Sufyan\\Desktop\\test\\ccc.pdf", "rb")

parser = PDFParser(fp)
doc = PDFDocument(parser)
fields = resolve1(doc.catalog["AcroForm"])["Fields"]
for i in fields:
    field = resolve1(i)
    name, value = field.get("T"), field.get("V")
    filehehe = "{0}:{1}".format(name,value)
    values = resolve1(value)
    names = resolve1(name)
    print(values)

with open('test.csv','wb') as f:
    for i in names:
        f.write(values)
</code>```

答:
Clues:

There is no i inside this loop:

with open('test.csv','wb') as f:
    for i in names:
        f.write(values)
```

For the same for loop, which values does names contain? Are these a lot? 1? 2? Why?

Title: Writing pdf data into csv

Body:
I am a beginner to python and I am stuck in a critical part of my script. The goal is to get fillable pdf data into one single csv file. I have built a script to do so through pdfminer but I am now stuck in the part where I should get my script to write all of the output data into my csv. Instead, I am only getting one data line written in my csv. Any clue please?

Here is my code:

import sys, os
import six
import csv
import numpy as np
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdftypes import resolve1

fp = open("C:\\Users\\Sufyan\\Desktop\\test\\ccc.pdf", "rb")

parser = PDFParser(fp)
doc = PDFDocument(parser)
fields = resolve1(doc.catalog["AcroForm"])["Fields"]
for i in fields:
    field = resolve1(i)
    name, value = field.get("T"), field.get("V")
    filehehe = "{0}:{1}".format(name,value)
    values = resolve1(value)
    names = resolve1(name)
    print(values)

with open('test.csv','wb') as f:
    for i in names:
        f.write(values)

Body:
Clues:

There is no i inside this loop:

with open('test.csv','wb') as f:
    for i in names:
        f.write(values)

For the same for loop, which values does names contain? Are these a lot? 1? 2? Why?


答:
You have some syntax problems in your code (You have missed brackets). Here is a fixed one:</p>
```<code>let result = []
for (var i = 0; i < brands.length; i++) {
    let id = brands[i].id
    if (i == 0) {
        result.push({
            "id": brands[i].id,
            "name": brands[i].name,
        });
    } else {
        result.push({
            "id": brands[i].id,
            "name": brands[i].name
        });
    }
}
</code>```

Title: how to build a json array with custom elements with javascript

Body:
You have some syntax problems in your code (You have missed brackets). Here is a fixed one:

let result = []
for (var i = 0; i < brands.length; i++) {
    let id = brands[i].id
    if (i == 0) {
        result.push({
            "id": brands[i].id,
            "name": brands[i].name,
        });
    } else {
        result.push({
            "id": brands[i].id,
            "name": brands[i].name
        });
    }
}


问:
Why are all references to my IDispatch object not released?
I'm hosting an IWebBrowser2 control in my C++ program using nothing but plain Win32 (no mfc, atl, wtl etc). On DISPID_NAVIGATECOMPLETE2 I add a custom object to be accessed from javascript running on the displayed webpage.

To add the custom object I call InvokeEx with DISPATCH_PROPERTYPUT and a DISPPARAMS structure with a pointer to my custom object.

During the call to InvokeEx the AddRef function of my custom object is called and I increment its reference counter. But the object never gets a call to its Release function, so the reference counter never decreases down to zero again.

Who is responsible for calling Release() after AddRef() has been called in InvokeEx?

EDIT: (Adding some code)

This is the code that adds my custom object to the IHTMLWindow2. custObj points to my custom object

```<code>IHTMLWindow2 *win = NULL;
GetDoc()->get_parentWindow(&win);
IDispatchEx *winEx = NULL;
win->QueryInterface(&winEx);

DISPID dispid;
HRESULT hr = winEx->GetDispID(objName, fdexNameEnsure, &dispid); //objName is "JSObject"

DISPID namedArgs[] = {DISPID_PROPERTYPUT};
DISPPARAMS params;
params.rgvarg = new VARIANT[1];
params.rgvarg[0].pdispVal = custObj;
params.rgvarg[0].vt = VT_DISPATCH;
params.rgdispidNamedArgs = namedArgs;
params.cArgs = 1;
params.cNamedArgs = 1;

hr = winEx->InvokeEx(dispid, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &params, NULL, NULL, NULL);
</code>```

This is the object that I'm adding (some private members have been left out for brevity)

```<code>class JSObject : public IDispatch {
private:
    long ref;
public:
    JSObject();

    // IUnknown
    virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv);
    virtual ULONG STDMETHODCALLTYPE AddRef();
    virtual ULONG STDMETHODCALLTYPE Release();

    // IDispatch
    virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(UINT *pctinfo);
    virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(UINT iTInfo, LCID lcid,
        ITypeInfo **ppTInfo);
    virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(REFIID riid,
        LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId);
    virtual HRESULT STDMETHODCALLTYPE Invoke(DISPID dispIdMember, REFIID riid,
        LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult,
        EXCEPINFO *pExcepInfo, UINT *puArgErr);
};
</code>```

EDIT 2:

Now that it seems to be working like it should I decided to put it on github.

https://github.com/Tobbe/CppIEEmbed. Please fork and improve if you can :)

答:
Well, you are assigning a property, aren't you? As long as this property exists and refers to your object, it will have a reference added.

If you want the remote object to release your reference you should assign NULL to the property, or some other object.

Body:
I'm hosting an IWebBrowser2 control in my C++ program using nothing but plain Win32 (no mfc, atl, wtl etc). On DISPID_NAVIGATECOMPLETE2 I add a custom object to be accessed from javascript running on the displayed webpage.

To add the custom object I call InvokeEx with DISPATCH_PROPERTYPUT and a DISPPARAMS structure with a pointer to my custom object.

During the call to InvokeEx the AddRef function of my custom object is called and I increment its reference counter. But the object never gets a call to its Release function, so the reference counter never decreases down to zero again.

Who is responsible for calling Release() after AddRef() has been called in InvokeEx?

EDIT: (Adding some code)

This is the code that adds my custom object to the IHTMLWindow2. custObj points to my custom object

IHTMLWindow2 *win = NULL;
GetDoc()->get_parentWindow(&win);
IDispatchEx *winEx = NULL;
win->QueryInterface(&winEx);

DISPID dispid;
HRESULT hr = winEx->GetDispID(objName, fdexNameEnsure, &dispid); //objName is "JSObject"

DISPID namedArgs[] = {DISPID_PROPERTYPUT};
DISPPARAMS params;
params.rgvarg = new VARIANT[1];
params.rgvarg[0].pdispVal = custObj;
params.rgvarg[0].vt = VT_DISPATCH;
params.rgdispidNamedArgs = namedArgs;
params.cArgs = 1;
params.cNamedArgs = 1;

hr = winEx->InvokeEx(dispid, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &params, NULL, NULL, NULL);

This is the object that I'm adding (some private members have been left out for brevity)

class JSObject : public IDispatch {
private:
    long ref;
public:
    JSObject();

    // IUnknown
    virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv);
    virtual ULONG STDMETHODCALLTYPE AddRef();
    virtual ULONG STDMETHODCALLTYPE Release();

    // IDispatch
    virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(UINT *pctinfo);
    virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(UINT iTInfo, LCID lcid,
        ITypeInfo **ppTInfo);
    virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(REFIID riid,
        LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId);
    virtual HRESULT STDMETHODCALLTYPE Invoke(DISPID dispIdMember, REFIID riid,
        LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult,
        EXCEPINFO *pExcepInfo, UINT *puArgErr);
};

EDIT 2:

Now that it seems to be working like it should I decided to put it on github.

https://github.com/Tobbe/CppIEEmbed. Please fork and improve if you can :)


问:
export "firebase/storage" and "firebase/firestore" in one file - Nextjs
I have a problem when I want to export both objects of my firebase.js file I got this error:

```<code>TypeError: Cannot read properties of undefined (reading 'ref')
</code>```

firebase.js

```<code>import firebase from "firebase";
import "firebase/storage";
import "firebase/firestore";

const firebaseConfig = {
  apiKey: ....
};
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
} else {
  firebase.app();
}
var storage = firebase.storage();
var firestore = firebase.firestore();

export default { storage, firestore };
</code>```

upload.js

```<code>  import React, { useState } from "react";
  import { storage } from "../lib/firebase";

  function account() {
    const [image, setImage] = useState("");
    const upload = () => {
      if (image == null) return;
      storage
        .ref(`/images/${image.name}`)
        ....
    };

    return (
      <div>
        <Upload />
      </div>
    );
  }

  export default account;
</code>```

If I export only the storage and import it in my upload.jsfile it works. What is the different?

答:
if you to try import per module. It should be something like this.

firebase.js

```<code>import firebase from "firebase";
import "firebase/storage";
import "firebase/firestore";

const firebaseConfig = {
  apiKey: ....
};
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
} else {
  firebase.app();
}
var storage = firebase.storage();
var firestore = firebase.firestore();

export { storage, firestore };
</code>```

upload.js

```<code>import React, { useState } from "react";
  import { storage, firestore } from "../lib/firebase";

  function account() {
    const [image, setImage] = useState("");
    const upload = () => {
      if (image == null) return;
      storage
        .ref(`/images/${image.name}`)
        ....
    };

    return (
      <div>
        <Upload />
      </div>
    );
  }

  export default account;
</code>```

Hopefully can help you!

Body:
I have a problem when I want to export both objects of my firebase.js file I got this error:

TypeError: Cannot read properties of undefined (reading 'ref')

firebase.js

import firebase from "firebase";
import "firebase/storage";
import "firebase/firestore";

const firebaseConfig = {
  apiKey: ....
};
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
} else {
  firebase.app();
}
var storage = firebase.storage();
var firestore = firebase.firestore();

export default { storage, firestore };

upload.js

  import React, { useState } from "react";
  import { storage } from "../lib/firebase";

  function account() {
    const [image, setImage] = useState("");
    const upload = () => {
      if (image == null) return;
      storage
        .ref(`/images/${image.name}`)
        ....
    };

    return (

        <Upload />

    );
  }

  export default account;

If I export only the storage and import it in my upload.jsfile it works. What is the different?

Body:
if you to try import per module. It should be something like this.

firebase.js

import firebase from "firebase";
import "firebase/storage";
import "firebase/firestore";

const firebaseConfig = {
  apiKey: ....
};
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
} else {
  firebase.app();
}
var storage = firebase.storage();
var firestore = firebase.firestore();

export { storage, firestore };

upload.js

import React, { useState } from "react";
  import { storage, firestore } from "../lib/firebase";

  function account() {
    const [image, setImage] = useState("");
    const upload = () => {
      if (image == null) return;
      storage
        .ref(`/images/${image.name}`)
        ....
    };

    return (
      <div>
        <Upload />
      </div>
    );
  }

  export default account;

Hopefully can help you!


问:
"use of moved value" when the control flow won't allow it?
This is a minimal reproduction of the code I'm struggling with:

// real code struct is not just a string, and is not cloneable
struct NotCloneable(String);

fn outer() -> Result<NotCloneable, String> {
    let obj = NotCloneable(String::from("Hello, world!"));
    might_fail().map_err(|_| {
        // real code closure might return one of several errors, including an
        // error containing non-cloneable fields from struct
        obj.0
    })?;
    // the ? means that if we got to here, the closure never executed
    // ... yet this won't compile because it claims the closure moved obj
    Ok(obj)
}

fn might_fail() -> Result<(), ()> {
    Err(())
}
```
<p>It fails to compile with:</p>
```error[E0382]: use of partially moved value: `obj`
  --> src/main.rs:16:8
   |
10 |     might_fail().map_err(|_| {
   |                          --- value partially moved into closure here
...
14 |         obj.0
   |         ----- variable partially moved due to use in closure
15 |     })?;
16 |     Ok(obj)
   |        ^^^ value used here after partial move
   |
   = note: partial move occurs because `obj.0` has type `String`, which does not implement the `Copy` trait

For more information about this error, try `rustc --explain E0382`.
error: could not compile `playground` due to previous error
```

答:
After @Jmb's comment I also tried:

fn outer() -> Result<NotCloneable, String> {
    let obj = NotCloneable(String::from("Hello, world!"));
    match might_fail() {
        Ok(_) => Ok(()),
        Err(_) => Err(obj.0),
    }?;
    Ok(obj)
}
```
<p>However, this fails to compile due the same error. What I did find is that if I explicitly early-return then it works:</p>
<pre class="lang-rust prettyprint-override"><code>fn outer() -> Result<NotCloneable, String> {
    let obj = NotCloneable(String::from("Hello, world!"));
    match might_fail() {
        Ok(_) => (),
        Err(_) => return Err(obj.0),
    };
    Ok(obj)
}
</code>```

So it seems that whatever control flow analysis is happening is not smart enough to figure out that the capture is in an Err that is handled with an early return '?'.

Body:
This is a minimal reproduction of the code I'm struggling with:

// real code struct is not just a string, and is not cloneable
struct NotCloneable(String);

fn outer() -> Result<NotCloneable, String> {
    let obj = NotCloneable(String::from("Hello, world!"));
    might_fail().map_err(|_| {
        // real code closure might return one of several errors, including an
        // error containing non-cloneable fields from struct
        obj.0
    })?;
    // the ? means that if we got to here, the closure never executed
    // ... yet this won't compile because it claims the closure moved obj
    Ok(obj)
}

fn might_fail() -> Result<(), ()> {
    Err(())
}

It fails to compile with:

error[E0382]: use of partially moved value: `obj`
  --> src/main.rs:16:8
   |
10 |     might_fail().map_err(|_| {
   |                          --- value partially moved into closure here
...
14 |         obj.0
   |         ----- variable partially moved due to use in closure
15 |     })?;
16 |     Ok(obj)
   |        ^^^ value used here after partial move
   |
   = note: partial move occurs because `obj.0` has type `String`, which does not implement the `Copy` trait

For more information about this error, try `rustc --explain E0382`.
error: could not compile `playground` due to previous error

Body:
After @Jmb's comment I also tried:

fn outer() -> Result<NotCloneable, String> {
    let obj = NotCloneable(String::from("Hello, world!"));
    match might_fail() {
        Ok(_) => Ok(()),
        Err(_) => Err(obj.0),
    }?;
    Ok(obj)
}

However, this fails to compile due the same error. What I did find is that if I explicitly early-return then it works:

fn outer() -> Result<NotCloneable, String> {
    let obj = NotCloneable(String::from("Hello, world!"));
    match might_fail() {
        Ok(_) => (),
        Err(_) => return Err(obj.0),
    };
    Ok(obj)
}

So it seems that whatever control flow analysis is happening is not smart enough to figure out that the capture is in an Err that is handled with an early return '?'.


问:
Selenium-chromedriver: Cannot construct KeyEvent from non-typeable key
I updated my Chrome and Chromedriver to the latest version yesterday, and since then I get the following error messages when running my Cucumber features:

```<code>....
unknown error: Cannot construct KeyEvent from non-typeable key
        (Session info: chrome=98.0.4758.80) (Selenium::WebDriver::Error::UnknownError)
      #0 0x55e9ce6a4093 <unknown>
      #1 0x55e9ce16a648 <unknown>
      #2 0x55e9ce1a9866 <unknown>
      #3 0x55e9ce1cbd29 <unknown>
      .....
</code>```

I try to fill a text field with Capybara's fill_in method. While debugging I noticed that Capybara has problems especially with the symbols @ and \. Every other character can be written into the text field without any problems.

The code that triggers the error looks like this

```<code>def sign_in(user)
  visit new_sign_in_path
  fill_in 'Email', with: user.email
  fill_in 'Password', with: user.password
  click_button 'Sign in'
end
</code>```

user.email contains a string like "example1@mail.com".

I work with Rails 6.1.3.1, Cucumber 5.3.0, Chromedriver 98.0.4758.48, capybara 3.35.3

The error only occurs on features that are tagged with @javascript

Do you have any ideas what causes this error or how to fix it?

答:
I am using Selenium with Java. I have been automating login functions without any problem until the Google Chrome update. After the update, I started getting the same error as well. I just changed my keyboard language to "US" and the problem is solved.

Update: Recently (mid-February) my ChromeDriver stopped giving the same error. I am not sure if there has been a fix as I didn't see a new release since I started having problems but my Java/Selenium automation codes run without any error regardless of the keyboard language and send characters like '@'. So, no need to switch the keyboard language to "US" anymore.

Body:
I updated my Chrome and Chromedriver to the latest version yesterday, and since then I get the following error messages when running my Cucumber features:

....
unknown error: Cannot construct KeyEvent from non-typeable key
        (Session info: chrome=98.0.4758.80) (Selenium::WebDriver::Error::UnknownError)
      #0 0x55e9ce6a4093 <unknown>
      #1 0x55e9ce16a648 <unknown>
      #2 0x55e9ce1a9866 <unknown>
      #3 0x55e9ce1cbd29 <unknown>
      .....

I try to fill a text field with Capybara's fill_in method. While debugging I noticed that Capybara has problems especially with the symbols @ and \. Every other character can be written into the text field without any problems.

The code that triggers the error looks like this

def sign_in(user)
  visit new_sign_in_path
  fill_in 'Email', with: user.email
  fill_in 'Password', with: user.password
  click_button 'Sign in'
end

user.email contains a string like "example1@mail.com".

I work with Rails 6.1.3.1, Cucumber 5.3.0, Chromedriver 98.0.4758.48, capybara 3.35.3

The error only occurs on features that are tagged with @javascript

Do you have any ideas what causes this error or how to fix it?


问:
Jmeter/Selenium scroll down in a specific area and not the entire page
I am having trouble trying to figure out how to scroll down a one section only from the entire webpage. I have tried window.scrollBy(x,y) which works but for the entire page and not the section which I need. The scroll bar does not show up either. I am using JMeter (JS as language) and Selenium as the driver.

答:
Try the following:

var element = WDS.browser.findElement(org.openqa.selenium.By.id('some id'))  - locate the Web Element you want to "see"

WDS.browser.executeScript('arguments[0].scrollIntoView(true);', element) - bring the element into the visible area

More information:

Element.scrollIntoView()

HTML DOM scrollIntoView Method

The WebDriver Sampler: Your Top 10 Questions Answered


问:
Microsoft GraphAPI PowerShell download attachment
How can I download the attachment from the Microsoft Graph API for Mail message?

'$attachment=Get-MgUserMessageAttachment -MessageId AAMkAGIzZWEyN2MxLWJmNTktNDBkMi05ZWY2LWE3YjFhYWJjNmEwOABGAAAAAAA2OVriHzx8TL2ku-KbIgYgBwChRsRs-pG2QpRCaG5OA-T0FcAAA= -UserId abcd@gmail.com

$attachment
ContentType          : application/octet-stream
Id                   : AAMkAGIzZWEyN2MxLWJmNTktNDBkMi05ZWY2LWE3YjFhYWJjNmEwOABGAAAAAAA2OVriHzx8TL2ku-KbIgYgBwChRsRs-pG2QpRCaG5OgRLxAAAAAAEMAAChRsRs-pG2QpRCaG5OgRLxAAA-T0FcAAABEg
                       AQANUHCnnWvO5Dr-D2VilhKP8=
IsInline             : False
LastModifiedDateTime : 4/14/2020 7:21:32 PM
Name                 : report.csv
Size                 : 707'
```

答:
This works ("Log" basically just calls write-verbose):</p>
```<code># Install Microsoft Graph API PowerShell module if not already installed
if (Get-Module 'Microsoft.Graph' -ListAvailable) {
    Log 'PowerShell Module Microsoft.Graph is already installed.'
} else {
    Log 'PowerShell Module Microsoft.Graph not installed. Installing...'
    try {
        Install-Module 'Microsoft.Graph' -Force
        Log 'Installed successfully.'
    }
    catch {
        throw 'Error: unable to install PowerShell Module Microsoft.Graph Module.'
    }
}

$UserId     = ''
$FolderId   = ''
$Filename   = "$( $env:USERPROFILE )\Downloads\test.pdf"
$TId        = ''
$AppId      = ''
$CertThumb  = ''

# Connect to Microsoft Graph API
$null = Connect-MgGraph -TenantId $TId -AppId $AppId -CertificateThumbprint $CertThumb
# Using null suppresses the output

# Get Message from Folder in User
$Msgs = Get-MgUserMailFolderMessage -UserId $UserId -MailFolderId $FolderId
$MsgId = $Msgs[0].Id

# Get Attachment
$Attachm = Get-MgUserMailFolderMessageAttachment -UserId $UserId -MailFolderId $FolderId -MessageId $MsgId

# Get Attachment as Base64
$Base64B = ($Attachm).AdditionalProperties.contentBytes
# Works also: Get-MgUserMessageAttachment

# Save Base64 to file
$Bytes = [Convert]::FromBase64String($Base64B)
[IO.File]::WriteAllBytes($Filename, $Bytes)

Disconnect-MgGraph
</code>```

Body:
This works ("Log" basically just calls write-verbose):

# Install Microsoft Graph API PowerShell module if not already installed
if (Get-Module 'Microsoft.Graph' -ListAvailable) {
    Log 'PowerShell Module Microsoft.Graph is already installed.'
} else {
    Log 'PowerShell Module Microsoft.Graph not installed. Installing...'
    try {
        Install-Module 'Microsoft.Graph' -Force
        Log 'Installed successfully.'
    }
    catch {
        throw 'Error: unable to install PowerShell Module Microsoft.Graph Module.'
    }
}

$UserId     = ''
$FolderId   = ''
$Filename   = "$( $env:USERPROFILE )\Downloads\test.pdf"
$TId        = ''
$AppId      = ''
$CertThumb  = ''

# Connect to Microsoft Graph API
$null = Connect-MgGraph -TenantId $TId -AppId $AppId -CertificateThumbprint $CertThumb
# Using null suppresses the output

# Get Message from Folder in User
$Msgs = Get-MgUserMailFolderMessage -UserId $UserId -MailFolderId $FolderId
$MsgId = $Msgs[0].Id

# Get Attachment
$Attachm = Get-MgUserMailFolderMessageAttachment -UserId $UserId -MailFolderId $FolderId -MessageId $MsgId

# Get Attachment as Base64
$Base64B = ($Attachm).AdditionalProperties.contentBytes
# Works also: Get-MgUserMessageAttachment

# Save Base64 to file
$Bytes = [Convert]::FromBase64String($Base64B)
[IO.File]::WriteAllBytes($Filename, $Bytes)

Disconnect-MgGraph


问:
bitmap size exceeds VM budget Error on Android
I'm loading 100 images from Asset folder to an array object. The pictures are quite small (png ~20k each), and im using this code do to it, and to prevent memory leak & optimized performances:

in a loop:

```<code>// create resized bitmap from asset resource
        InputStream istr = assetManager.open(pics[i]);
        Bitmap b = BitmapFactory.decodeStream(istr);
        b = Bitmap.createScaledBitmap(b, 240, 240, true);
</code>```

where pics[i] is a list of filenames which sits in my Asset folder.

The code works for me, but i still receive from time to time Errors from users (i see it on Developer Console errors):

```<code>java.lang.OutOfMemoryError: bitmap size exceeds VM budget
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:468)
at android.graphics.Bitmap.createBitmap(Bitmap.java:435)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:340)
</code>```

Is there anything i can do to improve it? or this is Android's world, we can never deliever a perfect application?

答: Bitmaps aren't compressed so they are stored in width * height * 4 bytes. It means that every image uses about 225 KB of memory. 100 images require about 22 MB of memory. The minimal heap size is 16 MB, but devices usually have 24+ MB heap. And this heap is used not only for data but also for activities, view and so on. That means you can't load 100 bitmaps of this size.

Body:
I'm loading 100 images from Asset folder to an array object. The pictures are quite small (png ~20k each), and im using this code do to it, and to prevent memory leak & optimized performances:

in a loop:

// create resized bitmap from asset resource
        InputStream istr = assetManager.open(pics[i]);
        Bitmap b = BitmapFactory.decodeStream(istr);
        b = Bitmap.createScaledBitmap(b, 240, 240, true);

where pics[i] is a list of filenames which sits in my Asset folder.

The code works for me, but i still receive from time to time Errors from users (i see it on Developer Console errors):

java.lang.OutOfMemoryError: bitmap size exceeds VM budget
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:468)
at android.graphics.Bitmap.createBitmap(Bitmap.java:435)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:340)

Is there anything i can do to improve it? or this is Android's world, we can never deliever a perfect application?


问:
How do i fix this error in next js TypeError: Cannot set properties of undefined (setting 'className')
I am working on a next js project , copied some coe on code pen , it is used for a product design of an e commerce website . However i am having this problem.
TypeError: Cannot set properties of undefined (setting 'className'). What is an equalvalent of
getElementsByClassName or how can i override this eror
here is a glimse of the code</p>
```<code>var slider = document.getElementsByClassName("sliderBlock_items");
    var slides = document.getElementsByClassName("sliderBlock_items__itemPhoto");
    var next = document.getElementsByClassName("sliderBlock_controls__arrowForward")[0];
    var previous = document.getElementsByClassName("sliderBlock_controls__arrowBackward")[0];
    var items = document.getElementsByClassName("sliderBlock_positionControls")[0];
</code>```

答:
You can use:

document.querySelector(".your_class_name").value
querySelector() can be used to select elements on a page, just pass in a CSS like selector...

Cannot set value of undefined would mean that you are trying to select HTML elements that are not on the page. This could mean your code gets run before the components get rendered

Share your full code, or add that code inside a useEffect()

Body:
I am working on a next js project , copied some coe on code pen , it is used for a product design of an e commerce website . However i am having this problem.
TypeError: Cannot set properties of undefined (setting 'className'). What is an equalvalent of
getElementsByClassName or how can i override this eror
here is a glimse of the code

var slider = document.getElementsByClassName("sliderBlock_items");
    var slides = document.getElementsByClassName("sliderBlock_items__itemPhoto");
    var next = document.getElementsByClassName("sliderBlock_controls__arrowForward")[0];
    var previous = document.getElementsByClassName("sliderBlock_controls__arrowBackward")[0];
    var items = document.getElementsByClassName("sliderBlock_positionControls")[0];


问:
Google Apps Scripts - Add specific value to each row being processed in a loop
so I want to write a function that takes leads from a source sheet, and then, sends them to another sheet (the destsheet) if they haven't been sent yet. The difference between a lead that has been sent and a lead that hasn't been is that a lead sent should have "yes" in column K (column 10)

I have managed to get the first part working (sending leads from a sheet to another) but for some reason, I can't get the script to add "yes" when a lead is sent to the other sheet. As you can see below, I've tried adding "values[i][tstCol] = "yes";" in several different spots, but it's not working.
Any ideas of what I'm doing wrong? Thanks!

```<code>function newLeads() {
  var sourceSheet = SpreadsheetApp.openById('ID').getSheetByName('SHEETNAME');
  var destSheet = SpreadsheetApp.openById('ID').getSheetByName('SHEETNAME');

var values = sourceSheet.getDataRange().getDisplayValues();
var finalValues=[];

var columns = String("0,1,2,3,4,5,6,7,8").split(','); //only want these columns
var tstCol = 10;
for (var i=0;i<values.length;i++) {
    var newValues=[];
    //values[i][tstCol] = "yes";
    if (values[i][tstCol] != "yes") {
    //values[i][tstCol] = "yes";
      for (var j=0;j<columns.length;j++) {
      //values[i][tstCol] = "yes";
        newValues.push(values[i][columns[j]]);
      }
      finalValues.push(newValues);
    }
  }
  destSheet.getRange(destSheet.getLastRow() + 1, 1, finalValues.length, finalValues[0].length).setValues(finalValues);
}
</code>```

答:
Take a look at this.

```<code>function newLeads() {
  try {
    var sourceSheet = SpreadsheetApp.openById('ID').getSheetByName('SHEETNAME');
    var destSheet = SpreadsheetApp.openById('ID').getSheetByName('SHEETNAME');

    var values = sourceSheet.getDataRange().getDisplayValues();
    var finalValues=[];

    var columns = String("0,1,2,3,4,5,6,7,8").split(','); //only want these columns
    var tstCol = 10;
    for (var i=0;i<values.length;i++) {
      var newValues=[];
      if (values[i][tstCol] != "yes") {
        values[i][tstCol] = "yes";  // is this where you want to set to yes
        for (var j=0;j<columns.length;j++) {
          newValues.push(values[i][columns[j]]);
        }
        finalValues.push(newValues);
      }
      values[i] = [values[i][tstCol]];  // this would extract column tstCol
    }
    destSheet.getRange(destSheet.getLastRow() + 1, 1, finalValues.length, finalValues[0].length).setValues(finalValues);
    sourceSheet.getRange(1,tstCol+1,values.length,1).setValues(values);
  }
  catch(err) {
    console.log(err);
  }
}
</code>```

Explanation:

The try block is used to see if an error occurs during the block between try and catch; if an error occurs, the catch(err) block is executed and the error is being displayed.

The values array is an array of rows [[1,2,3,4],[5,6,7,8],...] which I converted it to an array [[1],[2],[3]...] of a single column of the spreadsheet type in order to use the setValues(values) method.

Reference link:

Apps Script setValues().

Body:
so I want to write a function that takes leads from a source sheet, and then, sends them to another sheet (the destsheet) if they haven't been sent yet. The difference between a lead that has been sent and a lead that hasn't been is that a lead sent should have "yes" in column K (column 10)

I have managed to get the first part working (sending leads from a sheet to another) but for some reason, I can't get the script to add "yes" when a lead is sent to the other sheet. As you can see below, I've tried adding "values[i][tstCol] = "yes";" in several different spots, but it's not working.
Any ideas of what I'm doing wrong? Thanks!

function newLeads() {
  var sourceSheet = SpreadsheetApp.openById('ID').getSheetByName('SHEETNAME');
  var destSheet = SpreadsheetApp.openById('ID').getSheetByName('SHEETNAME');

var values = sourceSheet.getDataRange().getDisplayValues();
var finalValues=[];

var columns = String("0,1,2,3,4,5,6,7,8").split(','); //only want these columns
var tstCol = 10;
for (var i=0;i<values.length;i++) {
    var newValues=[];
    //values[i][tstCol] = "yes";
    if (values[i][tstCol] != "yes") {
    //values[i][tstCol] = "yes";
      for (var j=0;j<columns.length;j++) {
      //values[i][tstCol] = "yes";
        newValues.push(values[i][columns[j]]);
      }
      finalValues.push(newValues);
    }
  }
  destSheet.getRange(destSheet.getLastRow() + 1, 1, finalValues.length, finalValues[0].length).setValues(finalValues);
}

Body:
Take a look at this.

function newLeads() {
  try {
    var sourceSheet = SpreadsheetApp.openById('ID').getSheetByName('SHEETNAME');
    var destSheet = SpreadsheetApp.openById('ID').getSheetByName('SHEETNAME');

    var values = sourceSheet.getDataRange().getDisplayValues();
    var finalValues=[];

    var columns = String("0,1,2,3,4,5,6,7,8").split(','); //only want these columns
    var tstCol = 10;
    for (var i=0;i<values.length;i++) {
      var newValues=[];
      if (values[i][tstCol] != "yes") {
        values[i][tstCol] = "yes";  // is this where you want to set to yes
        for (var j=0;j<columns.length;j++) {
          newValues.push(values[i][columns[j]]);
        }
        finalValues.push(newValues);
      }
      values[i] = [values[i][tstCol]];  // this would extract column tstCol
    }
    destSheet.getRange(destSheet.getLastRow() + 1, 1, finalValues.length, finalValues[0].length).setValues(finalValues);
    sourceSheet.getRange(1,tstCol+1,values.length,1).setValues(values);
  }
  catch(err) {
    console.log(err);
  }
}

Explanation:

The try block is used to see if an error occurs during the block between try and catch; if an error occurs, the catch(err) block is executed and the error is being displayed.

The values array is an array of rows [[1,2,3,4],[5,6,7,8],...] which I converted it to an array [[1],[2],[3]...] of a single column of the spreadsheet type in order to use the setValues(values) method.

Reference link:

Apps Script setValues().


问:
if else not providing desired output
My conditional function is not working. Where is the issue?

From  the below text, if "DFF  Manufacturing  Company" available, then it will print the name.

```<code>DFF  DFF  Manufacturing  Company  QWE  LIMITED
DFF  Strasse  16  O  Strasse  103
96032,  Germany  23467,  Germany
</code>```

Python code:

```<code>if "DFF  Manufacturing  Company" in text.split('\n'):
    print("DFF Manufacturing Company")
</code>```

Output:
No result is showing

答:
if you want to split lines and need to check every line, you have to check by loop.

```<code>for line in text.split('\n'):
   if "DFF  Manufacturing  Company" in line:
      print("DFF Manufacturing Company")
      #break #if you want to check once
</code>```

if you want to check in full paragraph , use below code

```<code>if "DFF  Manufacturing  Company" in text:
    print("DFF Manufacturing Company")
</code>```

Title: if else not providing desired output

Body:
My conditional function is not working. Where is the issue?

From  the below text, if "DFF  Manufacturing  Company" available, then it will print the name.

DFF  DFF  Manufacturing  Company  QWE  LIMITED
DFF  Strasse  16  O  Strasse  103
96032,  Germany  23467,  Germany

Python code:

if "DFF  Manufacturing  Company" in text.split('\n'):
    print("DFF Manufacturing Company")

Output:
No result is showing

Body:
if you want to split lines and need to check every line, you have to check by loop.

for line in text.split('\n'):
   if "DFF  Manufacturing  Company" in line:
      print("DFF Manufacturing Company")
      #break #if you want to check once

if you want to check in full paragraph , use below code

if "DFF  Manufacturing  Company" in text:
    print("DFF Manufacturing Company")


问:
Show validation feedback to the user
I am making a simple react form with a react-hook-form and yup as the validator. If the user's input is successfully validated, I want to show some feedback to the user, like a green outline. The problem is that I only want to show the green outline when my input has been validated, not every time the component is rendered. How can I do this? Component:</p>
```<code>const schema = yup.object().shape({
  email: yup
    .string()
    .required("This field is required"),
  password: yup.string().required("This field is required"),
});

export const Form = () => {
  const {
    register,
    handleSubmit,
    getValues,
    formState: { errors },
  } = useForm({
    mode: "onBlur",
    resolver: yupResolver(schema),
  });

  return (
      <form noValidate onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="email">Email</label>
      <input
        id="email"
        {...register("email")}
      />
     {errors.email ? errors?.email.message : null}
       <label htmlFor="password">Password</label>
      <input
        id="password"
        type="password"
        {...register("password")}
      />
      {errors.password ? errors?.password.message : null}
      <button
        type="submit"
      >
        Submit
      </button>
    </form>
  );
};

</code>```

答:
You can implement what you want with the touched property. Using the touched property for this kind of scenario is very common. Here's what you can do:

From the useForm hook, you can also extract the touchedFields

```<code>const {
    register,
    handleSubmit,
    getValues,
    formState: { errors, touchedFields }
  } = useForm({
    mode: "onBlur",
    resolver: yupResolver(schema)
  });
</code>```

The touchedFields properties stores the touched fields. A field is touched the first time the user leaves the focus from that field. So, then you can conditionally show a message about a field if it is touched and it has no errors like this:

```<code>{touchedFields.email && !errors.email ? <div>Email ok</div> : null}
</code>```

You can try this sandbox. I hope you can get the idea from it.

Title: Show validation feedback to the user

Body:
I am making a simple react form with a react-hook-form and yup as the validator. If the user's input is successfully validated, I want to show some feedback to the user, like a green outline. The problem is that I only want to show the green outline when my input has been validated, not every time the component is rendered. How can I do this? Component:

const schema = yup.object().shape({
  email: yup
    .string()
    .required("This field is required"),
  password: yup.string().required("This field is required"),
});

export const Form = () => {
  const {
    register,
    handleSubmit,
    getValues,
    formState: { errors },
  } = useForm({
    mode: "onBlur",
    resolver: yupResolver(schema),
  });

  return (
      <form noValidate onSubmit={handleSubmit(onSubmit)}>
      Email
      <input
        id="email"
        {...register("email")}
      />
     {errors.email ? errors?.email.message : null}
       Password
      <input
        id="password"
        type="password"
        {...register("password")}
      />
      {errors.password ? errors?.password.message : null}
      <button
        type="submit"
      >
        Submit
      </button>
    </form>
  );
};

Body:
You can implement what you want with the touched property. Using the touched property for this kind of scenario is very common. Here's what you can do:

From the useForm hook, you can also extract the touchedFields

const {
    register,
    handleSubmit,
    getValues,
    formState: { errors, touchedFields }
  } = useForm({
    mode: "onBlur",
    resolver: yupResolver(schema)
  });

The touchedFields properties stores the touched fields. A field is touched the first time the user leaves the focus from that field. So, then you can conditionally show a message about a field if it is touched and it has no errors like this:

{touchedFields.email && !errors.email ? <div>Email ok</div> : null}

You can try this sandbox. I hope you can get the idea from it.


问:
parsing in Ruby returns key not value
I don't know Ruby at all. I just need to run Vagrantfile writtne in ruby and I get wrong values from config file.

Vagrantfile:

```<code># -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.

require 'yaml'
current_dir = File.dirname(File.expand_path(__FILE__))
settings = YAML.load_file("#{current_dir}/vars.yaml")

Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.

  config.vm.define "testsbox" do |testsbox|
    testsbox.vm.box = "generic/rhel8"
    testsbox.vm.hostname = "testsbox"
    testsbox.vm.provision "shell", privileged: true,
      env: {
        "LOGIN" => settings['login'],
        "PASSWORD" => settings['password']
      },
      inline: <<-SHELL
      echo ****************SUBSCRIPTION**************
      echo --username=${LOGIN} --password=${PASSWORD}
      echo ****************SUBSCRIPTION**************
</code>```

And while running that I get:

```<code>--username=login --password=password
</code>```

vars.yaml file looks like this:

```<code>---
login:myuser
password:mysecretpassword
</code>```

I have no clue what can be wrong. Any hits are welcome. code executed on Windows 10 but under git-bash. File vars.yaml was edited under Windows but format was changed from Windnows (CR LF) to  (Unix (LF)

答:
Your YAML file has the wrong format - missing spaces after colons. The proper one would be:

```<code>---
login: myuser
password: mysecretpassword
</code>```

Fix it and your code should work.

What happens in your code? Something like the following:

YAML parser parses the wrong yaml file as a non-structured string, so your settings becomes something like "login:myuser password:mysecretpassword" (just a single string)

For strings [] behaves as a pattern matching to some extent - it just returns the matched substring, if any. Look:

s = "login:myuser password:mysecretpassword"
s["login"] #=> "login"
s[/login/] #=> "login" # Yes, this works too
s["foo"] #=> nil
```

Title: parsing in Ruby returns key not value

Body:
I don't know Ruby at all. I just need to run Vagrantfile writtne in ruby and I get wrong values from config file.

Vagrantfile:

# -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.

require 'yaml'
current_dir = File.dirname(File.expand_path(__FILE__))
settings = YAML.load_file("#{current_dir}/vars.yaml")

Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.

  config.vm.define "testsbox" do |testsbox|
    testsbox.vm.box = "generic/rhel8"
    testsbox.vm.hostname = "testsbox"
    testsbox.vm.provision "shell", privileged: true,
      env: {
        "LOGIN" => settings['login'],
        "PASSWORD" => settings['password']
      },
      inline: <<-SHELL
      echo ****************SUBSCRIPTION**************
      echo --username=${LOGIN} --password=${PASSWORD}
      echo ****************SUBSCRIPTION**************

And while running that I get:

--username=login --password=password

vars.yaml file looks like this:

---
login:myuser
password:mysecretpassword

I have no clue what can be wrong. Any hits are welcome. code executed on Windows 10 but under git-bash. File vars.yaml was edited under Windows but format was changed from Windnows (CR LF) to  (Unix (LF)

Body:
Your YAML file has the wrong format - missing spaces after colons. The proper one would be:

---
login: myuser
password: mysecretpassword

Fix it and your code should work.

What happens in your code? Something like the following:

YAML parser parses the wrong yaml file as a non-structured string, so your settings becomes something like "login:myuser password:mysecretpassword" (just a single string)

For strings [] behaves as a pattern matching to some extent - it just returns the matched substring, if any. Look:

s = "login:myuser password:mysecretpassword"
s["login"] #=> "login"
s[/login/] #=> "login" # Yes, this works too
s["foo"] #=> nil


问:
How to Fix Flutter Warning: Your Flutter application is created using an older version
I am receiving the following warning on running a Flutter App. Kindly guide how to fix it</p>
```<code>Warning: Your Flutter application is created using an older version of the Android
embedding. It's being deprecated in favor of Android embedding v2.
</code>```

答:
Just change this line:

```<code>io.flutter.app.FlutterActivity
</code>```

with this:

```<code>io.flutter.embedding.android.FlutterActivity
</code>```

in AndroidManifest

For more details check this url https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects

Body:
I am receiving the following warning on running a Flutter App. Kindly guide how to fix it

Warning: Your Flutter application is created using an older version of the Android
embedding. It's being deprecated in favor of Android embedding v2.

Body:
Just change this line:

io.flutter.app.FlutterActivity

with this:

io.flutter.embedding.android.FlutterActivity

in AndroidManifest

For more details check this url https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects


问:
SES error missing final '@domain'
I'm using python lib boto for sending emails via SES. And when I tried to send to more than 30 (but less than 50, so limit is not exceeded) recipients, I got an error:

```<code>  <Error>
    <Type>Sender</Type>
    <Code>InvalidParameterValue</Code>
    <Message>Missing final '@domain'</Message>
  </Error>
</code>```

My to_addresses is empty list, all recipients are in bcc_addresses list.

What does it mean? Every recipient's address is valid and sender address is verified and valid.

答: I used a malformed e-mail address in Source when I got this error.

Title: SES error missing final '@domain'

Body:
I'm using python lib boto for sending emails via SES. And when I tried to send to more than 30 (but less than 50, so limit is not exceeded) recipients, I got an error:

  <Error>
    <Type>Sender</Type>
    InvalidParameterValue
    <Message>Missing final '@domain'</Message>
  </Error>

My to_addresses is empty list, all recipients are in bcc_addresses list.

What does it mean? Every recipient's address is valid and sender address is verified and valid.