问:
JSON.stringify is distorting code adding \ inside strings?
I am trying to save local storage info but what happens is I am getting \ added to all the items that are strings I mean as some answers stated it is caused by double stringfy ? issue is my blob action that saves the local storage refuse to handle the it unless is it is stringifed, long story short could this double stringfy needed for the function cause issues later, I have no problem when parsing back but the look of the saved elements looks really weird  ?

//const ls = JSON.stringify(localStorage);
// "id":"\"159e17e9-19b7-453d-8e10-a411c7424586\"
// "groups":"{\"bee7bdc4-d888-46e6-93d7-ed0c\" : :[{\"id\":\"0e6e6426-4d79-4eea-9180-06111dd2a0e3\"}]

const config = {a: 'fdfgdg', b: 2}
console.log(JSON.stringify(config))```

答:
When saving to localStorage use JSON.stringify (since Storage accepts only String values):

const myData = {some: "data", other: "stuff"};
localStorage.appData = JSON.stringify(myData);
```
<p>When <strong>reading</strong> from localStorage, use <strong>JSON.parse</strong>:</p>
<pre class="lang-js prettyprint-override"><code>const myData = JSON.parse(localStorage.appData || "{}");
console.log(myData);  // {some: "data", other: "stuff"}
</code>```

Don't be afraid of escaped double-quotes with backslash! Otherwise it would end up in an invalid String format

const test = "this is \"something\""; // properly escaped quotes
```
<p>Get used to see in console (on in LocalStorage) the escaped strings used for Keys os String properties of a JSON stringified Object literal:</p>
<pre class="lang-js prettyprint-override"><code>"{\"prop\": \"some value\"}"   // Valid stringified JSON
</code>```

perfectly fine.

Learn more about the JSON format.

JSON, in order to be valid, its keys need to be enclosed in double quotes. JSON.stringify will take care of adding quotes to a JS Object Literal keys for you.

Body:
When saving to localStorage use JSON.stringify (since Storage accepts only String values):

const myData = {some: "data", other: "stuff"};
localStorage.appData = JSON.stringify(myData);

When reading from localStorage, use JSON.parse:

const myData = JSON.parse(localStorage.appData || "{}");
console.log(myData);  // {some: "data", other: "stuff"}

Don't be afraid of escaped double-quotes with backslash! Otherwise it would end up in an invalid String format

const test = "this is \"something\""; // properly escaped quotes

Get used to see in console (on in LocalStorage) the escaped strings used for Keys os String properties of a JSON stringified Object literal:

"{\"prop\": \"some value\"}"   // Valid stringified JSON

perfectly fine.

Learn more about the JSON format.

JSON, in order to be valid, its keys need to be enclosed in double quotes. JSON.stringify will take care of adding quotes to a JS Object Literal keys for you.


来源: stackexchange

问:
Optional parameters and option types using F#
Consider the following code:

```<code>type Test () =
  member o.fn1 (?bo) = 1
  member o.fn2 (?bo) = o.fn1 bo

  member o.fn3 (?bo) = 1 + bo.Value
  member o.fn4 (?bo) = o.fn3 bo
</code>```

While fn1 and fn2 work just fine, fn4 produces the following error:

init.fsx(6,30): error FS0001: This expression was expected to have type int but here has type 'a option

MSDN states:

Optional parameters are interpreted as the F# option type, so you can query them in the regular way that option types are queried, by using a match expression with Some and None.

To me, optional parameters are not interpreted as the F# option type otherwise the code would compile. Moreover I do not understand why, when I hover over ?bo in fn3 the tooltip says val bo: int option but from outside expects only int. I would expect a behavior of accepting nothing, int, Some int and None. And as the last note, I do not understand why fn2 works but fn4 does not.

Thanks for clarification

答:
I have to reconsider the correct answer. Based on this question (and answer):

Propagating optional arguments

it seams that the correct answer is the following:

```<code>type Test () =
  member o.fn1 (?bo) = 1
  member o.fn2 (?bo) = o.fn1 bo

  member o.fn3 (?bo) = 1 + bo.Value
  member o.fn4 (?bo) = o.fn3 (?bo = bo)
</code>```

It is a neat feature and credits for the answer go to desco!

ContentLicense: CC BY-SA 3.0

Body:
Consider the following code:

type Test () =
  member o.fn1 (?bo) = 1
  member o.fn2 (?bo) = o.fn1 bo

  member o.fn3 (?bo) = 1 + bo.Value
  member o.fn4 (?bo) = o.fn3 bo

While fn1 and fn2 work just fine, fn4 produces the following error:

init.fsx(6,30): error FS0001: This expression was expected to have type int but here has type 'a option

MSDN states:

Optional parameters are interpreted as the F# option type, so you can query them in the regular way that option types are queried, by using a match expression with Some and None.

To me, optional parameters are not interpreted as the F# option type otherwise the code would compile. Moreover I do not understand why, when I hover over ?bo in fn3 the tooltip says val bo: int option but from outside expects only int. I would expect a behavior of accepting nothing, int, Some int and None. And as the last note, I do not understand why fn2 works but fn4 does not.

Thanks for clarification

Body:
I have to reconsider the correct answer. Based on this question (and answer):

Propagating optional arguments

it seams that the correct answer is the following:

type Test () =
  member o.fn1 (?bo) = 1
  member o.fn2 (?bo) = o.fn1 bo

  member o.fn3 (?bo) = 1 + bo.Value
  member o.fn4 (?bo) = o.fn3 (?bo = bo)

It is a neat feature and credits for the answer go to desco!


问:
bitarray to byte array possible endian issues
I am wanting to store a sequence of bool values in azure blob storage along with a separate map file (a comma separated list of names in the same order as the bool values).

As efficiency and storage are important factors I want to store the bool values as a byte array.

I have gone about this by constructing a bitarray, i am then using the bitarray CopyTo to copy it into a byte array. I have tested locally by converting it back with new BitArray(mybytearray) and comparing the result and it matches fine.

My question is, is this code going to be reliable? or will it be environment/hardware specific? do big/little endians come into effect here? when i deploy this to an azure service running on windows will it operate the same? would running off a linux vm cause the endianess to create wrong outputs? (a separate azure service will actually be the one reading from the blob but it should be configured the same i.e windows/plan)

I am a bit confused, while my code seems to be working fine, the below SO post accepted answer has comments saying that the way bitarray writes to bytearray the order will be reversed, so you should specifically reverse the array before putting it into the bytearray.
Convert from BitArray to Byte

This is a minimal code example of my logic (my case has hundreds of thousands of booleans):

```<code>     var boolarr = new bool[] { true, true, false, false, false };
            var bitarr = new BitArray(boolarr);
            var length = bitarr.Length / 8;
            if (bitarr.Length % 8 > 0)
                length += 1;
            var bytearray = new byte[length];
            bitarr.CopyTo(bytearray, 0);
            BitArray bits = new BitArray(bytearray);

//Below just checking the above is working properly
            for (var i = 0; i < bits.Length; i++)
            {
                if (i >= bitarr.Length)
                    break;//last byte may not be using all bits
                if (bits[i] != bitarr[i])
                {
                    throw new Exception();//This would be bad.
                }
            }

</code>```

答:
I think the code will be hardware specific, but to be honest, I don't know the inner workings of BitArray and I can't tell you for sure. But I can give you some code that will work regardless of the hardware/environment:

```<code>private const int bitsPerByte = 8;
public static byte[] ToByteArray(bool[] bits)
{
    var bitCount = bits.Length;
    var byteCount = bitCount / bitsPerByte ;
    if (bitCount - byteCount*bitsPerByte  > 0) byteCount += 1;
    var bytes = new byte[byteCount];
    for (int i = 0; i < bitCount; i++)
    {
        SetBit(bytes, i, bits[i]);
    }

    return bytes;
}

public static bool[] ToBoolArray(byte[] bytes)
{
    var bitCount = bytes.Length * bitsPerByte;
    var bools = new bool[bitCount];
    for (int i = 0; i < bitCount; i++)
    {
        bools[i] = GetBit(bytes, i);
    }

    return bools;
}
</code>```

This relies on the following helper code:

```<code>private static bool GetBit(byte[] bytes, int bitNumber)
{
    var byteNumber = bitNumber / bitsPerByte;
    var bit = bitNumber % bitsPerByte;
    return GetBit(bytes[byteNumber], bit);
}

private static bool GetBit(byte byteValue, int bitNumber) => (byteValue >> bitNumber) % 2 > 0;

private static void SetBit(byte[] bytes, int bitNumber, bool value)
{
    var byteNumber = bitNumber / bitsPerByte;
    var bit = bitNumber % bitsPerByte;
    SetBit(ref bytes[byteNumber], bit, value);
}

private static void SetBit(ref byte byteValue, int bitNumber, bool value)
{
    var operand = (byte)(1 << bitNumber);
    if (value)
    {
        byteValue |= operand;
    }
    else
    {
        operand = (byte)~operand;
        byteValue &= operand;
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am wanting to store a sequence of bool values in azure blob storage along with a separate map file (a comma separated list of names in the same order as the bool values).

As efficiency and storage are important factors I want to store the bool values as a byte array.

I have gone about this by constructing a bitarray, i am then using the bitarray CopyTo to copy it into a byte array. I have tested locally by converting it back with new BitArray(mybytearray) and comparing the result and it matches fine.

My question is, is this code going to be reliable? or will it be environment/hardware specific? do big/little endians come into effect here? when i deploy this to an azure service running on windows will it operate the same? would running off a linux vm cause the endianess to create wrong outputs? (a separate azure service will actually be the one reading from the blob but it should be configured the same i.e windows/plan)

I am a bit confused, while my code seems to be working fine, the below SO post accepted answer has comments saying that the way bitarray writes to bytearray the order will be reversed, so you should specifically reverse the array before putting it into the bytearray.
Convert from BitArray to Byte

This is a minimal code example of my logic (my case has hundreds of thousands of booleans):

     var boolarr = new bool[] { true, true, false, false, false };
            var bitarr = new BitArray(boolarr);
            var length = bitarr.Length / 8;
            if (bitarr.Length % 8 > 0)
                length += 1;
            var bytearray = new byte[length];
            bitarr.CopyTo(bytearray, 0);
            BitArray bits = new BitArray(bytearray);

//Below just checking the above is working properly
            for (var i = 0; i < bits.Length; i++)
            {
                if (i >= bitarr.Length)
                    break;//last byte may not be using all bits
                if (bits[i] != bitarr[i])
                {
                    throw new Exception();//This would be bad.
                }
            }

Body:
I think the code will be hardware specific, but to be honest, I don't know the inner workings of BitArray and I can't tell you for sure. But I can give you some code that will work regardless of the hardware/environment:

private const int bitsPerByte = 8;
public static byte[] ToByteArray(bool[] bits)
{
    var bitCount = bits.Length;
    var byteCount = bitCount / bitsPerByte ;
    if (bitCount - byteCount*bitsPerByte  > 0) byteCount += 1;
    var bytes = new byte[byteCount];
    for (int i = 0; i < bitCount; i++)
    {
        SetBit(bytes, i, bits[i]);
    }

    return bytes;
}

public static bool[] ToBoolArray(byte[] bytes)
{
    var bitCount = bytes.Length * bitsPerByte;
    var bools = new bool[bitCount];
    for (int i = 0; i < bitCount; i++)
    {
        bools[i] = GetBit(bytes, i);
    }

    return bools;
}

This relies on the following helper code:

private static bool GetBit(byte[] bytes, int bitNumber)
{
    var byteNumber = bitNumber / bitsPerByte;
    var bit = bitNumber % bitsPerByte;
    return GetBit(bytes[byteNumber], bit);
}

private static bool GetBit(byte byteValue, int bitNumber) => (byteValue >> bitNumber) % 2 > 0;

private static void SetBit(byte[] bytes, int bitNumber, bool value)
{
    var byteNumber = bitNumber / bitsPerByte;
    var bit = bitNumber % bitsPerByte;
    SetBit(ref bytes[byteNumber], bit, value);
}

private static void SetBit(ref byte byteValue, int bitNumber, bool value)
{
    var operand = (byte)(1 << bitNumber);
    if (value)
    {
        byteValue |= operand;
    }
    else
    {
        operand = (byte)~operand;
        byteValue &= operand;
    }
}


问:
Why 'blocked by CORS policy' in React, but not with Node?
Running the exact same script in React is blocked by Cors policy, but not when I run it with node.

Why can it be done with node, but not with React?

How can I still fetch this in a React app?

It's also allowed in this chrome extension, is that because the script is executed visiting youtube so that domain is youtube?

```<code>async function isThisAllowed() {
    const videoURL = `https://www.youtube.com/watch?v=QnQe0xW_JY4`
    const data = await axios.get(videoURL);
    console.log(data);
}
</code>```

答:
CORS is a way for websites (in this case YouTube) to prevent other domains from accessing them. Basically, in this case, scripts running on other domains will not be able to access youtube.com.

CORS is only enforced by browsers, so it makes sense that your Node script would work as expected while your React app wouldn't.

Here's a good explanation of how CORS works.

You could fix this with a simple Node proxy:

```<code>import express from "express";
import axios from "axios";

const app = express();

app.get("/proxy", async (req, res) => {
  const resp = await axios.get(req.query.url);

  res.send(resp.data);
});

app.listen(process.env.PORT || 3000);
</code>```

Body:
Running the exact same script in React is blocked by Cors policy, but not when I run it with node.

Why can it be done with node, but not with React?

How can I still fetch this in a React app?

It's also allowed in this chrome extension, is that because the script is executed visiting youtube so that domain is youtube?

async function isThisAllowed() {
    const videoURL = `https://www.youtube.com/watch?v=QnQe0xW_JY4`
    const data = await axios.get(videoURL);
    console.log(data);
}

Body:
CORS is a way for websites (in this case YouTube) to prevent other domains from accessing them. Basically, in this case, scripts running on other domains will not be able to access youtube.com.

CORS is only enforced by browsers, so it makes sense that your Node script would work as expected while your React app wouldn't.

Here's a good explanation of how CORS works.

You could fix this with a simple Node proxy:

import express from "express";
import axios from "axios";

const app = express();

app.get("/proxy", async (req, res) => {
  const resp = await axios.get(req.query.url);

  res.send(resp.data);
});

app.listen(process.env.PORT || 3000);


问:
How I can remove this nested for loops, it take too much time
```<code>for i,row_1 in df_1.iterrows():
   for j, row_2 in df_2.iterrows():
      if row_1['RECKEY'] == row_2['RECKEY']:
         df_1.loc[i ,'RECKEY'] = df_2.loc[j ,'RECKEY_NEW']
</code>```

How do I build a filter which does this?

I tried the following without any success.

```<code>df_1.loc[df_1.RECKEY.isin(df_2.RECKEY), 'RECKEY'] = df_2.loc['RECKEY_NEW']
</code>```

Output:

```<code>Index: [])
'RECKEY_NEW'
</code>```

答:
You should use merge, that will solve your problem.</p>
```<code>new_df = df_1.merge(df_2[['RECKEY_NEW','RECKEY']], left_on='RECKEY',
right_on='RECKEY')
new_df['RECKEY'] = new_df['RECKEY_NEW'].astype(int)
</code>```

Body:
for i,row_1 in df_1.iterrows():
   for j, row_2 in df_2.iterrows():
      if row_1['RECKEY'] == row_2['RECKEY']:
         df_1.loc[i ,'RECKEY'] = df_2.loc[j ,'RECKEY_NEW']

How do I build a filter which does this?

I tried the following without any success.

df_1.loc[df_1.RECKEY.isin(df_2.RECKEY), 'RECKEY'] = df_2.loc['RECKEY_NEW']

Output:

Index: [])
'RECKEY_NEW'

Body:
You should use merge, that will solve your problem.

new_df = df_1.merge(df_2[['RECKEY_NEW','RECKEY']], left_on='RECKEY',
right_on='RECKEY')
new_df['RECKEY'] = new_df['RECKEY_NEW'].astype(int)


问:
Advantage of switching from ASP.NET to bread & butter HTML/jQuery
I have been getting more and more sick of all the quirks about control ids, trying to get your data in serverside (based on client-side events). I seem to spend more time fighting with controls in asp.net, that I think it takes me more time than I gain by using it.

I was thinking about using plain html/javascript with jQuery and a web service that returns json for the data.

The only thing I think I would miss from webforms is the MasterPages, the session management, authentication based on windows login and possibly validators(although they have some quirks too). (In fact, maybe not for sessions and auth, but I have never developped webservices)

Is there something wrong with the way
I am thinking about this, or
something I didn't think about ?

Are there things in asp.net that you
think I will miss ?

Has anyone done this before and wants to share experience ?

Please, also take note, that I only have the Framework 2.0 available for development.

Edit: The kind of things giving me troubles in asp.net that makes me wonder for the switch:

Here is a sample of a page giving me problems.

There is a tree table (master / details)

You can edit fields on each child row.

When you press the save button, the data from the group row must be updated (just data from a select, no modification in database), as
the data from the child row.

I don't want to refresh the whole page because the displayed records are based from search criterias.

The Master / Details are generated using Repeaters

Trying to update a record from code behind is really quirky, and still have no clue about updating the display.

Using jQuery and a web service, my guess would be that i could update directly to the database, request what I want to be displayed and just update that record. This is the kind of things that make me wonder if asp.net is just getting in my way.

```

 ________________________________________________________________________
| -  Some             Details           About            Group           |
|________________________________________________________________________|
    |¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    |_______________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|

```

Edit2:
The problem I have about ASP.NET is not related to ajax. Yes, I use jQuery to make the interfaces more dynamic like showing / hiding the search section when not needed and collapsing details from the tree, but this is all I do with it.

What bothers me is that if I want to check which button has been clicked in this example, I have to use some tricks that feel a bit haky.

If you want to use databound comboboxes in a repeater, you have to use codebehind to set the selected value, it will be a pain to retreive the data selected.

Next, if you want to check what data was modified, you have to save the datatable in the viewstate, read data from all controls in the repeater, then compare with the datatable to make an update. This is this kind of things that bother me with asp.net.

答:
If used properly, ASP.NET and JavaScript/jQuery web applications really can compliment each other.  I have now implemented jQuery in 3 different web applications and am loving every minute of it.  So long as you use each component to its strength, you'll end up being happy with the project in the end.

You specifically mentioned that Control ID's were causing a problem, but its really not that big of a deal.

JavaScript

```<code>document.getElementById("<%=this.MyObject.ClientID %>");
</code>```

jQuery

```<code>$("#<%=this.MyObject.ClientID %>")....
</code>```

In your example of a parent child relationship, you can very easily handle exactly what you are discussing with ASP.NET and the AJAX framework with UpdatePanels.

OwnerDisplayName: Martin

ContentLicense: CC BY-SA 2.5

Body:
I have been getting more and more sick of all the quirks about control ids, trying to get your data in serverside (based on client-side events). I seem to spend more time fighting with controls in asp.net, that I think it takes me more time than I gain by using it.

I was thinking about using plain html/javascript with jQuery and a web service that returns json for the data.

The only thing I think I would miss from webforms is the MasterPages, the session management, authentication based on windows login and possibly validators(although they have some quirks too). (In fact, maybe not for sessions and auth, but I have never developped webservices)

Is there something wrong with the way
I am thinking about this, or
something I didn't think about ?

Are there things in asp.net that you
think I will miss ?

Has anyone done this before and wants to share experience ?

Please, also take note, that I only have the Framework 2.0 available for development.

Edit: The kind of things giving me troubles in asp.net that makes me wonder for the switch:

Here is a sample of a page giving me problems.

There is a tree table (master / details)

You can edit fields on each child row.

When you press the save button, the data from the group row must be updated (just data from a select, no modification in database), as
the data from the child row.

I don't want to refresh the whole page because the displayed records are based from search criterias.

The Master / Details are generated using Repeaters

Trying to update a record from code behind is really quirky, and still have no clue about updating the display.

Using jQuery and a web service, my guess would be that i could update directly to the database, request what I want to be displayed and just update that record. This is the kind of things that make me wonder if asp.net is just getting in my way.

 ________________________________________________________________________
| -  Some             Details           About            Group           |
|________________________________________________________________________|
    |¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    |_______________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|

Edit2:
The problem I have about ASP.NET is not related to ajax. Yes, I use jQuery to make the interfaces more dynamic like showing / hiding the search section when not needed and collapsing details from the tree, but this is all I do with it.

What bothers me is that if I want to check which button has been clicked in this example, I have to use some tricks that feel a bit haky.

If you want to use databound comboboxes in a repeater, you have to use codebehind to set the selected value, it will be a pain to retreive the data selected.

Next, if you want to check what data was modified, you have to save the datatable in the viewstate, read data from all controls in the repeater, then compare with the datatable to make an update. This is this kind of things that bother me with asp.net.

LastEditorDisplayName: Martin

Body:
If used properly, ASP.NET and JavaScript/jQuery web applications really can compliment each other.  I have now implemented jQuery in 3 different web applications and am loving every minute of it.  So long as you use each component to its strength, you'll end up being happy with the project in the end.

You specifically mentioned that Control ID's were causing a problem, but its really not that big of a deal.

JavaScript

document.getElementById("<%=this.MyObject.ClientID %>");

jQuery

$("#<%=this.MyObject.ClientID %>")....

In your example of a parent child relationship, you can very easily handle exactly what you are discussing with ASP.NET and the AJAX framework with UpdatePanels.

OwnerDisplayName: RSolberg

LastEditorDisplayName: RSolberg


问:
GCloud Vision API's NewImageAnnotatorClient throwing Permission Denied using option.WithCredentialsFile
I have two GCP projects, projectA for kubernetes resources and projectB for product-search-api and spanner database. I created a service account in projectB with required permissions and mount its credentials.json to the service in projectA as GOOGLE_APPLICATION_CREDENTIALS env var and it works well.

But because of this there are some other permissions issue for the service using features in projectA for eg. stackdriver monitoring etc. I could grant these permissions to the service account I created but I then found a ClientOption - withCredentialsFile.

I planned to use this option without modifying GOOGLE_APPLICATION_CREDENTIALS env var in the service i.e. keep using projectA credentials. So, I passed it to spanner client like below and it works well

```<code>client, err := spanner.NewClientWithConfig(context, dbn, spanner.ClientConfig{
        SessionPoolConfig: spanner.SessionPoolConfig{
            MaxIdle: 100,
        },
    }, option.WithCredentialsFile(cfg.CredsPathtoProjectB))
</code>```

But when I pass it to vision.NewImageAnnotatorClient to make request to ProductSearchAPI, I get Permission Denied.

```<code>c, err := vision.NewImageAnnotatorClient(context, option.WithCredentialsFile(cfg.CredsPathtoProjectB))
ictx := &pb.ImageContext{
    ProductSearchParams: &pb.ProductSearchParams{
        ProductSet:        fmt.Sprintf("projects/%s/locations/%s/productSets/%s", cfg.ProjectID, cfg.ProjectLocation, cfg.ProductSetID),
        ProductCategories: []string{cfg.ProductCategory},
        Filter:            filter,
    },
}
response, err := c.AnnotateImage(ctx, &pb.AnnotateImageRequest{
    Image:        img,
    ImageContext: ictx,
    Features:     []*pb.Feature{{Type: visionpb.Feature_PRODUCT_SEARCH,
    MaxResults: int32(maxItems)}},
})
------------------------
<OUTPUT>
"response:":"error:{code:7 message:\"Permission denied.\"}"
</code>```

I could use same credentials to request product search API when overwriting GOOGLE_APPLICATION_CREDENTIALS. Am I making any mistake?

答: You don't need Owner's permission on the service account. However, if the product search resources are in projectB, then you have to call Vision API with a service account from projectB.</p>

Body:
I have two GCP projects, projectA for kubernetes resources and projectB for product-search-api and spanner database. I created a service account in projectB with required permissions and mount its credentials.json to the service in projectA as GOOGLE_APPLICATION_CREDENTIALS env var and it works well.

But because of this there are some other permissions issue for the service using features in projectA for eg. stackdriver monitoring etc. I could grant these permissions to the service account I created but I then found a ClientOption - withCredentialsFile.

I planned to use this option without modifying GOOGLE_APPLICATION_CREDENTIALS env var in the service i.e. keep using projectA credentials. So, I passed it to spanner client like below and it works well

client, err := spanner.NewClientWithConfig(context, dbn, spanner.ClientConfig{
        SessionPoolConfig: spanner.SessionPoolConfig{
            MaxIdle: 100,
        },
    }, option.WithCredentialsFile(cfg.CredsPathtoProjectB))

But when I pass it to vision.NewImageAnnotatorClient to make request to ProductSearchAPI, I get Permission Denied.

c, err := vision.NewImageAnnotatorClient(context, option.WithCredentialsFile(cfg.CredsPathtoProjectB))
ictx := &pb.ImageContext{
    ProductSearchParams: &pb.ProductSearchParams{
        ProductSet:        fmt.Sprintf("projects/%s/locations/%s/productSets/%s", cfg.ProjectID, cfg.ProjectLocation, cfg.ProductSetID),
        ProductCategories: []string{cfg.ProductCategory},
        Filter:            filter,
    },
}
response, err := c.AnnotateImage(ctx, &pb.AnnotateImageRequest{
    Image:        img,
    ImageContext: ictx,
    Features:     []*pb.Feature{{Type: visionpb.Feature_PRODUCT_SEARCH,
    MaxResults: int32(maxItems)}},
})
------------------------
<OUTPUT>
"response:":"error:{code:7 message:\"Permission denied.\"}"

I could use same credentials to request product search API when overwriting GOOGLE_APPLICATION_CREDENTIALS. Am I making any mistake?


问:
How to update cells in a spreadsheet without the values on the list repeating on openpyxl
I'm new to programming so sorry the silly question.

I have been trying to develop a spreadsheet on excel that updates the duties of staff members from a certain list.

For example I have this code:

```<code>senior_duties = ['SOPs', 'EQA review', 'Doc review', 'NC review', 'Trend analysis']

senior_duties1 = random.choice(senior_duties)

#Staff member 1

sheet["D5"] = senior_duties1
sheet["D6"] = senior_duties1

#Staff member 2

sheet["E5"] = senior_duties1
sheet["E6"] = senior_duties1
</code>```

I understand that this only prints random values from the list that some times repeat and duplicate between two staff members.

I want the code to print something new for each staff member from the list every time the script is run. I'm sure the solution involves a 'for' loop but I just can't seem to solve it.

Any help will be appreciated!

答:
If you want to randomly assign the duties to each staff member, just shuffle the list and assign the duties from the list.

```<code>import random

senior_duties = ['SOPs', 'EQA review', 'Doc review', 'NC review', 'Trend analysis']

random.shuffle(senior_duties)

# Staff member 1

sheet["D5"] = senior_duties[0]
sheet["D6"] = senior_duties[0]

# Staff member 2

sheet["E5"] = senior_duties[1]
sheet["E6"] = senior_duties[1]
</code>```

This will give you a random duty assignment every time you run the script, however if you want an assignment that has not been done yet, you will need to add further logic

Body:
I'm new to programming so sorry the silly question.

I have been trying to develop a spreadsheet on excel that updates the duties of staff members from a certain list.

For example I have this code:

senior_duties = ['SOPs', 'EQA review', 'Doc review', 'NC review', 'Trend analysis']

senior_duties1 = random.choice(senior_duties)

#Staff member 1

sheet["D5"] = senior_duties1
sheet["D6"] = senior_duties1

#Staff member 2

sheet["E5"] = senior_duties1
sheet["E6"] = senior_duties1

I understand that this only prints random values from the list that some times repeat and duplicate between two staff members.

I want the code to print something new for each staff member from the list every time the script is run. I'm sure the solution involves a 'for' loop but I just can't seem to solve it.

Any help will be appreciated!

Body:
If you want to randomly assign the duties to each staff member, just shuffle the list and assign the duties from the list.

import random

senior_duties = ['SOPs', 'EQA review', 'Doc review', 'NC review', 'Trend analysis']

random.shuffle(senior_duties)

# Staff member 1

sheet["D5"] = senior_duties[0]
sheet["D6"] = senior_duties[0]

# Staff member 2

sheet["E5"] = senior_duties[1]
sheet["E6"] = senior_duties[1]

This will give you a random duty assignment every time you run the script, however if you want an assignment that has not been done yet, you will need to add further logic


问:
.NET 6 (ASP.NET Core 6.0) get Startup or Program Assembly from Test project
In .NET Core 3.1 and .NET 5, we had an Xunit test like the example below. It makes sure every Controller has an AuthorizeAttribute to prevent security leaks.

When upgrading our web project to ASP.NET Core 6's minimal hosting model, the Program and Startup classes are no longer needed. Everything works fine, except for the following:

var types = typeof(Startup).Assembly.GetTypes();
```
<p>Looking at the namespace <code>Example.Web</code>, I can't see any classes to load assemblies from, either. How can the <code>Program.cs</code> assembly be loaded in .NET 6?</p>
<p>Example from .NET 5:</p>
```using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;

namespace Example.Web.Tests.ControllerTests
{
    public class AuthorizeAttributeTest
    {
        [Fact]
        public void ApiAndMVCControllersShouldHaveAuthorizeAttribute()
        {
            var controllers = GetChildTypes<ControllerBase>();
            foreach (var controller in controllers)
            {
                var attribute = Attribute.GetCustomAttribute(controller, typeof(Microsoft.AspNetCore.Authorization.AuthorizeAttribute), true) as Microsoft.AspNetCore.Authorization.AuthorizeAttribute;
                Assert.NotNull(attribute);
            }
        }

        private static IEnumerable<Type> GetChildTypes<T>()
        {
            var types = typeof(Startup).Assembly.GetTypes();
            return types.Where(t => t.IsSubclassOf(typeof(T)) && !t.IsAbstract);
        }
    }
}
```

答:
The quick answer is that you can reference any (accessible) class in your application in order to get a reference to the assembly. It needn't be the Program or Startup class, and it needn't be in the root namespace.

You'll obviously want to choose a class you expect to be persistent, and not subject to being renamed or removed in later versions. Historically, the Startup class fit that criteria. With the ASP.NET Core 6 minimal hosting model, however, that's obviously not true anymore.

Given this, there are two approaches you can take here.

Option 1: Anchor your Assembly reference off of an application class

The first option is to anchor off of any arbitrary, public class from your application. For example, you could use one of your controllers. So long as it's compiled into the same assembly, the Assembly.GetTypes() call will yield the same results. This might look like e.g.:

using Example.Web.Controllers;

var types = typeof(ExampleController).Assembly.GetTypes();
```
<p>The main downside of this approach is that the class is completely arbitrary, and could potentially be moved or renamed in the future. Of course, if that <em>did</em> happen, you'll likely need to update your unit tests anyway, so it's not that big of a deal.</p>
<h3>Option 2: Expose your <code>Program</code> class to your test assembly</h3>
<p>Another option is to anchor your <code>Assembly</code> reference off of the class compiled from your <code>Program.cs</code> file, which is very similar to your previous approach. This requires understanding a bit about how this file is processed by the compiler.</p>
<p>When you use the ASP.NET Core 6 minimal hosting model, you're actually taking advantage of C# 9's top-level statements. The compiler automatically places any top-level statements into a class named <code>Program</code>, without a namespace.</p>
<blockquote>
<p><em><strong>Note:</strong></em> That happens to align with your use of <code>Program.cs</code>, but that's completely incidental; you could rename <code>Program.cs</code> to <code>MyWebApplication.cs</code>, but the class will <em>still</em> be named <code>Program</code>.</p>
</blockquote>
<p><em>The problem is that this</em> <code>Program</code> <em>class is marked as</em> <code>internal</code>, <em>and thus not accessible to your unit test assembly.</em></p>
<p>You can work around that, however, by marking your ASP.NET Core assembly's internals as visible to your unit test assembly. This can be done by adding the following to e.g. your <code>AssemblyInfo.cs</code>:</p>
<pre class="lang-cs prettyprint-override"><code>[assembly: InternalsVisibleTo("Example.Web.Tests")]
</code>```

Or, as @kal pointed out in the comments, by setting the following in your csproj file:

<ItemGroup>
    <InternalsVisibleTo Include="Example.Web.Tests" />
</ItemGroup>
```
<p>Once this is done, you can access your <code>Program</code> class using:</p>
<pre class="lang-cs prettyprint-override"><code>var types = typeof(Program).Assembly.GetTypes();
</code>```

I'm not a big fan of exposing the internals of my assembly in this way, but it's fairly common practice with unit tests, so I'm including it as an option in case you're already doing this.

Ultimately, this really isn't any different from the first option—you're still anchoring your Assembly reference off of a different class—but it has the advantage of being anchored to a class we know will always be present, and not some arbitrary, application-specific class. That may also feel more intuitive when reading the code.

Body:
In .NET Core 3.1 and .NET 5, we had an Xunit test like the example below. It makes sure every Controller has an AuthorizeAttribute to prevent security leaks.

When upgrading our web project to ASP.NET Core 6's minimal hosting model, the Program and Startup classes are no longer needed. Everything works fine, except for the following:

var types = typeof(Startup).Assembly.GetTypes();

Looking at the namespace Example.Web, I can't see any classes to load assemblies from, either. How can the Program.cs assembly be loaded in .NET 6?

Example from .NET 5:

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;

namespace Example.Web.Tests.ControllerTests
{
    public class AuthorizeAttributeTest
    {
        [Fact]
        public void ApiAndMVCControllersShouldHaveAuthorizeAttribute()
        {
            var controllers = GetChildTypes<ControllerBase>();
            foreach (var controller in controllers)
            {
                var attribute = Attribute.GetCustomAttribute(controller, typeof(Microsoft.AspNetCore.Authorization.AuthorizeAttribute), true) as Microsoft.AspNetCore.Authorization.AuthorizeAttribute;
                Assert.NotNull(attribute);
            }
        }

        private static IEnumerable<Type> GetChildTypes<T>()
        {
            var types = typeof(Startup).Assembly.GetTypes();
            return types.Where(t => t.IsSubclassOf(typeof(T)) && !t.IsAbstract);
        }
    }
}

Body:
The quick answer is that you can reference any (accessible) class in your application in order to get a reference to the assembly. It needn't be the Program or Startup class, and it needn't be in the root namespace.

You'll obviously want to choose a class you expect to be persistent, and not subject to being renamed or removed in later versions. Historically, the Startup class fit that criteria. With the ASP.NET Core 6 minimal hosting model, however, that's obviously not true anymore.

Given this, there are two approaches you can take here.

Option 1: Anchor your Assembly reference off of an application class

The first option is to anchor off of any arbitrary, public class from your application. For example, you could use one of your controllers. So long as it's compiled into the same assembly, the Assembly.GetTypes() call will yield the same results. This might look like e.g.:

using Example.Web.Controllers;

var types = typeof(ExampleController).Assembly.GetTypes();

The main downside of this approach is that the class is completely arbitrary, and could potentially be moved or renamed in the future. Of course, if that did happen, you'll likely need to update your unit tests anyway, so it's not that big of a deal.

Option 2: Expose your Program class to your test assembly

Another option is to anchor your Assembly reference off of the class compiled from your Program.cs file, which is very similar to your previous approach. This requires understanding a bit about how this file is processed by the compiler.

When you use the ASP.NET Core 6 minimal hosting model, you're actually taking advantage of C# 9's top-level statements. The compiler automatically places any top-level statements into a class named Program, without a namespace.

Note: That happens to align with your use of Program.cs, but that's completely incidental; you could rename Program.cs to MyWebApplication.cs, but the class will still be named Program.

The problem is that this Program class is marked as internal, and thus not accessible to your unit test assembly.

You can work around that, however, by marking your ASP.NET Core assembly's internals as visible to your unit test assembly. This can be done by adding the following to e.g. your AssemblyInfo.cs:

[assembly: InternalsVisibleTo("Example.Web.Tests")]

Or, as @kal pointed out in the comments, by setting the following in your csproj file:

<ItemGroup>
    <InternalsVisibleTo Include="Example.Web.Tests" />
</ItemGroup>

Once this is done, you can access your Program class using:

var types = typeof(Program).Assembly.GetTypes();

I'm not a big fan of exposing the internals of my assembly in this way, but it's fairly common practice with unit tests, so I'm including it as an option in case you're already doing this.

Ultimately, this really isn't any different from the first option—you're still anchoring your Assembly reference off of a different class—but it has the advantage of being anchored to a class we know will always be present, and not some arbitrary, application-specific class. That may also feel more intuitive when reading the code.


问:
How to retrieve the title property from my Campaign Contract to display it in my render method
I'm developing a crowdfunding DApp that constantly needs to access the contract variables through function calls in order to retrieve them.

The getDeployedCampaigns function returns an array of deployed campaign's addresses. They then get passed down to a map function in order to create a react component with the corresponding address on it.

In the ideal scenario I would like to be able to also retrieve and use the campaignTitle variable inside the campaign contract but I'm having lots of trouble in finding a way of doing so without breaking the whole rendering program.

This is how the code is currently working

```<code>import { Card, Button } from "semantic-ui-react";
import factory from "../ethereum/factory";
import Layout from "../components/Layout";
import { Link } from "../routes";

class CampaignIndex extends Component {
  static async getInitialProps() {
    const campaigns = await factory.methods.getDeployedCampaigns().call();

    return { campaigns };
  }
  renderCampaigns() {
    const items = this.props.campaigns.map((address) => {
      return {
        header: address,
        description: (
          <Link route={`/campaigns/${address}`}>
            <a>View Campaign</a>
          </Link>
        ),
        fluid: true,
      };
    });
    return <Card.Group items={items} />;
  }
  render() {
    return (
      <Layout>
        <div>
          <h3>Open Campaigns</h3>
          <Link route="/campaigns/new">
            <a>
              <Button
                floated="right"
                content="Create Campaign"
                icon="add circle"
                primary
              />
            </a>
          </Link>
          {this.renderCampaigns()}
        </div>
      </Layout>
    );
  }
}

export default CampaignIndex;
</code>```

And this is what I am trying to do but is not working at all

```<code>import { Card, Button } from 'semantic-ui-react';
import factory from '../ethereum/factory';
import Layout from '../components/Layout';
import { Link } from '../routes';
import Campaign from '../ethereum/campaign';

class CampaignIndex extends Component {
  static async getInitialProps() {
    const campaigns = await factory.methods.getDeployedCampaigns().call();

    const campaignInfo = Promise.all(
      campaigns.map(async (address) => {
        const campaign = Campaign(address);
        const title = await campaign.methods.campaignTitle().call();

        return {
          header: title,
          meta: address,
          description: (
            <Link route={`/campaigns/${address}`}>
              <a>View Campaign</a>
            </Link>
          ),
          fluid: true,
        };
      })
    );

    return { campaignInfo };
  }
  renderCampaigns() {
    const items = this.props.campaignInfo;
    return <Card.Group items={items} />;
  }
  render() {
    return (
      <Layout>
        <div>
          <h3>Open Campaigns</h3>
          <Link route="/campaigns/new">
            <a>
              <Button
                floated="right"
                content="Create Campaign"
                icon="add circle"
                primary
              />
            </a>
          </Link>
          {this.renderCampaigns()}
        </div>
      </Layout>
    );
  }
}

export default CampaignIndex;
</code>```

And the Smart Contract for you to see

```<code>
contract CampaignFactory {
    address[] public deployedCampaigns;

    function createCampaign(uint minimum, string title, string description) public {
        address newCampaign = new Campaign(minimum, msg.sender, title, description);
        deployedCampaigns.push(newCampaign);
    }

    function getDeployedCampaigns() public view returns (address[]) {
        return deployedCampaigns;
    }
}

contract Campaign {
    struct Request {
        string description;
        uint value;
        address recipient;
        bool complete;
        uint approvalCount;
        mapping(address => bool) approvals;
    }

    Request[] public requests;
    address public manager;
    uint public minimumContribution;
    string public campaignTitle;
    string public campaignDescription;
    mapping(address => bool) public approvers;
    uint public approversCount;

    modifier restricted() {
        require(msg.sender == manager);
        _;
    }

    function Campaign(uint minimum, address creator, string givenTitle, string givenDescription) public {
        manager = creator;
        minimumContribution = minimum;
        campaignTitle = givenTitle;
        campaignDescription = givenDescription;

    }

    function contribute() public payable {
        require(msg.value > minimumContribution);

        approvers[msg.sender] = true;
        approversCount++;
    }

    function createRequest(string description, uint value, address recipient) public restricted {
        Request memory newRequest = Request({
           description: description,
           value: value,
           recipient: recipient,
           complete: false,
           approvalCount: 0
        });

        requests.push(newRequest);
    }

    function approveRequest(uint index) public {
        Request storage request = requests[index];

        require(approvers[msg.sender]);
        require(!request.approvals[msg.sender]);

        request.approvals[msg.sender] = true;
        request.approvalCount++;
    }

    function finalizeRequest(uint index) public restricted {
        Request storage request = requests[index];

        require(request.approvalCount > (approversCount / 2));
        require(!request.complete);

        request.recipient.transfer(request.value);
        request.complete = true;
    }

    function getSummary() public view returns (
      uint, uint, uint, uint, address
      ) {
        return (
          minimumContribution,
          this.balance,
          requests.length,
          approversCount,
          manager
        );
    }

    function getRequestsCount() public view returns (uint) {
        return requests.length;
    }
}
</code>```

答:
In the factory contract, you are returning an array of items directly, Which means you are using a newer version of solidity. However, in Campaign contract, you are using function Campaign which is meant to be used as a constructor in early versions of solidity. If you are using newer version of solidity, you initialize the contract with the constructor keyword, since you do not use constructor you are not assigning value to title.

Instead of function Campaign use constructor

```<code>constructor(uint minimum, address creator, string givenTitle, string givenDescription) {
        manager = creator;
        minimumContribution = minimum;
        campaignTitle = givenTitle;
        campaignDescription = givenDescription;

    }
</code>```

Body:
I'm developing a crowdfunding DApp that constantly needs to access the contract variables through function calls in order to retrieve them.

The getDeployedCampaigns function returns an array of deployed campaign's addresses. They then get passed down to a map function in order to create a react component with the corresponding address on it.

In the ideal scenario I would like to be able to also retrieve and use the campaignTitle variable inside the campaign contract but I'm having lots of trouble in finding a way of doing so without breaking the whole rendering program.

This is how the code is currently working

import { Card, Button } from "semantic-ui-react";
import factory from "../ethereum/factory";
import Layout from "../components/Layout";
import { Link } from "../routes";

class CampaignIndex extends Component {
  static async getInitialProps() {
    const campaigns = await factory.methods.getDeployedCampaigns().call();

    return { campaigns };
  }
  renderCampaigns() {
    const items = this.props.campaigns.map((address) => {
      return {
        header: address,
        description: (
          <Link route={`/campaigns/${address}`}>
            View Campaign
          </Link>
        ),
        fluid: true,
      };
    });
    return <Card.Group items={items} />;
  }
  render() {
    return (
      <Layout>

Open Campaigns

          <Link route="/campaigns/new">

              <Button
                floated="right"
                content="Create Campaign"
                icon="add circle"
                primary
              />

          </Link>
          {this.renderCampaigns()}

      </Layout>
    );
  }
}

export default CampaignIndex;

And this is what I am trying to do but is not working at all

import { Card, Button } from 'semantic-ui-react';
import factory from '../ethereum/factory';
import Layout from '../components/Layout';
import { Link } from '../routes';
import Campaign from '../ethereum/campaign';

class CampaignIndex extends Component {
  static async getInitialProps() {
    const campaigns = await factory.methods.getDeployedCampaigns().call();

    const campaignInfo = Promise.all(
      campaigns.map(async (address) => {
        const campaign = Campaign(address);
        const title = await campaign.methods.campaignTitle().call();

        return {
          header: title,
          meta: address,
          description: (
            <Link route={`/campaigns/${address}`}>
              View Campaign
            </Link>
          ),
          fluid: true,
        };
      })
    );

    return { campaignInfo };
  }
  renderCampaigns() {
    const items = this.props.campaignInfo;
    return <Card.Group items={items} />;
  }
  render() {
    return (
      <Layout>

Open Campaigns

          <Link route="/campaigns/new">

              <Button
                floated="right"
                content="Create Campaign"
                icon="add circle"
                primary
              />

          </Link>
          {this.renderCampaigns()}

      </Layout>
    );
  }
}

export default CampaignIndex;

And the Smart Contract for you to see

contract CampaignFactory {
    address[] public deployedCampaigns;

    function createCampaign(uint minimum, string title, string description) public {
        address newCampaign = new Campaign(minimum, msg.sender, title, description);
        deployedCampaigns.push(newCampaign);
    }

    function getDeployedCampaigns() public view returns (address[]) {
        return deployedCampaigns;
    }
}

contract Campaign {
    struct Request {
        string description;
        uint value;
        address recipient;
        bool complete;
        uint approvalCount;
        mapping(address => bool) approvals;
    }

    Request[] public requests;
    address public manager;
    uint public minimumContribution;
    string public campaignTitle;
    string public campaignDescription;
    mapping(address => bool) public approvers;
    uint public approversCount;

    modifier restricted() {
        require(msg.sender == manager);
        _;
    }

    function Campaign(uint minimum, address creator, string givenTitle, string givenDescription) public {
        manager = creator;
        minimumContribution = minimum;
        campaignTitle = givenTitle;
        campaignDescription = givenDescription;

    }

    function contribute() public payable {
        require(msg.value > minimumContribution);

        approvers[msg.sender] = true;
        approversCount++;
    }

    function createRequest(string description, uint value, address recipient) public restricted {
        Request memory newRequest = Request({
           description: description,
           value: value,
           recipient: recipient,
           complete: false,
           approvalCount: 0
        });

        requests.push(newRequest);
    }

    function approveRequest(uint index) public {
        Request storage request = requests[index];

        require(approvers[msg.sender]);
        require(!request.approvals[msg.sender]);

        request.approvals[msg.sender] = true;
        request.approvalCount++;
    }

    function finalizeRequest(uint index) public restricted {
        Request storage request = requests[index];

        require(request.approvalCount > (approversCount / 2));
        require(!request.complete);

        request.recipient.transfer(request.value);
        request.complete = true;
    }

    function getSummary() public view returns (
      uint, uint, uint, uint, address
      ) {
        return (
          minimumContribution,
          this.balance,
          requests.length,
          approversCount,
          manager
        );
    }

    function getRequestsCount() public view returns (uint) {
        return requests.length;
    }
}

Body:
In the factory contract, you are returning an array of items directly, Which means you are using a newer version of solidity. However, in Campaign contract, you are using function Campaign which is meant to be used as a constructor in early versions of solidity. If you are using newer version of solidity, you initialize the contract with the constructor keyword, since you do not use constructor you are not assigning value to title.

Instead of function Campaign use constructor

constructor(uint minimum, address creator, string givenTitle, string givenDescription) {
        manager = creator;
        minimumContribution = minimum;
        campaignTitle = givenTitle;
        campaignDescription = givenDescription;

    }


问:
Lisp: Setting element in one row results in setting that element in every row (list of lists)?
I am setting the element at row 1, column 1 of a 2D Matrix represented as a list of lists result in setting all elements at column 1 of the 2D Matrix? It is required that I rerpresent the 2D matrix as a list of lists. Below is my code:

```<code>(defvar matrix (make-list 5 :initial-element (make-list 5)))
(print (format nil "matrix (before) = ~a" matrix))
(setf (nth 1 (nth 1 matrix)) 1)
(print (format nil "matrix (after) = ~a" matrix))
</code>```

With the following output:

"matrix (before) =  ((NIL NIL NIL NIL NIL) (NIL NIL NIL NIL NIL) (NIL
NIL NIL NIL NIL)  (NIL NIL NIL NIL NIL) (NIL NIL NIL NIL NIL))"

"matrix (after) =  ((NIL 1 NIL NIL NIL) (NIL 1 NIL NIL NIL) (NIL 1 NIL
NIL NIL)  (NIL 1 NIL NIL NIL) (NIL 1 NIL NIL NIL))"

This seems strange, considering that I only set an element in the 2D matrix once.

答:
It is a somewhat subtle bug. When you call (make-list 5 :initial-element (make-list 5), the inner (make-list 5) is evaluated before being passed to the outer make-list. As a result, each row of your matrix points to the same list in memory. Therefore all rows of your matrix reference the same location in memory.

To resolve the issue, I recommend (loop repeat 5 collect (make-list 5)) instead.

Body:
I am setting the element at row 1, column 1 of a 2D Matrix represented as a list of lists result in setting all elements at column 1 of the 2D Matrix? It is required that I rerpresent the 2D matrix as a list of lists. Below is my code:

(defvar matrix (make-list 5 :initial-element (make-list 5)))
(print (format nil "matrix (before) = ~a" matrix))
(setf (nth 1 (nth 1 matrix)) 1)
(print (format nil "matrix (after) = ~a" matrix))

With the following output:

"matrix (before) =  ((NIL NIL NIL NIL NIL) (NIL NIL NIL NIL NIL) (NIL
NIL NIL NIL NIL)  (NIL NIL NIL NIL NIL) (NIL NIL NIL NIL NIL))"

"matrix (after) =  ((NIL 1 NIL NIL NIL) (NIL 1 NIL NIL NIL) (NIL 1 NIL
NIL NIL)  (NIL 1 NIL NIL NIL) (NIL 1 NIL NIL NIL))"

This seems strange, considering that I only set an element in the 2D matrix once.


问:
Generate two same random alpha-numeric strings in different java programs
I am looking to see if there is a possibility to generate two same alpha-numeric strings in two different java codes. This is for the purpose of secured communication between client and server.

Or is there an alternative way to do this?

I looked at the usual ways of public private key encryption and related stuff. For my requirement, I do not need such a mechanism as its kind of too much of standard stuff. I am kind of looking for a simple alternative like this.

Thanks,
Abishek

答:
I think what you're looking for is akin to a time-synchronized one-time password.

A simplistic way to do this is to use the system time, rounded to the nearest, say, 6-second 'pulse' as a seed for a cryptographically secure random number generator (Java provides SecureRandom FWIW). Then, along with a pre-shared 'secret' put that through a one-way cryptographic hash (say, SHA256) to generate your alpha-numeric (hex or base64) string.

If you don't need to display/pass along the actual string, then I suppose you can skip the hash step and just use the shared secret and the synchronized time as the IV + key for a cipher applied to the communications stream on both ends.

The obvious risk or complication with this approach is keeping the two system clocks in sync. If you use NTP or some other time synchronization protocol, then you have to secure that as well (otherwise you're potentially open to a replay attack). Standard computer clocks are prone to drift (hence the 6-second window) and you have to secure them from tampering as well.

(Disclaimer: I am not a security specialist so don't think for a moment that what I've outlined about is completely secure/safe as is.)


问:
show default value in select input with backgroundcoulr different for each : react js
i have some select buttons displayed dynamicaly based on the user.subscription the values in user.subscription  can be 2 monthpack , 3 month pack, 6month pack, 12month pack,

so the value in  user.subscription` sould be selected as default when the maping loads in all

also  there must be differt colours for backgound of the slected button based on the default select button
button

if

2 month package is the default seleted then   defaultcolor  should be red

if

3  month package is the default seleted then   defaultcolor  should be green

if

6  month package is the default seleted then   defaultcolor should be yellow

if

12  month package is the default seleted then   defaultcolor  should be orange

```<code>{
  data.map((user) => (
    <select
      value={user.subscription}
      style={{ background: defaultcolor }}
      onChange={handleBackground}
    >
      <option value="white"> 2 month package</option>
      <option value="green">3 month package</option>
      <option value="red">6 month package</option>
      <option value="yellow">12 month package</option>
    </select>
  ));
}
</code>```

答:
you can hold a small 'configuration' object like this:

const monthToColor = {
  2: 'red',
  3: 'green',
  6: 'yellow',
  12: 'orange'
}```
</div>
</div>
</p>
<p>The keys should match the user.subscription options you have.</p>
<p>Now, for each option, add a style with background color of: monthToColor[user.subscription] like this:</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><option style={{ backgroundColor: monthToColor[user.subscription] }}>
  months
</options></code>```

Body:
i have some select buttons displayed dynamicaly based on the user.subscription the values in user.subscription  can be 2 monthpack , 3 month pack, 6month pack, 12month pack,

so the value in  user.subscription` sould be selected as default when the maping loads in all

also  there must be differt colours for backgound of the slected button based on the default select button
button

if

2 month package is the default seleted then   defaultcolor  should be red

if

3  month package is the default seleted then   defaultcolor  should be green

if

6  month package is the default seleted then   defaultcolor should be yellow

if

12  month package is the default seleted then   defaultcolor  should be orange

{
  data.map((user) => (
    <select
      value={user.subscription}
      style={{ background: defaultcolor }}
      onChange={handleBackground}
    >
      <option value="white"> 2 month package</option>
      <option value="green">3 month package</option>
      <option value="red">6 month package</option>
      <option value="yellow">12 month package</option>
    </select>
  ));
}

Body:
you can hold a small 'configuration' object like this:

const monthToColor = {
  2: 'red',
  3: 'green',
  6: 'yellow',
  12: 'orange'
}

The keys should match the user.subscription options you have.

Now, for each option, add a style with background color of: monthToColor[user.subscription] like this:

<option style={{ backgroundColor: monthToColor[user.subscription] }}>
  months
</options>


问:
Apache 404 for every page other than index using laravel
I am able to get to the home page but every single other page gives a 404 error (apache 404 not laravel 404 error page) and i have no clue why. composer dependencies are installed and so is npm. the routes must be working somehow or I wouldn't be able to access my index page at all.
here is my apache config for sites-enabled

```<code><VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/public/

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
</code>```

vim: syntax=apache ts=4 sw=4 sts=4 sr noet

here is my config for sites avaliable

```<code><VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/public/

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
</code>```

vim: syntax=apache ts=4 sw=4 sts=4 sr noet

答:
Add into virtual host directory RewriteEngine On and make sure that is installed.

https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html

Body:
I am able to get to the home page but every single other page gives a 404 error (apache 404 not laravel 404 error page) and i have no clue why. composer dependencies are installed and so is npm. the routes must be working somehow or I wouldn't be able to access my index page at all.
here is my apache config for sites-enabled

<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/public/

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf

vim: syntax=apache ts=4 sw=4 sts=4 sr noet

here is my config for sites avaliable

<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/public/

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf

vim: syntax=apache ts=4 sw=4 sts=4 sr noet


问:
How to save a function result that is always the same to reduce time
I have a function that takes about a minute to be executed, and I want to save the result and somehow check if I have the result stored to avoid executing the whole function everytime.
I was told that the pickle library can help me, but I've never used it, and I don't know if it can be helpful in this situation.

The result format is two lists

```<code>x=[27.93444444444444, 27.345321428571427, 27.16951351351352, 26.750275, 26.33651724137932, 26.330903225806452, 26.27517647058824, 26.12369444444444, 25.420257142857142, 25.349783783783785, 24.932657142857146, 24.839000000000002, 24.69474193548387, 24.62828125, ...]
y=['MSC', 'OCO', 'MAZ', 'GIO', 'RAI', 'STR', 'TSU', 'GAS', 'RUS', 'VET', 'ALO', 'HAM', 'SAI', 'RIC', ...]
</code>```

Edit:
I want to save the result in a file and check if the result is stored to get it from the file instead of executing the function

Body:
I have a function that takes about a minute to be executed, and I want to save the result and somehow check if I have the result stored to avoid executing the whole function everytime.
I was told that the pickle library can help me, but I've never used it, and I don't know if it can be helpful in this situation.

The result format is two lists

x=[27.93444444444444, 27.345321428571427, 27.16951351351352, 26.750275, 26.33651724137932, 26.330903225806452, 26.27517647058824, 26.12369444444444, 25.420257142857142, 25.349783783783785, 24.932657142857146, 24.839000000000002, 24.69474193548387, 24.62828125, ...]
y=['MSC', 'OCO', 'MAZ', 'GIO', 'RAI', 'STR', 'TSU', 'GAS', 'RUS', 'VET', 'ALO', 'HAM', 'SAI', 'RIC', ...]

Edit:
I want to save the result in a file and check if the result is stored to get it from the file instead of executing the function

Body:
Pickle is fine. Or even hdf5. But you might also consider ConfigParser. It's designed for reading and writing config files. It's built into the standard library and it's pretty easy to use.

To write your file:

import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'x': [27.93444444444444, 27.345321428571427, 27.16951351351352, 26.750275, 26.33651724137932, 26.330903225806452, 26.27517647058824, 26.12369444444444, 25.420257142857142, 25.349783783783785, 24.932657142857146, 24.839000000000002, 24.69474193548387, 24.62828125],
                     'y': ['MSC', 'OCO', 'MAZ', 'GIO', 'RAI', 'STR', 'TSU', 'GAS', 'RUS', 'VET', 'ALO', 'HAM', 'SAI', 'RIC']
                     }
with open('myfile.ini', 'w') as configfile:
    config.write(configfile)

and the file will look like:

[DEFAULT]
x = [27.93444444444444, 27.345321428571427, 27.16951351351352, 26.750275, 26.33651724137932, 26.330903225806452, 26.27517647058824, 26.12369444444444, 25.420257142857142, 25.349783783783785, 24.932657142857146, 24.839000000000002, 24.69474193548387, 24.62828125]
y = ['MSC', 'OCO', 'MAZ', 'GIO', 'RAI', 'STR', 'TSU', 'GAS', 'RUS', 'VET', 'ALO', 'HAM', 'SAI', 'RIC']

To read the values back:

import configparser
config = configparser.ConfigParser()
config.read('myfile.ini')
x = config['DEFAULT']['x']
y = config['DEFAULT']['y']

print(x)
print(y)

which has output:

[27.93444444444444, 27.345321428571427, 27.16951351351352, 26.750275, 26.33651724137932, 26.330903225806452, 26.27517647058824, 26.12369444444444, 25.420257142857142, 25.349783783783785, 24.932657142857146, 24.839000000000002, 24.69474193548387, 24.62828125]
['MSC', 'OCO', 'MAZ', 'GIO', 'RAI', 'STR', 'TSU', 'GAS', 'RUS', 'VET', 'ALO', 'HAM', 'SAI', 'RIC']

There's a third party library similar to ConfigParser called ConfigObj that is more powerful and marginally easier to use.


问:
Is it not proper to use the send method to return HTML? Express
I am playing with express, in the past I have used echo with PHP to render out lines of html. In node/express I can add html to a variable and use res.send to return html. That way I can run loops and other things right in the function returning that route. Is this method bad practice? Below I have an example that counts to four.</p>
```<code>var router = express.Router();
let a = (req, res, next) => {
  let send = `<html>`;
  for (let i = 0; i < 5; i++) {
    send += `${i}`;
  }
  send += `</html>`;
  res.send(send);
  //res.download(filepath)
}
router.get('/', [a]);
module.exports = router;

</code>```

答:
I think this is a way to go about express router but it's probably not the easiest and it would cause a lot of code on your router page. It all depends on how large and scalable you want your project to be. If you are looking at doing a smaller project then this would work but if you were doing something a little larger e.g. e-commerce site then I would say put your html files in a separate folder and create a views directory for express. I would also suggest using an open source JavaScript Framework such as ReactJS, Vue, or ejs to name a few. You would have to do more code to your express server by adding views as seen in this link
Adding views in express

So instead of sending the html you would do something like res.render('/home'); if that is what you called your home page in your views file.

If that didn't answer your question please let me know.

Body:
I am playing with express, in the past I have used echo with PHP to render out lines of html. In node/express I can add html to a variable and use res.send to return html. That way I can run loops and other things right in the function returning that route. Is this method bad practice? Below I have an example that counts to four.

var router = express.Router();
let a = (req, res, next) => {
  let send = `<html>`;
  for (let i = 0; i < 5; i++) {
    send += `${i}`;
  }
  send += `</html>`;
  res.send(send);
  //res.download(filepath)
}
router.get('/', [a]);
module.exports = router;


问:
Am I missing some code to view this video in a react app using visual studio code [react]
App.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';

import { Menu } from './Menu';
import { Video } from './Video';

const VIDEOS = {
  fast: require('./videos/bel.mp4'),
  slow: require('./videos/mimi.mp4'),
  cute: require('./videos/coco.mp4'),
  eek: require('./videos/drea.mp4')
};

export class App extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      src: VIDEOS.fast
    };
  }

  render() {
    return(
      <div>
        <Menu  />
        <Video src={this.state.src} />
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);
</code>```

Video.js

```<code>import React from 'react';

export class Video extends React.Component {
    render() {
        return(
            <div>
                <video controls autoPlay muted src={this.props.src}/>
            </div>
        );
    }
}
</code>```

Menu.js

```<code>import React from 'react';

export class Menu extends React.Component {
    render(){
        return(
            <form>
                <input type="radio" name="src" value="fast"  /> Bella
                <input type="radio" name="src" value="slow"  /> Coco
                <input type="radio" name="src" value="cute"  /> Mimi
                <input type="radio" name="src" value="eek"  /> Drea
            </form>
        );
    }
}
</code>```

Trying to create a small React app to practice on my personal computer but the video isn't playing, not sure what I am missing. Video player shows and radio buttons are visible but video doesn't play. I know there is more that needs to be done but first I want to have the first video play that is why I set this.state to VIDEOS.fast

答:
Try importing the videos like this maybe ?

```<code>import bel from './videos/bel.mp4';
import mimi from './videos/mimi.mp4';
import coco from './videos/coco.mp4';
import drea from './videos/drea.mp4';

const VIDEOS = {
  fast: bel,
  slow: mimi,
  cute: coco,
  eek: drea
};
</code>```

And then don't forget the type attribute in the video tag

```<code><video controls autostart autoPlay src={bel} type="video/mp4" />
</code>```

Body:
App.js

import React from 'react';
import ReactDOM from 'react-dom';

import { Menu } from './Menu';
import { Video } from './Video';

const VIDEOS = {
  fast: require('./videos/bel.mp4'),
  slow: require('./videos/mimi.mp4'),
  cute: require('./videos/coco.mp4'),
  eek: require('./videos/drea.mp4')
};

export class App extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      src: VIDEOS.fast
    };
  }

  render() {
    return(

        <Menu  />
        <Video src={this.state.src} />

    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

Video.js

import React from 'react';

export class Video extends React.Component {
    render() {
        return(

                <video controls autoPlay muted src={this.props.src}/>

        );
    }
}

Menu.js

import React from 'react';

export class Menu extends React.Component {
    render(){
        return(
            <form>
                <input type="radio" name="src" value="fast"  /> Bella
                <input type="radio" name="src" value="slow"  /> Coco
                <input type="radio" name="src" value="cute"  /> Mimi
                <input type="radio" name="src" value="eek"  /> Drea
            </form>
        );
    }
}

Trying to create a small React app to practice on my personal computer but the video isn't playing, not sure what I am missing. Video player shows and radio buttons are visible but video doesn't play. I know there is more that needs to be done but first I want to have the first video play that is why I set this.state to VIDEOS.fast

Body:
Try importing the videos like this maybe ?

import bel from './videos/bel.mp4';
import mimi from './videos/mimi.mp4';
import coco from './videos/coco.mp4';
import drea from './videos/drea.mp4';

const VIDEOS = {
  fast: bel,
  slow: mimi,
  cute: coco,
  eek: drea
};

And then don't forget the type attribute in the video tag

<video controls autostart autoPlay src={bel} type="video/mp4" />


问:
Replace a set of html br elements with another in jQuery -- parsing HTML with jQuery
So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.

Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.

So ultimately, what I need to do is come up with a jQuery statement that replaces

```<code><br><br clear=all><br>
</code>```

with

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

I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?

Thanks in advance for any help!

答:
To remove all but one:

```<code>$('br,[clear!="all"]').remove()
</code>```

Then to remove the 'clear=all':

```<code>$('br').removeAttribute('clear')
</code>```

Body:
So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.

Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.

So ultimately, what I need to do is come up with a jQuery statement that replaces

with

I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?

Thanks in advance for any help!

Body:
To remove all but one:

$('br,[clear!="all"]').remove()

Then to remove the 'clear=all':

$('br').removeAttribute('clear')


问:
Looping through array with forEach
I am trying to make a basic program that loops through an array and logs the 'place' & 'distance' to the console. My program isn't working as intended and won't log the values to the console. What am I doing wrong and how can I fix it?</p>
```<code>let destinations = [
  {place: ['Dubai'],
  distance: 7276},
  {place: ['Sydney'],
  distance: 8759},
  {place: ['London'],
  distance: 4166},
  {place: ['tokyo'],
  distance: 5754},
  {place: ['Seoul'],
  distance: 6037},
];

destinations.forEach(spot => {
    if (spot.length < 6) {
      console.log(`${spot} is an interesting vacation spot.
      Let's see how far it is before we pull the trigger`);
      destinations.forEach(howFar => {
        if (howFar < 6000) {
          console.log(`${spot} is close enough. Let's go there!`);
        } if (howFar > 6000) {
          console.log(`Nevermind. ${spot} is too far.`);
        }});
    }
});
</code>```

答:
You'll want to step through the code very carefully to try to see what the JS interpreter sees. It can help to put down the value of variables on scratch paper and how they change as you loop. That'll help you see your own mistakes:

```<code>destinations.forEach(spot => {
</code>```

What is spot here? It'll be each value of destinations, so for example on the first iteration it'll be {place: ['Dubai'],distance: 7276}.

```<code>if (spot.length < 6) {
</code>```

What would the length property be for {place: ['Dubai'],distance: 7276}? That doesn't look like it'd have a length property. It's not an Array. Plus, what condition are you checking here? Are you sure you need an if statement here?

```<code>console.log(`${spot} is an interesting vacation spot.
Let's see how far it is before we pull the trigger`);
</code>```

What would you expect to see putting spot in a string here? Its value is {place: ['Dubai'],distance: 7276}. Are you sure you're not wanting to get some value from the object to put into the string?

```<code>destinations.forEach(howFar => {
</code>```

Isn't this looping over the same Array you looped over earlier? Given 6 destinations, this means it'll run 36 times. And what is howFar? Since it's from destinations.forEach, it'll be one of the objects in the destinations array.

```<code>if (howFar < 6000) {
</code>```

Would an object in the destinations array be comparable to a number? It's an object, so that won't work. Did you mean to access the distance property of the object?

My first piece of advice is to simplify your destinations Array. place is an Array of strings currently, but they're all single items, so you probably don't need an Array for that. Also, since you're not changing destinations, you could make it a a const variable which is helpful because it lets someone looking at your code know they don't have to worry about finding places where it might be changing:

```<code>const destinations = [
  {place: 'Dubai', distance: 7276},
  {place: 'Sydney', distance: 8759},
  {place: 'London', distance: 4166},
  {place: 'Tokyo', distance: 5754},
  {place: 'Seoul', distance: 6037},
];
</code>```

Your way of looping through the destinations is fine, but you'll need to access the properties of the object, and you don't need the extraneous inner loop and if statement (unless you meant to do something with it that I'm not understanding).

```<code>destinations.forEach(spot => {
  console.log(`${spot.place} is an interesting vacation spot.
    Let's see how far it is before we pull the trigger`);
  if (spot.distance < 6000) {
    console.log(`${spot.place} is close enough. Let's go there!`);
  } else {
    console.log(`Nevermind. ${spot.place} is too far.`);
  }
});
</code>```

Title: Looping through array with forEach

Body:
I am trying to make a basic program that loops through an array and logs the 'place' & 'distance' to the console. My program isn't working as intended and won't log the values to the console. What am I doing wrong and how can I fix it?

let destinations = [
  {place: ['Dubai'],
  distance: 7276},
  {place: ['Sydney'],
  distance: 8759},
  {place: ['London'],
  distance: 4166},
  {place: ['tokyo'],
  distance: 5754},
  {place: ['Seoul'],
  distance: 6037},
];

destinations.forEach(spot => {
    if (spot.length < 6) {
      console.log(`${spot} is an interesting vacation spot.
      Let's see how far it is before we pull the trigger`);
      destinations.forEach(howFar => {
        if (howFar < 6000) {
          console.log(`${spot} is close enough. Let's go there!`);
        } if (howFar > 6000) {
          console.log(`Nevermind. ${spot} is too far.`);
        }});
    }
});

Body:
You'll want to step through the code very carefully to try to see what the JS interpreter sees. It can help to put down the value of variables on scratch paper and how they change as you loop. That'll help you see your own mistakes:

destinations.forEach(spot => {

What is spot here? It'll be each value of destinations, so for example on the first iteration it'll be {place: ['Dubai'],distance: 7276}.

if (spot.length < 6) {

What would the length property be for {place: ['Dubai'],distance: 7276}? That doesn't look like it'd have a length property. It's not an Array. Plus, what condition are you checking here? Are you sure you need an if statement here?

console.log(`${spot} is an interesting vacation spot.
Let's see how far it is before we pull the trigger`);

What would you expect to see putting spot in a string here? Its value is {place: ['Dubai'],distance: 7276}. Are you sure you're not wanting to get some value from the object to put into the string?

destinations.forEach(howFar => {

Isn't this looping over the same Array you looped over earlier? Given 6 destinations, this means it'll run 36 times. And what is howFar? Since it's from destinations.forEach, it'll be one of the objects in the destinations array.

if (howFar < 6000) {

Would an object in the destinations array be comparable to a number? It's an object, so that won't work. Did you mean to access the distance property of the object?

My first piece of advice is to simplify your destinations Array. place is an Array of strings currently, but they're all single items, so you probably don't need an Array for that. Also, since you're not changing destinations, you could make it a a const variable which is helpful because it lets someone looking at your code know they don't have to worry about finding places where it might be changing:

const destinations = [
  {place: 'Dubai', distance: 7276},
  {place: 'Sydney', distance: 8759},
  {place: 'London', distance: 4166},
  {place: 'Tokyo', distance: 5754},
  {place: 'Seoul', distance: 6037},
];

Your way of looping through the destinations is fine, but you'll need to access the properties of the object, and you don't need the extraneous inner loop and if statement (unless you meant to do something with it that I'm not understanding).

destinations.forEach(spot => {
  console.log(`${spot.place} is an interesting vacation spot.
    Let's see how far it is before we pull the trigger`);
  if (spot.distance < 6000) {
    console.log(`${spot.place} is close enough. Let's go there!`);
  } else {
    console.log(`Nevermind. ${spot.place} is too far.`);
  }
});


问:
"GET http://localhost:8801/main.js net::ERR_ABORTED 404 (Not Found)" error
Google thinks that I am trying to read data from localhost:8801, but I am trying to read that data from another file called "main.js." The error is "GET http://localhost:8801/main.js net::ERR_ABORTED 404 (Not Found)" How can I reference the command from main.js without google thinking that it is a subdirectory. Here is my code in index.html:

https://sourceb.in/iuMyon5XI7

Thank you in advance.

答:
I think you are reffering to Chrome browser when you say google (it's confusing) but google have nothing to do with the issue you're facing.

anyway I understand you're trying to get json data from local file;
try this

var json = require('./data.json'); //(with your file path)```


问:
What is the cleanest way to get the sum of numbers in a collection/list in Dart?
I don't like using an indexed array for no reason other than I think it looks ugly. Is there a clean way to sum with an anonymous function? Is it possible to do it without using any outside variables?</p>

答:
I'd just like to add some small detail to @tmaihoff's answer (about using the collection.dart package):

The sum getter he talks about only works for iterables of num values, like List<int> or Set<double>.

If you have a list of other object types that represent values (like Money, Decimal, Rational, or any others) you must map it to numbers. For example, to count the number of chars in a list of strings you can do:

```<code>// Returns 15.
['a', 'ab', 'abc', 'abcd', 'abcde'].map((e) => e.length).sum;
</code>```

As of 2022, another way of doing it, is using the sumBy() method of the fast_immutable_collections package:

```<code>// Returns 15.
['a', 'ab', 'abc', 'abcd', 'abcde'].sumBy((e) => e.length), 15);
</code>```

Note: I'm the package author.

Body:
I'd just like to add some small detail to @tmaihoff's answer (about using the collection.dart package):

The sum getter he talks about only works for iterables of num values, like List<int> or Set<double>.

If you have a list of other object types that represent values (like Money, Decimal, Rational, or any others) you must map it to numbers. For example, to count the number of chars in a list of strings you can do:

// Returns 15.
['a', 'ab', 'abc', 'abcd', 'abcde'].map((e) => e.length).sum;

As of 2022, another way of doing it, is using the sumBy() method of the fast_immutable_collections package:

// Returns 15.
['a', 'ab', 'abc', 'abcd', 'abcde'].sumBy((e) => e.length), 15);

Note: I'm the package author.


问:
Broken Eclipse console log output using Log4J's %style
I created an appender in my Log4J.xml config file following this manual :

```<code><Console name="Console" target="SYSTEM_OUT" follow="true">
    <PatternLayout pattern="%green{%d} %style{%t}{BG_Green,white} %yellow{[%-5p]} %m%n"/>
</Console>
</code>```

My broken console output :

```<code>[32m2022-02-07 23:58:46,394[m [33m[INFO ][m HHH000412: Hibernate ORM core version 5.6.5.Final
[32m2022-02-07 23:58:46,659[m [33m[INFO ][m HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
[32m2022-02-07 23:58:46,751[m [33m[WARN ][m HHH10001002: Using Hibernate built-in connection pool (not for production use!)
[32m2022-02-07 23:58:46,755[m [33m[INFO ][m HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost/hibernate_demo]
[32m2022-02-07 23:58:46,755[m [33m[INFO ][m HHH10001001: Connection properties: {password=****, user=root}
[32m2022-02-07 23:58:46,755[m [33m[INFO ][m HHH10001003: Autocommit mode: false
[32m2022-02-07 23:58:46,756[m [33m[INFO ][m HHH000115: Hibernate connection pool size: 20 (min=1)
[32m2022-02-07 23:58:47,001[m [33m[INFO ][m HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
</code>```

I tried to add this disableAnsi="true" to my <PatternLayout /> , didnt work.

I tired adding this eclipse plugin, didnt work.

Eclipse version: 2021-06 (4.20.0)

Log4J dependency :

```<code><!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.17.1</version>
    </dependency>
</code>```

EDIT 1 :

it's working partially

I needed to check a checkbox in Window => Prefrences => Run/debug => Console => "Interpret ASCII Control Characters".

Must have this Eclipse Plugin installed .

see picture

Using %style{pattern}{myStyles} is displaying colors in the console correctly , but %highligh is not, no idea where to go from here.
( see console coloring )

答:
The solution is to add disableAnsi="false" to my PatternLayout like so :

```<code><Console name="Console" target="SYSTEM_OUT" >
   <PatternLayout disableAnsi="false" pattern="[ %blue{%d{dd-MMM-yyyy @ HH:mm}} ] %highlight{[%-5p]} %green{[%t]} - %m%n%throwable"/>
</Console>
</code>```

Body:
I created an appender in my Log4J.xml config file following this manual :

<Console name="Console" target="SYSTEM_OUT" follow="true">
    <PatternLayout pattern="%green{%d} %style{%t}{BG_Green,white} %yellow{[%-5p]} %m%n"/>
</Console>

My broken console output :

[32m2022-02-07 23:58:46,394[m [33m[INFO ][m HHH000412: Hibernate ORM core version 5.6.5.Final
[32m2022-02-07 23:58:46,659[m [33m[INFO ][m HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
[32m2022-02-07 23:58:46,751[m [33m[WARN ][m HHH10001002: Using Hibernate built-in connection pool (not for production use!)
[32m2022-02-07 23:58:46,755[m [33m[INFO ][m HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost/hibernate_demo]
[32m2022-02-07 23:58:46,755[m [33m[INFO ][m HHH10001001: Connection properties: {password=****, user=root}
[32m2022-02-07 23:58:46,755[m [33m[INFO ][m HHH10001003: Autocommit mode: false
[32m2022-02-07 23:58:46,756[m [33m[INFO ][m HHH000115: Hibernate connection pool size: 20 (min=1)
[32m2022-02-07 23:58:47,001[m [33m[INFO ][m HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect

I tried to add this disableAnsi="true" to my <PatternLayout /> , didnt work.

I tired adding this eclipse plugin, didnt work.

Eclipse version: 2021-06 (4.20.0)

Log4J dependency :

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.17.1</version>
    </dependency>

EDIT 1 :

it's working partially

I needed to check a checkbox in Window => Prefrences => Run/debug => Console => "Interpret ASCII Control Characters".

Must have this Eclipse Plugin installed .

see picture

Using %style{pattern}{myStyles} is displaying colors in the console correctly , but %highligh is not, no idea where to go from here.
( see console coloring )

Body:
The solution is to add disableAnsi="false" to my PatternLayout like so :

<Console name="Console" target="SYSTEM_OUT" >
   <PatternLayout disableAnsi="false" pattern="[ %blue{%d{dd-MMM-yyyy @ HH:mm}} ] %highlight{[%-5p]} %green{[%t]} - %m%n%throwable"/>
</Console>