问:
How do I make this object immutable
I am working with this code below

```<code>const recipes = {
  recipe1: {
    title: "pancake",
    serving: 4,
    ingredients: ["flour", "egg", "milk", "vanilla", "baking Powder"],
  },
  recipe2: {
    title: "eggSalad",
    serving: 2,
    ingredients: ["egg", "mayo", "lettuce", "cucumber", "tomato"],
  },
  recipe3: {
    title: "omelette",
    serving: 4,
    ingredients: ["egg", "mushroom", "pepper", "salt", "tomato"],
  }
};

const arr1 = Object.assign({}, {...recipes})

Object.values(arr1).forEach(e => {
  console.log(e.title)
  console.log(e.serving)
  console.log(e.ingredients)

  e.title = "this has been mutated"
})

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

I want to log each recipe, which I have done successfully. HOWEVER, I also don't want to mutate the object. I thought by using the Object.assign along with the ... / spread operator, it would sever ties with the original recipes object. But on the last console log, the original object is in fact mutated and logs each recipe title with 'this has been mutated'

I am very confused why this is happening, and furthermore, cannot find a solution in which I can copy the orginal array without mutating it.

I am sure I am doing something rather silly, but I want to maintain good practice of keeping things immutable, and I cannot get this to work!

Can anyone help, or even better, educate me where I am going wrong?

Thanks!

答:
In order to create a "deep copy" of your nested objects, you have to create copies for every non-primitive value (plain object or array object) within.

Otherwise, the objects within will still be same objects in the original (even though you created a copy of their "container object").

In the case of your example data, you can do it using recursive spread syntax like in the example below where copy is created:

const recipes = {
  recipe1: {
    title: "pancake",
    serving: 4,
    ingredients: ["flour", "egg", "milk", "vanilla", "baking Powder"],
  },
  recipe2: {
    title: "eggSalad",
    serving: 2,
    ingredients: ["egg", "mayo", "lettuce", "cucumber", "tomato"],
  },
  recipe3: {
    title: "omelette",
    serving: 4,
    ingredients: ["egg", "mushroom", "pepper", "salt", "tomato"],
  }
};

const copy = Object.fromEntries([...Object.entries(recipes)].map(([name, recipe]) => [name, {
  ...recipe,
  ingredients: [...recipe.ingredients],
}]));

Object.values(copy).forEach(recipe => {
  console.log(recipe);
  recipe.title = "this has been mutated";
})

console.log(recipes);```
</div>
</div>
</p>
<p>In the case of data that can be directly serialized as JSON without a type coercion (like your example), you can also simply use:</p>
<pre class="lang-js prettyprint-override"><code>const copy = JSON.parse(JSON.stringify(recipes));
</code>```

Title: How do I make this object immutable

Body:
I am working with this code below

const recipes = {
  recipe1: {
    title: "pancake",
    serving: 4,
    ingredients: ["flour", "egg", "milk", "vanilla", "baking Powder"],
  },
  recipe2: {
    title: "eggSalad",
    serving: 2,
    ingredients: ["egg", "mayo", "lettuce", "cucumber", "tomato"],
  },
  recipe3: {
    title: "omelette",
    serving: 4,
    ingredients: ["egg", "mushroom", "pepper", "salt", "tomato"],
  }
};

const arr1 = Object.assign({}, {...recipes})

Object.values(arr1).forEach(e => {
  console.log(e.title)
  console.log(e.serving)
  console.log(e.ingredients)

  e.title = "this has been mutated"
})

console.log(recipes)

I want to log each recipe, which I have done successfully. HOWEVER, I also don't want to mutate the object. I thought by using the Object.assign along with the ... / spread operator, it would sever ties with the original recipes object. But on the last console log, the original object is in fact mutated and logs each recipe title with 'this has been mutated'

I am very confused why this is happening, and furthermore, cannot find a solution in which I can copy the orginal array without mutating it.

I am sure I am doing something rather silly, but I want to maintain good practice of keeping things immutable, and I cannot get this to work!

Can anyone help, or even better, educate me where I am going wrong?

Thanks!

Body:
In order to create a "deep copy" of your nested objects, you have to create copies for every non-primitive value (plain object or array object) within.

Otherwise, the objects within will still be same objects in the original (even though you created a copy of their "container object").

In the case of your example data, you can do it using recursive spread syntax like in the example below where copy is created:

const recipes = {
  recipe1: {
    title: "pancake",
    serving: 4,
    ingredients: ["flour", "egg", "milk", "vanilla", "baking Powder"],
  },
  recipe2: {
    title: "eggSalad",
    serving: 2,
    ingredients: ["egg", "mayo", "lettuce", "cucumber", "tomato"],
  },
  recipe3: {
    title: "omelette",
    serving: 4,
    ingredients: ["egg", "mushroom", "pepper", "salt", "tomato"],
  }
};

const copy = Object.fromEntries([...Object.entries(recipes)].map(([name, recipe]) => [name, {
  ...recipe,
  ingredients: [...recipe.ingredients],
}]));

Object.values(copy).forEach(recipe => {
  console.log(recipe);
  recipe.title = "this has been mutated";
})

console.log(recipes);

In the case of data that can be directly serialized as JSON without a type coercion (like your example), you can also simply use:

const copy = JSON.parse(JSON.stringify(recipes));


来源: stackexchange

问:
How can I attach an existing EBS volume to an EC2 instance with Ansible?
I've looked through the Ansible documentation for ec2_instance and ec2_vol but both seem to only support creating a new EBS volume (either blank or from an EBS snapshot). I would like to attach an existing EBS volume directly to an instance, not create a snapshot of it and then create a new volume from that snapshot. Is there an Ansible module that does this or should I just use shell and run the right AWS CLI command?

答:
You're looking for the union of the id: and instance: properties, as indicated by the language next to the id: property:

Volume id if you wish to attach an existing volume (requires instance) or remove an existing volume

- amazon.aws.ec2_vol:
    id: '{{ my_volume_id }}'
    instance: '{{ my_inst_id }}'
    device_name: /dev/xvdf # or whatever
```

Be aware (as this bit me) when they say instance: "None" to detach it, they really mean None, and not null or whatever else

ContentLicense: CC BY-SA 4.0

Body:
You're looking for the union of the id: and instance: properties, as indicated by the language next to the id: property:

Volume id if you wish to attach an existing volume (requires instance) or remove an existing volume

- amazon.aws.ec2_vol:
    id: '{{ my_volume_id }}'
    instance: '{{ my_inst_id }}'
    device_name: /dev/xvdf # or whatever

Be aware (as this bit me) when they say instance: "None" to detach it, they really mean None, and not null or whatever else


问:
async function returns Promise { <pending> } #axios #lorem-picsum
I am using the lorem picsum api with axios.

```<code>const axios = require('axios').default;
const imageArray = async () => {
    try {
        const list = await axios.get('https://picsum.photos/v2/list?page=2&limit=50');
        const data = await list.data;
        console.log(data);
        return data;
    } catch (err) {
        console.log(err);
    }
}
const imageList = imageArray();
console.log(imageList);
</code>```

https://picsum.photos/v2/list?page=2&limit=50 this url returns an array of 50 objects named data. I want to assign this array to imageList.

console.log(data) gives the following output.

```<code>[
  {
    id: '1047',
    author: 'sergee bee',
    width: 3264,
    height: 2448,
    url: 'https://unsplash.com/photos/bIQiMWxX_WU',
    download_url: 'https://picsum.photos/id/1047/3264/2448'
  },
  {
    id: '1048',
    author: 'Anthony DELANOIX',
    width: 5616,
    height: 3744,
    url: 'https://unsplash.com/photos/b5POxb2aL9o',
    download_url: 'https://picsum.photos/id/1048/5616/3744'
  },.....
......
....]
</code>```

But console.log(imageList) returns Promise { <pending> } and no other error.
From the log i understand that the output is called before promise is completed.
But i don't get why this happens because the function i am calling is already an async function. so it must await.

pls help me.
sorry if this question was silly.

答:
It's because you're missing await in

```<code>const imageList = imageArray();
</code>```

Try to change it into

```<code>((async () => {
    const imageList = await imageArray();
    console.log(imageList);
})());
</code>```

and run again

Body:
I am using the lorem picsum api with axios.

const axios = require('axios').default;
const imageArray = async () => {
    try {
        const list = await axios.get('https://picsum.photos/v2/list?page=2&limit=50');
        const data = await list.data;
        console.log(data);
        return data;
    } catch (err) {
        console.log(err);
    }
}
const imageList = imageArray();
console.log(imageList);

https://picsum.photos/v2/list?page=2&limit=50 this url returns an array of 50 objects named data. I want to assign this array to imageList.

console.log(data) gives the following output.

[
  {
    id: '1047',
    author: 'sergee bee',
    width: 3264,
    height: 2448,
    url: 'https://unsplash.com/photos/bIQiMWxX_WU',
    download_url: 'https://picsum.photos/id/1047/3264/2448'
  },
  {
    id: '1048',
    author: 'Anthony DELANOIX',
    width: 5616,
    height: 3744,
    url: 'https://unsplash.com/photos/b5POxb2aL9o',
    download_url: 'https://picsum.photos/id/1048/5616/3744'
  },.....
......
....]

But console.log(imageList) returns Promise { <pending> } and no other error.
From the log i understand that the output is called before promise is completed.
But i don't get why this happens because the function i am calling is already an async function. so it must await.

pls help me.
sorry if this question was silly.

Body:
It's because you're missing await in

const imageList = imageArray();

Try to change it into

((async () => {
    const imageList = await imageArray();
    console.log(imageList);
})());

and run again


问:
Read Multiple Text Files in PySpark
I have many text files stored in S3, almost partitioned, but not quite. I want to read and union all of them. Keys have prefixes like:

```<code>s3_keys = ['s3a://prd-bucket//PROD/data/2021-04-16/part-2144.log',
 's3a://prd-bucket//PROD/data/2021-04-16/part-2146.log',
 's3a://prd-bucket//PROD/data/2021-04-16/part-2148.log',
 's3a://prd-bucket//PROD/data/2021-04-16/part-2150.log',
 's3a://prd-bucket//PROD/data/2021-04-16/part-2164.log',
 's3a://prd-bucket//PROD/data/2021-04-16/part-requeue-client-xxx.log'
]
</code>```

I tried following this answer, but for some strange reason, spark.read.text mangles the filesystem prepended in each path after the first:

```<code>df = (
    spark.read.option('mode', 'FAILFAST')
    .text(','.join(s3_keys))
)
</code>```

Py4JJavaError: An error occurred while calling o40880.text. :
org.apache.spark.sql.AnalysisException: Path does not exist:
s3a://prd-bucket/PROD/data/2021-04-16/part-2144.log,s3a:/prd-bucket/PROD/data/2021-04-16/part-2146.log
...

Note the s3a:/ instead of s3a://. Why is this happening? I'm also curious if there is a limit for this sort of path munging...something like AmazonS3Exception: Request-URI Too Large

Similar question asked here, but I need a solution for PySpark (2.4) on S3.

答:
You are passing multiple paths separated by , as one string thats why you are getting below error.

```<code>Py4JJavaError: An error occurred while calling o40880.text. : org.apache.spark.sql.AnalysisException: Path does not exist: s3a://prd-bucket/PROD/data/2021-04-16/part-2144.log,s3a:/prd-bucket/PROD/data/2021-04-16/part-2146.log ...
</code>```

Pass multiple paths as varargs or list. Try below code.

```<code>df = (
    spark.read.option('mode', 'FAILFAST')
    .text(s3_keys)
)
</code>```

Title: Read Multiple Text Files in PySpark

Body:
I have many text files stored in S3, almost partitioned, but not quite. I want to read and union all of them. Keys have prefixes like:

s3_keys = ['s3a://prd-bucket//PROD/data/2021-04-16/part-2144.log',
 's3a://prd-bucket//PROD/data/2021-04-16/part-2146.log',
 's3a://prd-bucket//PROD/data/2021-04-16/part-2148.log',
 's3a://prd-bucket//PROD/data/2021-04-16/part-2150.log',
 's3a://prd-bucket//PROD/data/2021-04-16/part-2164.log',
 's3a://prd-bucket//PROD/data/2021-04-16/part-requeue-client-xxx.log'
]

I tried following this answer, but for some strange reason, spark.read.text mangles the filesystem prepended in each path after the first:

df = (
    spark.read.option('mode', 'FAILFAST')
    .text(','.join(s3_keys))
)

Py4JJavaError: An error occurred while calling o40880.text. :
org.apache.spark.sql.AnalysisException: Path does not exist:
s3a://prd-bucket/PROD/data/2021-04-16/part-2144.log,s3a:/prd-bucket/PROD/data/2021-04-16/part-2146.log
...

Note the s3a:/ instead of s3a://. Why is this happening? I'm also curious if there is a limit for this sort of path munging...something like AmazonS3Exception: Request-URI Too Large

Similar question asked here, but I need a solution for PySpark (2.4) on S3.

Body:
You are passing multiple paths separated by , as one string thats why you are getting below error.

Py4JJavaError: An error occurred while calling o40880.text. : org.apache.spark.sql.AnalysisException: Path does not exist: s3a://prd-bucket/PROD/data/2021-04-16/part-2144.log,s3a:/prd-bucket/PROD/data/2021-04-16/part-2146.log ...

Pass multiple paths as varargs or list. Try below code.

df = (
    spark.read.option('mode', 'FAILFAST')
    .text(s3_keys)
)


问:
Custom function to rename all columns
I want to manipulate the names of all the columns in a dataframe with this function that I wrote:

```<code>clean_names <- function(df) {
  names(df) <- tolower(names(df))
  names(df) <- gsub('\\s', '\\_', names(df))
  names(df) <- gsub('\\(|\\)|\\/|,|\\.', '\\_', names(df))
  names(df) <- gsub('(\\_)\\_', '\\1', names(df))
  names(df) <- gsub('\\_$', '', names(df))
}
</code>```

That said, when actually called, it doesn't do anything (no error just nothing).
What's the problem here?

I suspect the problem is that I'm only assigning things and not returning anything. But in this case I don't want to return a value just change the column names.

The only parameter here is df and I'm calling the names() function multiple times. Shouldn't this work? Any help is appreciated!

答:
Two things here:

R tends to not operate in side-effect, so while you may pass a data.frame in to it, the first time you change anything about it, the df in the function is completely copied into a new object that will go away when the function is done. The original frame is untouched. There are some functions in R that operate in side-effect, but most of R is not. With this, you cannot just make changes inside the function and assume that it will have an effect outside of the function. For this, you would need to reassign the results back to the frame, as in:

mydata <- clean_names(mydata)
```
</li>
<li><p>When there is no literal <code>return(.)</code> statement in a function, R will return the last expression (often invisibly). You will often see functions end with the desired object (<code>df</code> here) without using the literal <code>return</code> function; that function is useful in some circumstances but usually not needed.</p>
<p>The last expression is usually <em>invisible</em>. You can see what is really happening by capturing the return value in a new variable or, as a shortcut, just <code>(clean_names(mydata))</code>. My gut feeling is that the output from that function is a vector of strings.</p>
<p>Why? Because the last expression is a reassignment of names. The RHS of that assignment is producing a <code>character</code> vector, and that is passed to the <code>`names<-`</code> function on the LHS, and that value (the vector of strings) is then used as the return value of the function.</p>
<p>The resolution here is to add <code>df</code> (or <code>return(df)</code> if you must) to the end of your function, as in:</p>
<pre class="lang-r prettyprint-override"><code>clean_names <- function(df) {
  names(df) <- tolower(names(df))
  names(df) <- gsub('\\s', '\\_', names(df))
  names(df) <- gsub('\\(|\\)|\\/|,|\\.', '\\_', names(df))
  names(df) <- gsub('(\\_)\\_', '\\1', names(df))
  names(df) <- gsub('\\_$', '', names(df))
  df
}
</code>```

After doing both of those steps, you should then get data.

Title: Custom function to rename all columns

Body:
I want to manipulate the names of all the columns in a dataframe with this function that I wrote:

clean_names <- function(df) {
  names(df) <- tolower(names(df))
  names(df) <- gsub('\\s', '\\_', names(df))
  names(df) <- gsub('\\(|\\)|\\/|,|\\.', '\\_', names(df))
  names(df) <- gsub('(\\_)\\_', '\\1', names(df))
  names(df) <- gsub('\\_$', '', names(df))
}

That said, when actually called, it doesn't do anything (no error just nothing).
What's the problem here?

I suspect the problem is that I'm only assigning things and not returning anything. But in this case I don't want to return a value just change the column names.

The only parameter here is df and I'm calling the names() function multiple times. Shouldn't this work? Any help is appreciated!

Body:
Two things here:

R tends to not operate in side-effect, so while you may pass a data.frame in to it, the first time you change anything about it, the df in the function is completely copied into a new object that will go away when the function is done. The original frame is untouched. There are some functions in R that operate in side-effect, but most of R is not. With this, you cannot just make changes inside the function and assume that it will have an effect outside of the function. For this, you would need to reassign the results back to the frame, as in:

mydata <- clean_names(mydata)

When there is no literal return(.) statement in a function, R will return the last expression (often invisibly). You will often see functions end with the desired object (df here) without using the literal return function; that function is useful in some circumstances but usually not needed.

The last expression is usually invisible. You can see what is really happening by capturing the return value in a new variable or, as a shortcut, just (clean_names(mydata)). My gut feeling is that the output from that function is a vector of strings.

Why? Because the last expression is a reassignment of names. The RHS of that assignment is producing a character vector, and that is passed to the `names<-` function on the LHS, and that value (the vector of strings) is then used as the return value of the function.

The resolution here is to add df (or return(df) if you must) to the end of your function, as in:

clean_names <- function(df) {
  names(df) <- tolower(names(df))
  names(df) <- gsub('\\s', '\\_', names(df))
  names(df) <- gsub('\\(|\\)|\\/|,|\\.', '\\_', names(df))
  names(df) <- gsub('(\\_)\\_', '\\1', names(df))
  names(df) <- gsub('\\_$', '', names(df))
  df
}

After doing both of those steps, you should then get data.


问:
Enable and disable. One then the other
One button shows the user local time when clicked. Then I have another button that stops the clock.
I am trying to disable "show local time" when the button "stop time" is clicked.

<button  id="start" onclick="showTime()" >Show Local showTime</button> <button  id="stop" onclick="myStop()">Stop Time</button>

This is my code in HTML

I've tried this for my javascript
document.getElementById(start).disabled = true; document.getElementById(stop).removeAttribute('disabled')

Tried this

```<code>function showTime() {
    document.getElementById("start").disabled = true;
  }

  function myStop() {
    document.getElementById("stop").disabled = false;
  }
</code>```

None of these have works for disabling the other button. They both are being allowed to be clicked.

答:
As far as I got the question, you need to disable one button when you click the other button. I will post an answer that will do the work.

function showTime() {
    document.getElementById("stop").disabled = !document.getElementById("stop").disabled;
}

function myStop() {
    document.getElementById("start").disabled = !document.getElementById("start").disabled;

}```

When you click the show local time button,

it will disable the stop time if stop time is enabled

it will enable the stop time if stop time is disabled

When you click the stop time button,

it will disable the show local time if show local time is enabled

it will enable the show local time if show local time is disabled

Title: Enable and disable. One then the other

Body:
One button shows the user local time when clicked. Then I have another button that stops the clock.
I am trying to disable "show local time" when the button "stop time" is clicked.

<button  id="start" onclick="showTime()" >Show Local showTime</button> <button  id="stop" onclick="myStop()">Stop Time</button>

This is my code in HTML

I've tried this for my javascript
document.getElementById(start).disabled = true; document.getElementById(stop).removeAttribute('disabled')

Tried this

function showTime() {
    document.getElementById("start").disabled = true;
  }

  function myStop() {
    document.getElementById("stop").disabled = false;
  }

None of these have works for disabling the other button. They both are being allowed to be clicked.

Body:
As far as I got the question, you need to disable one button when you click the other button. I will post an answer that will do the work.

function showTime() {
    document.getElementById("stop").disabled = !document.getElementById("stop").disabled;
}

function myStop() {
    document.getElementById("start").disabled = !document.getElementById("start").disabled;

}

When you click the show local time button,

it will disable the stop time if stop time is enabled

it will enable the stop time if stop time is disabled

When you click the stop time button,

it will disable the show local time if show local time is enabled

it will enable the show local time if show local time is disabled


问:
Apache Pulsar: Read / Consume messages from an integer specified message id to an end message Id?
With Kafka, I can specify an integer message id to begin consuming from and an end message to stop at, e.g as follows:

```<code> kafkacat -b kafka:9092 -t messages -o 11000 -c 11333

</code>```

However, it appears the same functionality to specify integer start and stop messages is not available in Apache Pulsar!

To be fair, it's possible to specify a start message id and end message id, if these have been tracked and saved in a byte format, using a very convoluted process which is bound to affect performance and code complexity.

As in this example:

```<code>client, err := NewClient(pulsar.ClientOptions{
    URL: lookupURL,
})

if err != nil {
    log.Fatal(err)
}
defer client.Close()

topic := "topic-1"
ctx := context.Background()

// create producer
producer, err := client.CreateProducer(pulsar.ProducerOptions{
    Topic:           topic,
    DisableBatching: true,
})
if err != nil {
    log.Fatal(err)
}
defer producer.Close()

// send 10 messages
msgIDs := [10]MessageID{}
for i := 0; i < 10; i++ {
    msgID, err := producer.Send(ctx, &pulsar.ProducerMessage{
        Payload: []byte(fmt.Sprintf("hello-%d", i)),
    })
    assert.NoError(t, err)
    assert.NotNil(t, msgID)
    msgIDs[i] = msgID
}

// create reader on 5th message (not included)
reader, err := client.CreateReader(pulsar.ReaderOptions{
    Topic:          topic,
    StartMessageID: msgIDs[4],
})

if err != nil {
    log.Fatal(err)
}
defer reader.Close()

// receive the remaining 5 messages
for i := 5; i < 10; i++ {
    msg, err := reader.Next(context.Background())
    if err != nil {
    log.Fatal(err)
}

// create reader on 5th message (included)
readerInclusive, err := client.CreateReader(pulsar.ReaderOptions{
    Topic:                   topic,
    StartMessageID:          msgIDs[4],
    StartMessageIDInclusive: true,
})

if err != nil {
    log.Fatal(err)
}
defer readerInclusive.Close()
</code>```

However, this is complicated and unreliable (or complex) for multiple concurrent readers and requires the use of an external construct to track the processed messages before it can be retrieved using the start/end semantics.

Is there any way to achieve this (preferably via golang)

答:
I've found that the following simple approach is sufficient (proof of concept script):</p>
```<code>package main

import (
    "context"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "strconv"
    "strings"
    "time"

    "github.com/apache/pulsar-client-go/pulsar"
)

func writeBytesToFile(f string, byteSlice []byte) int {
    // Open a new file for writing only

    f = "./data/" + f

    file, err := os.OpenFile(
        f,
        os.O_WRONLY|os.O_TRUNC|os.O_CREATE,
        0666,
    )
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    // Write bytes to file
    bytesWritten, err := file.Write(byteSlice)

    if err != nil {
        log.Fatal(err)
    }

    log.Printf("Wrote %d bytes.\n", bytesWritten)

    return bytesWritten
}

func readBackByEntryId(msgDir string, msgIndex string) (yourBytes []byte) {

    //We know the file name by convention
    fname := msgDir + "/" + msgIndex + ".dat"

    yourBytes, err := ioutil.ReadFile(fname)

    if err != nil {
        log.Printf("error reading %s", fname)
        return nil
    }

    return yourBytes
}

func getFiles(aDir string) []string {

    var theFiles []string

    files, err := ioutil.ReadDir("./data/")

    if err != nil {
        log.Fatal(err)
    }

    for _, f := range files {

        theFiles = append(theFiles, f.Name())

    }

    return theFiles
}

func streamAll(reader pulsar.Reader, startMsgIndex int64, stopMsgIndex int64) {

    read := false

    for reader.HasNext() {

        msg, err := reader.Next(context.Background())

        if err != nil {
            log.Fatal(err)
        }

        //can I access the details of the message ? yes
        fmt.Printf("%v -> %#v\n", msg.ID().EntryID(), msg.ID())

        //Can i serialize into bytes? Yes
        myBytes := msg.ID().Serialize()

        //Can I store it somewhere? Perhaps a map ? or even on disk in a file ?
        //In other words: Can I write a byte[] slice to a file? Yes!
        msgIndex := msg.ID().EntryID()

        if msgIndex == startMsgIndex {
            fmt.Println("start read: ", msgIndex)
            read = true
        }

        if msgIndex > stopMsgIndex {
            fmt.Println("stop reading: ", msgIndex)
            read = false
        }

        if read == false {

            fmt.Println("skipping ", msgIndex)

        } else {

            fname := strconv.FormatInt(msgIndex, 10) + ".dat"

            fmt.Println("written bytes: ", writeBytesToFile(fname, myBytes))

            fmt.Printf("Received message msgId: %#v -- content: '%s' published at %v\n",
                msg.ID(), string(msg.Payload()), msg.PublishTime())

        }

        /*
            //FYI - to save and reread a msgId from store: https://githubmemory.com/@storm-5
            msgId := msg.ID()
            msgIdBytes := msgId.Serialize()
            idNew, _ := pulsar.DeserializeMessageID(msgIdBytes)

            readerInclusive, err := client.CreateReader(pulsar.ReaderOptions{
                Topic:                   "ragnarok/transactions/requests",
                StartMessageID:          idNew,
                StartMessageIDInclusive: true,
            })
        */
    }

}

func retrieveRange(client pulsar.Client) {

    someFiles := getFiles("./data/")

    for _, f := range someFiles {

        fIndex := strings.Split(f, ".")[0]

        fmt.Println("re-reading message index -> ", fIndex)

        msgIdBytes := readBackByEntryId("./data", fIndex)

        fmt.Printf("boom -> %#v\n", msgIdBytes)

        idNew, err := pulsar.DeserializeMessageID(msgIdBytes)

        if err != nil {
            log.Fatal(err)
        }

        fmt.Println("Got message entry id => ", idNew.EntryID())

        readerInclusive, err := client.CreateReader(pulsar.ReaderOptions{
            Topic:                   "ragnarok/transactions/requests",
            StartMessageID:          idNew,
            StartMessageIDInclusive: true,
        })

        if err != nil {
            log.Fatal(err)
        }

        defer readerInclusive.Close()

        //defer readerInclusive.Close()
        fmt.Println("bleep!")

        msg, err := readerInclusive.Next(context.Background())

        if err != nil {
            log.Fatal(err)
        }

        //fmt.Println("retrieved message -> ", string(msg.Payload()))
        fmt.Printf("Retrieved message ID message msgId: %#v -- content: '%s' published at %v\n",
            msg.ID(), string(msg.Payload()), msg.PublishTime())

    }
}

func main() {

    client, err := pulsar.NewClient(
        pulsar.ClientOptions{
            URL:               "pulsar://localhost:6650",
            OperationTimeout:  30 * time.Second,
            ConnectionTimeout: 30 * time.Second,
        })

    if err != nil {
        log.Fatalf("Could not instantiate Pulsar client: %v", err)
    }

    defer client.Close()

    reader, err := client.CreateReader(pulsar.ReaderOptions{
        Topic:          "ragnarok/transactions/requests",
        StartMessageID: pulsar.EarliestMessageID(),
    })

    if err != nil {
        log.Fatal(err)
    }

    defer reader.Close()

    if err != nil {
        log.Fatal(err)
    }

    var startMsgId int64 = 55
    var stopMsgId int64 = 66

    //stream all the messages from the earliest to latest
    //pick a subset between a start and stop id
    streamAll(reader, startMsgId, stopMsgId)

    //retrieve the picked range
    retrieveRange(client)

}

</code>```

Body:
With Kafka, I can specify an integer message id to begin consuming from and an end message to stop at, e.g as follows:

 kafkacat -b kafka:9092 -t messages -o 11000 -c 11333

However, it appears the same functionality to specify integer start and stop messages is not available in Apache Pulsar!

To be fair, it's possible to specify a start message id and end message id, if these have been tracked and saved in a byte format, using a very convoluted process which is bound to affect performance and code complexity.

As in this example:

client, err := NewClient(pulsar.ClientOptions{
    URL: lookupURL,
})

if err != nil {
    log.Fatal(err)
}
defer client.Close()

topic := "topic-1"
ctx := context.Background()

// create producer
producer, err := client.CreateProducer(pulsar.ProducerOptions{
    Topic:           topic,
    DisableBatching: true,
})
if err != nil {
    log.Fatal(err)
}
defer producer.Close()

// send 10 messages
msgIDs := [10]MessageID{}
for i := 0; i < 10; i++ {
    msgID, err := producer.Send(ctx, &pulsar.ProducerMessage{
        Payload: []byte(fmt.Sprintf("hello-%d", i)),
    })
    assert.NoError(t, err)
    assert.NotNil(t, msgID)
    msgIDs[i] = msgID
}

// create reader on 5th message (not included)
reader, err := client.CreateReader(pulsar.ReaderOptions{
    Topic:          topic,
    StartMessageID: msgIDs[4],
})

if err != nil {
    log.Fatal(err)
}
defer reader.Close()

// receive the remaining 5 messages
for i := 5; i < 10; i++ {
    msg, err := reader.Next(context.Background())
    if err != nil {
    log.Fatal(err)
}

// create reader on 5th message (included)
readerInclusive, err := client.CreateReader(pulsar.ReaderOptions{
    Topic:                   topic,
    StartMessageID:          msgIDs[4],
    StartMessageIDInclusive: true,
})

if err != nil {
    log.Fatal(err)
}
defer readerInclusive.Close()

However, this is complicated and unreliable (or complex) for multiple concurrent readers and requires the use of an external construct to track the processed messages before it can be retrieved using the start/end semantics.

Is there any way to achieve this (preferably via golang)

Body:
I've found that the following simple approach is sufficient (proof of concept script):

package main

import (
    "context"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "strconv"
    "strings"
    "time"

    "github.com/apache/pulsar-client-go/pulsar"
)

func writeBytesToFile(f string, byteSlice []byte) int {
    // Open a new file for writing only

    f = "./data/" + f

    file, err := os.OpenFile(
        f,
        os.O_WRONLY|os.O_TRUNC|os.O_CREATE,
        0666,
    )
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    // Write bytes to file
    bytesWritten, err := file.Write(byteSlice)

    if err != nil {
        log.Fatal(err)
    }

    log.Printf("Wrote %d bytes.\n", bytesWritten)

    return bytesWritten
}

func readBackByEntryId(msgDir string, msgIndex string) (yourBytes []byte) {

    //We know the file name by convention
    fname := msgDir + "/" + msgIndex + ".dat"

    yourBytes, err := ioutil.ReadFile(fname)

    if err != nil {
        log.Printf("error reading %s", fname)
        return nil
    }

    return yourBytes
}

func getFiles(aDir string) []string {

    var theFiles []string

    files, err := ioutil.ReadDir("./data/")

    if err != nil {
        log.Fatal(err)
    }

    for _, f := range files {

        theFiles = append(theFiles, f.Name())

    }

    return theFiles
}

func streamAll(reader pulsar.Reader, startMsgIndex int64, stopMsgIndex int64) {

    read := false

    for reader.HasNext() {

        msg, err := reader.Next(context.Background())

        if err != nil {
            log.Fatal(err)
        }

        //can I access the details of the message ? yes
        fmt.Printf("%v -> %#v\n", msg.ID().EntryID(), msg.ID())

        //Can i serialize into bytes? Yes
        myBytes := msg.ID().Serialize()

        //Can I store it somewhere? Perhaps a map ? or even on disk in a file ?
        //In other words: Can I write a byte[] slice to a file? Yes!
        msgIndex := msg.ID().EntryID()

        if msgIndex == startMsgIndex {
            fmt.Println("start read: ", msgIndex)
            read = true
        }

        if msgIndex > stopMsgIndex {
            fmt.Println("stop reading: ", msgIndex)
            read = false
        }

        if read == false {

            fmt.Println("skipping ", msgIndex)

        } else {

            fname := strconv.FormatInt(msgIndex, 10) + ".dat"

            fmt.Println("written bytes: ", writeBytesToFile(fname, myBytes))

            fmt.Printf("Received message msgId: %#v -- content: '%s' published at %v\n",
                msg.ID(), string(msg.Payload()), msg.PublishTime())

        }

        /*
            //FYI - to save and reread a msgId from store: https://githubmemory.com/@storm-5
            msgId := msg.ID()
            msgIdBytes := msgId.Serialize()
            idNew, _ := pulsar.DeserializeMessageID(msgIdBytes)

            readerInclusive, err := client.CreateReader(pulsar.ReaderOptions{
                Topic:                   "ragnarok/transactions/requests",
                StartMessageID:          idNew,
                StartMessageIDInclusive: true,
            })
        */
    }

}

func retrieveRange(client pulsar.Client) {

    someFiles := getFiles("./data/")

    for _, f := range someFiles {

        fIndex := strings.Split(f, ".")[0]

        fmt.Println("re-reading message index -> ", fIndex)

        msgIdBytes := readBackByEntryId("./data", fIndex)

        fmt.Printf("boom -> %#v\n", msgIdBytes)

        idNew, err := pulsar.DeserializeMessageID(msgIdBytes)

        if err != nil {
            log.Fatal(err)
        }

        fmt.Println("Got message entry id => ", idNew.EntryID())

        readerInclusive, err := client.CreateReader(pulsar.ReaderOptions{
            Topic:                   "ragnarok/transactions/requests",
            StartMessageID:          idNew,
            StartMessageIDInclusive: true,
        })

        if err != nil {
            log.Fatal(err)
        }

        defer readerInclusive.Close()

        //defer readerInclusive.Close()
        fmt.Println("bleep!")

        msg, err := readerInclusive.Next(context.Background())

        if err != nil {
            log.Fatal(err)
        }

        //fmt.Println("retrieved message -> ", string(msg.Payload()))
        fmt.Printf("Retrieved message ID message msgId: %#v -- content: '%s' published at %v\n",
            msg.ID(), string(msg.Payload()), msg.PublishTime())

    }
}

func main() {

    client, err := pulsar.NewClient(
        pulsar.ClientOptions{
            URL:               "pulsar://localhost:6650",
            OperationTimeout:  30 * time.Second,
            ConnectionTimeout: 30 * time.Second,
        })

    if err != nil {
        log.Fatalf("Could not instantiate Pulsar client: %v", err)
    }

    defer client.Close()

    reader, err := client.CreateReader(pulsar.ReaderOptions{
        Topic:          "ragnarok/transactions/requests",
        StartMessageID: pulsar.EarliestMessageID(),
    })

    if err != nil {
        log.Fatal(err)
    }

    defer reader.Close()

    if err != nil {
        log.Fatal(err)
    }

    var startMsgId int64 = 55
    var stopMsgId int64 = 66

    //stream all the messages from the earliest to latest
    //pick a subset between a start and stop id
    streamAll(reader, startMsgId, stopMsgId)

    //retrieve the picked range
    retrieveRange(client)

}


问:
Not able to edit Public Server Name for embedded Tomcat
we are using Artifactory 6.20.0 in docker-compose mode. Stack is up and running fine. But I am not able to edit the "Public Server Name" in HTTP settings. It is greyed out.

How can I change it?

From Which file TomCat picks these values?

As per my understanding If I change Http settings and use nginx or tomcat. Still my Artifactory is reachable using same address which embedded Tomcat has provided and nginx will be only used for the path based routing. or nginx takes care of both parts?

答:
Please note 'HTTP settings' in Artifactory UI is a template to generate the reverse proxy configuration according to provided fields and you can use the same snippet downloaded and install directly in the corresponding directory of your reverse proxy server.

Answers to your queries:

Embedded tomcat will not pickup any values from this template, it runs on 8081 (over http) by default.

As stated above, changing Http settings in UI will not help as it is a simple template. You must have a reverse proxy installed and place the required configuration on reverse proxy directories in order to access Artifactory over a DNS(http/https). Please refer to Configuring Reverse Proxy wiki page for more details.


问:
Sending HTML Email in php?
Here is the code.

```<code>$to = 'youraddress@example.com';

$subject = 'Test HTML email';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

--PHP-alt-<?php echo $random_hash; ?>--
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
</code>```

I don't follow it well. expect someone can do me a favor.

Why should I generate a random hash?

Why I must add boundary string and mime type specification to header?

Why use ob_start();?

4.

```<code>--PHP-alt-<?php echo $random_hash; ?>
 Content-Type: text/html; charset="iso-8859-1"
 Content-Transfer-Encoding: 7bit
</code>```

What are those lines meaning? Could I delete them? Thank you.

答:
You don't have to. It's just that it makes things easier: the delimiter must be a string that's not part of the mail content.

You need a boundary to split the message in parts. An e-mail message is nothing else that a stream of characters. You need a MIME type so the e-mail client can know what each part contains. Otherwise, it could not know whether it's HTML or not (or a JPEG picture, or a PowerPoint presentation...)

Honestly, it looks like an overcomplicate replacement for regular string assignments. Rather than doing $message = 'Hello World!';, it prints Hello World! to standard output and captures the standard output into a variable.

These lines mean that you are finishing one part of the message and you are starting a new one that contains HTML. You can delete them if you don't want to add another message part that contains HTML but... isn't that what you want to do?

ContentLicense: CC BY-SA 3.0

Title: Sending HTML Email in php?

Body:
Here is the code.

$to = 'youraddress@example.com';

$subject = 'Test HTML email';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!

This is something with HTML formatting.

--PHP-alt-<?php echo $random_hash; ?>--
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>

I don't follow it well. expect someone can do me a favor.

Why should I generate a random hash?

Why I must add boundary string and mime type specification to header?

Why use ob_start();?

4.

--PHP-alt-<?php echo $random_hash; ?>
 Content-Type: text/html; charset="iso-8859-1"
 Content-Transfer-Encoding: 7bit

What are those lines meaning? Could I delete them? Thank you.


问:
cordova build cannot agree on Java version
$ cordova build android –release

When JAVA_HOME points to old C:\Program Files\Java\jdk1.8.0_261 - I get:

Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8.

When JAVA_HOME points to new C:\Program Files\Java\jdk-17.0.2 - I get:

Requirements check failed for JDK 8 ('1.8.*')! Detected version: 17.0.2

How do I solve this?

答:
Older versions of cordova-android required Java 8, which was requirements from the parts & versions of Android SDK cordova used. There is a Android SDK / cordova-android version mismatch in your environment.

As of cordova-android@10 (current version at the time of writing), the Java 8 restriction was opened up to allow Java 11 as cordova-android was updated to use more modern versions of the Android SDK which consequentially requires Java 11.

Requirements check failed for JDK 8 ('1.8.*')

Not sure which cordova-android version you're running but this error definitely means you aren't running cordova-android@10, so I'd suggest to update the cordova-android platform.

```<code>cordova platform remove android
cordova platform add android@10
</code>```

I'd also suggest ensuring you're running cordova cli verison 10 or later as well. (Checkable via cordova -v)

Body:
Older versions of cordova-android required Java 8, which was requirements from the parts & versions of Android SDK cordova used. There is a Android SDK / cordova-android version mismatch in your environment.

As of cordova-android@10 (current version at the time of writing), the Java 8 restriction was opened up to allow Java 11 as cordova-android was updated to use more modern versions of the Android SDK which consequentially requires Java 11.

Requirements check failed for JDK 8 ('1.8.*')

Not sure which cordova-android version you're running but this error definitely means you aren't running cordova-android@10, so I'd suggest to update the cordova-android platform.

cordova platform remove android
cordova platform add android@10

I'd also suggest ensuring you're running cordova cli verison 10 or later as well. (Checkable via cordova -v)


问:
How to compile this both in clang and gcc?
The below code compiles in g++ but error out in clang++. How to fix this code so that it can compile in both?</p>
```<code>class A {
    private:
        template<int _N> class B {
            public:
                static constexpr int N = _N;
        };
        class C {
            public:
                template <typename B>
                B* func();
        };
};

template <typename B>
B* A::C::func()
{
    constexpr int N = B::N;
}
</code>```

答:
clang prior clang 11 is unbale to resolve the name B properly. The solution is use another template parameter name:

```<code>template <typename D>
D* A::C::func()
{
    constexpr int N = D::N;
}
</code>```

The full example requires the public access to A::C at least or a friend function.

```<code>class A {
    private:
        template<int N_> class B {
            public:
                static constexpr int N = N_;
        };
        class C {
            public:
                template <typename B>
                B* func();
        };
    friend int main();
};

template <typename D>
D* A::C::func() {
    constexpr int N = D::N;
    return nullptr;
}

int main() {
    A::C c;
    auto *n = c.func<A::B<0>>();
}
</code>```

Body:
The below code compiles in g++ but error out in clang++. How to fix this code so that it can compile in both?

class A {
    private:
        template<int _N> class B {
            public:
                static constexpr int N = _N;
        };
        class C {
            public:
                template <typename B>
                B* func();
        };
};

template <typename B>
B* A::C::func()
{
    constexpr int N = B::N;
}

Body:
clang prior clang 11 is unbale to resolve the name B properly. The solution is use another template parameter name:

template <typename D>
D* A::C::func()
{
    constexpr int N = D::N;
}

The full example requires the public access to A::C at least or a friend function.

class A {
    private:
        template<int N_> class B {
            public:
                static constexpr int N = N_;
        };
        class C {
            public:
                template <typename B>
                B* func();
        };
    friend int main();
};

template <typename D>
D* A::C::func() {
    constexpr int N = D::N;
    return nullptr;
}

int main() {
    A::C c;
    auto *n = c.func<A::B<0>>();
}


问:
Laravel 8.60.0 creates a file instead of a folder/symlink when I run `php artisan storage:link`

So , I am working on a small project where I need to create a symlink to store file in the storage directory in laravel. I was previously working on windows where the same code was working fine but as I configured Laravel Sail and set it up in my WSL-2 environment, I performed my ritualistic tasks of setting up the config, creating symbolic link, I am noticing a weird behavior of running the php artisan storage:link command where it creates a file instead of a folder in my app/public folder.

It should be a clickable folder or if not clickable, atleast my IDE should show it as a directory like that of others, i.e. like public, bootstrap, database folders. Is that a problem with my WSL or some internal configuration of Laravel. On double clicking this link it shows:

Any assistance will be greatly appreciated.

答:
As a work around, created folder manually and run the command.
sail php artisan storage:link.

It will link


问:
How to convert binary to hexadecimal using python3
which is the easiest way that i can convert binary number into a hexadecimal number using latest python3?

i tried to convert a binary to number into a hexadecimal using hex() function. but it runs into few errors.

The code that i tried -:

```<code>choice = input("Enter Your Binary Number: ")

def binaryToHex(num):
    answer = hex(num)
    return(num)

print(binaryToHex(choice))
</code>```

error that i faced :

```<code>Traceback (most recent call last):
  File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 83, in <module>
    print(binaryToHex(choice))
  File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 80, in binaryToHex
    answer = hex(num)
TypeError: 'str' object cannot be interpreted as an integer
</code>```

EXAMPLE-:

111 --> 7

1010101011 --> 2AB

答:
<pre class="lang-py prettyprint-override"><code># Python code to convert from Binary
# to Hexadecimal using int() and hex()
def binToHexa(n):

    # convert binary to int
    num = int(str(n), 2)

    # convert int to hexadecimal
    hex_num = hex(num)
    return(hex_num)
</code>```

Body:
which is the easiest way that i can convert binary number into a hexadecimal number using latest python3?

i tried to convert a binary to number into a hexadecimal using hex() function. but it runs into few errors.

The code that i tried -:

choice = input("Enter Your Binary Number: ")

def binaryToHex(num):
    answer = hex(num)
    return(num)

print(binaryToHex(choice))

error that i faced :

Traceback (most recent call last):
  File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 83, in <module>
    print(binaryToHex(choice))
  File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 80, in binaryToHex
    answer = hex(num)
TypeError: 'str' object cannot be interpreted as an integer

EXAMPLE-:

111 --> 7

1010101011 --> 2AB


答:
Use int to convert a string of digits to an integer.  Use hex to convert that integer back to a hex string.

```<code>>>> hex(int('111', 2))
'0x7'
>>> hex(int('1010101011', 2))
'0x2ab'
</code>```

Title: How to convert binary to hexadecimal using python3

Body:
Use int to convert a string of digits to an integer.  Use hex to convert that integer back to a hex string.

>>> hex(int('111', 2))
'0x7'
>>> hex(int('1010101011', 2))
'0x2ab'


问:
How do I make the bottom area of my grid grow into the bottom right corner?
I want to grow the div with the text of "Five" to cover the area below "Two and Three" in this grid. However, I'm not sure what to do beyond making the div having the property of "Flex:1". If you run the snippet below, you can see that "Five" is below only "Two".

body{
    width: 100%;
}

.wrapper {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    width: 80%;
    margin: auto;
}

.Five{
    flex: 1;
    background-color: blue;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel = "stylesheet" href="styles.css">
</head>
<body>
    <div class="wrapper">
        <div class="One">One</div>
        <div class="Two">Two</div>
        <div class="Three">Three</div>
        <div class="Four">Four</div>
        <div class="Five">Five</div>
      </div>

</body>
</html></code>```

答: Add  grid-column: 2 / 4 to .Five which will make that element span the 2nd and 3rd columns.

Body:
I want to grow the div with the text of "Five" to cover the area below "Two and Three" in this grid. However, I'm not sure what to do beyond making the div having the property of "Flex:1". If you run the snippet below, you can see that "Five" is below only "Two".

body{
    width: 100%;
}

.wrapper {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    width: 80%;
    margin: auto;
}

.Five{
    flex: 1;
    background-color: blue;

}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel = "stylesheet" href="styles.css">

One

Two

Three

Four

Five


问:
How do I add a space between a RadioButtonList's radio buttons and their text?
I have been reading about some workaround but haven't found anything that works for me.  I'm using Bootstrap in my ASPX page to display a RadioButtonList with "Yes" and "No" options like so:

```<code><div class="form-group my-3">
    <label class="form-label" style="margin-top: 0px; margin-right: 15px; margin-bottom: 0px;">I worked in person:</label>
    <asp:RadioButtonList runat="server" ID="input_inPerson">
        <asp:ListItem Selected="False" Value="true">Yes</asp:ListItem>
        <asp:ListItem Selected="False" Value="false">No</asp:ListItem>
    </asp:RadioButtonList>
</div>
</code>```

The button and text are not spaced at all, as shown here:

My question is, are there any ways to add a space between this button and the text? If so, can I use bootstrap's "m" classes to do it?

答:
Just toss in a style, as the "label" part of the radio buttons are rendered as a simple "label"

So, try this:

```<code>        <style>
            .butLabel label {margin-left:15px}
        </style>

    <div class="form-group my-3">
        <label class="form-label" style="margin-top: 0px; margin-right: 15px; margin-bottom: 0px;">I worked in person:</label>
        <asp:RadioButtonList runat="server" ID="input_inPerson" CssClass="butLabel">
            <asp:ListItem Selected="False" Value="true">Yes</asp:ListItem>
            <asp:ListItem Selected="False" Value="false">No</asp:ListItem>
        </asp:RadioButtonList>
    </div>
</code>```

So, with say 15px, you get this:

Body:
I have been reading about some workaround but haven't found anything that works for me.  I'm using Bootstrap in my ASPX page to display a RadioButtonList with "Yes" and "No" options like so:

    I worked in person:
    <asp:RadioButtonList runat="server" ID="input_inPerson">
        <asp:ListItem Selected="False" Value="true">Yes</asp:ListItem>
        <asp:ListItem Selected="False" Value="false">No</asp:ListItem>
    </asp:RadioButtonList>

The button and text are not spaced at all, as shown here:

My question is, are there any ways to add a space between this button and the text? If so, can I use bootstrap's "m" classes to do it?

Body:
Just toss in a style, as the "label" part of the radio buttons are rendered as a simple "label"

So, try this:

        <style>
            .butLabel label {margin-left:15px}
        </style>

    <div class="form-group my-3">
        <label class="form-label" style="margin-top: 0px; margin-right: 15px; margin-bottom: 0px;">I worked in person:</label>
        <asp:RadioButtonList runat="server" ID="input_inPerson" CssClass="butLabel">
            <asp:ListItem Selected="False" Value="true">Yes</asp:ListItem>
            <asp:ListItem Selected="False" Value="false">No</asp:ListItem>
        </asp:RadioButtonList>
    </div>

So, with say 15px, you get this:


问:
Using Knockout.js with CouchDB - updating when changed
Just wondering about the best way to subscribe to my CouchDB data store, so that if a document in couch is updated, the KO view will also update (automagically). Is this something that's even possible?

Below is what I have so far, which simply get the user name from the user_info document.

```<code>$.getJSON('http://localhost/couchdb/user_info', function(data) {
    var viewModel = ko.mapping.fromJS(data);
    ko.applyBindings(viewModel);
});
</code>```

Any help would be greatly appreciated!

答:
CouchDB supports notifications when documents change: the changes feed.

You can poll the changes feed, with a ?since=X parameter to receive only updates since X.

You can also "long poll" the feed by adding &feed=longpoll. If there are no changes yet, CouchDB will receive your query but not answer until finally a change comes on.

Or, you can have a full COMET-style feed by instead adding &feed=continuous. That is similar to longpoll, however CouchDB will never close the connection. Every time a change happens, it will send you the JSON and then continue waiting.

Finally, you can be notified when anything changes in the database, or you can specify a Javascript filter to run on the server (&filter=designdoc/filtername). You will only receive notifications if the filter approves.

Body:
Just wondering about the best way to subscribe to my CouchDB data store, so that if a document in couch is updated, the KO view will also update (automagically). Is this something that's even possible?

Below is what I have so far, which simply get the user name from the user_info document.

$.getJSON('http://localhost/couchdb/user_info', function(data) {
    var viewModel = ko.mapping.fromJS(data);
    ko.applyBindings(viewModel);
});

Any help would be greatly appreciated!


问:
Host: localhost. is not in the cert's altnames
I'm getting the below error while doing server-side rendering.

```<code>RENDERING ERROR: { [Error: Network error: request to https://api-dev.xyz.io/graphql failed, reason: Hostname/IP doesn't match certificate's altnames: "Host: localhost. is not in the cert's altnames: DNS:*.xyz.io"]
  graphQLErrors: null,
  networkError:
   { [FetchError: request to https://api-dev.xyz.io/graphql failed, reason: Hostname/IP doesn't match certificate's altnames: "Host: localhost. is not in the cert's altnames: DNS:*.xyz.io"]
     name: 'FetchError',
     message: 'request to https://api-dev.xyz.io/graphql failed, reason: Hostname/IP doesn\'t match certificate\'s altnames: "Host: localhost. is not in the cert\'s altnames: DNS:*.xyz.io"',
     type: 'system',
     errno: undefined,
     code: undefined },
  message: 'Network error: request to https://api-dev.xyz.io/graphql failed, reason: Hostname/IP doesn\'t match certificate\'s altnames: "Host: localhost. is not in the cert\'s altnames: DNS:*.xyz.io"',
  extraInfo: undefined }
</code>```

Note:- I'm using react, redux, apollo-client(GraphQL) and ExpressJS(NodeJS). The API server to which I'm making the request is on another domain and I can't make any change on that.

While working with client-side rendering I'm not facing any difficulties everything is working as intended but while doing server-side render I'm getting the above error.

So I tried the below approaches on my server but still no luck.

Adding self-signed certificate

Adding 'rejectUnauthorized':false in https options.

```<code>const options = {
  'key': key,
  'cert': cert,
  'ca': [ fs.readFileSync('local-certificate.pem') ],
  'rejectUnauthorized':false
};

https.createServer(options, app).listen(httpsPort, '0.0.0.0', function onStart(err) {
  if (err) { console.log(err); }
  console.info('==> Listening on httpsPort %s. Open up http://0.0.0.0:%s/ in your browser.', httpsPort, options);
});
</code>```

Also I tried to add an alt name in my self-signed certificate with the help of How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Is there any way to bypass certificate verification so that my express server can make a request to the API server which is on another domain with a valid certificate?

I'm still a bit unsure whether I can fix it by making any changes at my end (on my express server).

Please let me know any insights on this.

答:
I believe Michael Landis was trying to get this point across, but didn't quite provide the solution. If your service is running on locally on 192.168.100.100, then this needs to be in your hosts file (e.g. /etc/hosts on linux):

```<code>192.168.100.100 api-dev.xyz.io
</code>```

The request that's currently failing needs to be made to api-dev.xyz.io, even during SSR. It's much easier to avoid the requests to "http[s]://localhost/...".

Body:
I'm getting the below error while doing server-side rendering.

RENDERING ERROR: { [Error: Network error: request to https://api-dev.xyz.io/graphql failed, reason: Hostname/IP doesn't match certificate's altnames: "Host: localhost. is not in the cert's altnames: DNS:*.xyz.io"]
  graphQLErrors: null,
  networkError:
   { [FetchError: request to https://api-dev.xyz.io/graphql failed, reason: Hostname/IP doesn't match certificate's altnames: "Host: localhost. is not in the cert's altnames: DNS:*.xyz.io"]
     name: 'FetchError',
     message: 'request to https://api-dev.xyz.io/graphql failed, reason: Hostname/IP doesn\'t match certificate\'s altnames: "Host: localhost. is not in the cert\'s altnames: DNS:*.xyz.io"',
     type: 'system',
     errno: undefined,
     code: undefined },
  message: 'Network error: request to https://api-dev.xyz.io/graphql failed, reason: Hostname/IP doesn\'t match certificate\'s altnames: "Host: localhost. is not in the cert\'s altnames: DNS:*.xyz.io"',
  extraInfo: undefined }

Note:- I'm using react, redux, apollo-client(GraphQL) and ExpressJS(NodeJS). The API server to which I'm making the request is on another domain and I can't make any change on that.

While working with client-side rendering I'm not facing any difficulties everything is working as intended but while doing server-side render I'm getting the above error.

So I tried the below approaches on my server but still no luck.

Adding self-signed certificate

Adding 'rejectUnauthorized':false in https options.

const options = {
  'key': key,
  'cert': cert,
  'ca': [ fs.readFileSync('local-certificate.pem') ],
  'rejectUnauthorized':false
};

https.createServer(options, app).listen(httpsPort, '0.0.0.0', function onStart(err) {
  if (err) { console.log(err); }
  console.info('==> Listening on httpsPort %s. Open up http://0.0.0.0:%s/ in your browser.', httpsPort, options);
});

Also I tried to add an alt name in my self-signed certificate with the help of How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Is there any way to bypass certificate verification so that my express server can make a request to the API server which is on another domain with a valid certificate?

I'm still a bit unsure whether I can fix it by making any changes at my end (on my express server).

Please let me know any insights on this.

Body:
I believe Michael Landis was trying to get this point across, but didn't quite provide the solution. If your service is running on locally on 192.168.100.100, then this needs to be in your hosts file (e.g. /etc/hosts on linux):

192.168.100.100 api-dev.xyz.io

The request that's currently failing needs to be made to api-dev.xyz.io, even during SSR. It's much easier to avoid the requests to "http[s]://localhost/...".


问:
Converting "Stream<String>" to "String" in java8 to combine group of strings in a stream
I want to convert Stream<String> to String and print all the string.

```<code>Stream<String> result= Stream.of("do","re","ma","po","fa","si")
                             .filter(str -> str.length()>5)
                             .peek(System.out:: println);
                           //.allMatch(str -> str.length() >5);

System.out.println(result);
</code>```

Here down output i get

java.util.Spliterators$1Adapter@63961c42

The result is printing an object but not a String and while converting to toString() also printing the same but how to print as a String

答:
you need to 'execute' the stream by calling collect or reduce</p>
```<code>assertEquals("ab", Arrays.stream(new String[]{"a", "b"}).reduce("", (s,x) -> s + x));
</code>```

Body:
I want to convert Stream<String> to String and print all the string.

Stream<String> result= Stream.of("do","re","ma","po","fa","si")
                             .filter(str -> str.length()>5)
                             .peek(System.out:: println);
                           //.allMatch(str -> str.length() >5);

System.out.println(result);

Here down output i get

java.util.Spliterators$1Adapter@63961c42

The result is printing an object but not a String and while converting to toString() also printing the same but how to print as a String

Body:
you need to 'execute' the stream by calling collect or reduce

assertEquals("ab", Arrays.stream(new String[]{"a", "b"}).reduce("", (s,x) -> s + x));


问:
Using sans-serif-condensed in compose
I'm want to use sans-serif-condensed in jetpack compose, but for the life of me, I can't find it anywhere within compose itself?

Am I just blind, or will I need to do something like import the font and set it all manually?

答:
You can use the fontFamily attribute to specify the font family.

```<code>Text("Hello World", fontFamily = FontFamily.Serif)
</code>```

Predefined Fonts

By default, Jetpack compose has only 5 Font Families,

Default, SansSerif, Serif, Monospace and Cursive.

Custom Fonts

If you need any other font family (which seems to be your case), you have to add it as mentioned here.

Steps

Download or Get the required fonts files and add them to the res/fonts directory.

Create FontFamily like this,

```<code> val firaSansFamily = FontFamily(
     Font(R.font.firasans_light, FontWeight.Light),
     Font(R.font.firasans_regular, FontWeight.Normal),
     Font(R.font.firasans_italic, FontWeight.Normal, FontStyle.Italic),
     Font(R.font.firasans_medium, FontWeight.Medium),
     Font(R.font.firasans_bold, FontWeight.Bold)
 )
</code>```

Use like this,

```<code> Text(..., fontFamily = firaSansFamily, fontWeight = FontWeight.Light)
 Text(..., fontFamily = firaSansFamily, fontWeight = FontWeight.Normal)
</code>```

Title: Using sans-serif-condensed in compose

Body:
You can use the fontFamily attribute to specify the font family.

Text("Hello World", fontFamily = FontFamily.Serif)

Predefined Fonts

By default, Jetpack compose has only 5 Font Families,

Default, SansSerif, Serif, Monospace and Cursive.

Custom Fonts

If you need any other font family (which seems to be your case), you have to add it as mentioned here.

Steps

Download or Get the required fonts files and add them to the res/fonts directory.

Create FontFamily like this,

 val firaSansFamily = FontFamily(
     Font(R.font.firasans_light, FontWeight.Light),
     Font(R.font.firasans_regular, FontWeight.Normal),
     Font(R.font.firasans_italic, FontWeight.Normal, FontStyle.Italic),
     Font(R.font.firasans_medium, FontWeight.Medium),
     Font(R.font.firasans_bold, FontWeight.Bold)
 )

Use like this,

 Text(..., fontFamily = firaSansFamily, fontWeight = FontWeight.Light)
 Text(..., fontFamily = firaSansFamily, fontWeight = FontWeight.Normal)


问:
move rows between two datatables
So here's the thing, I have two datatables side by side and I nedd to add items(rows) from Table A to Table B.

'Before' datatable I was doing all right using append:

```<code>function add(num)
{
      ...
      $("#myDiv1 tr#p"+num).appendTo("#myDiv2");
      ...
}
</code>```

Of course this doesn't work with datatables since does not update the table, and I can't seem to get It working using datatables functions, my code goes like the following but isn't working at all:

```<code>function add()
{
       ...
       stockTable = $('#stocktable').dataTable();
       catalogTable = $('#catalogtable').dataTable();
       var trdata = stockTable.fnGetData($(this).closest('tr'));
       stockTable.fnDeleteRow($(this).closest('tr'));
       catalogtable.fnAddData(trdata);
       ...
}
</code>```

Help appreciated!

答:
if table rows has custom css styles you can use row().node instead row().data() to copy classes and other attributes

```<code>         btpick.click(function() {
            table1.rows({
                selected: true
            }).every(function() {
                table2.row.add(this.node());
            }).remove();
            table1.draw();
            table2.draw();
         });

</code>```

and here a function to move all rows

```<code>         btpickall.click(function() {
            tqable2.rows.add(table1.rows().nodes()).draw();
            table1.clear();
         });
</code>```

Title: move rows between two datatables

Body:
So here's the thing, I have two datatables side by side and I nedd to add items(rows) from Table A to Table B.

'Before' datatable I was doing all right using append:

function add(num)
{
      ...
      $("#myDiv1 tr#p"+num).appendTo("#myDiv2");
      ...
}

Of course this doesn't work with datatables since does not update the table, and I can't seem to get It working using datatables functions, my code goes like the following but isn't working at all:

function add()
{
       ...
       stockTable = $('#stocktable').dataTable();
       catalogTable = $('#catalogtable').dataTable();
       var trdata = stockTable.fnGetData($(this).closest('tr'));
       stockTable.fnDeleteRow($(this).closest('tr'));
       catalogtable.fnAddData(trdata);
       ...
}

Help appreciated!

Body:
if table rows has custom css styles you can use row().node instead row().data() to copy classes and other attributes

         btpick.click(function() {
            table1.rows({
                selected: true
            }).every(function() {
                table2.row.add(this.node());
            }).remove();
            table1.draw();
            table2.draw();
         });

and here a function to move all rows

         btpickall.click(function() {
            tqable2.rows.add(table1.rows().nodes()).draw();
            table1.clear();
         });


问:
About flash builder mobile application iOS build file
I have made one one mobile application in flash builder using flex mobile project
I have a question that "why size of an .ipa file is large as I export a mobile application as iOS application.???? in compare to that same application for android takes small size!!!

Thanks in advance...

答:
Because the AIR Runtime is embedded in the .ipa
The application for Android doesn't embed the runtime, the runtime AIR is an other application.


问:
zsh: command not found: pre-commit but package installed
Installed pre-commit successfully using the following command in VSCode:

python3 -m pip install pre-commit --user
```
<p>but when I try to do the pre-commit install, I get the error message:</p>
<pre class="lang-py prettyprint-override"><code>zsh: command not found: pre-commit
</code>```

答:
Try adding this command to your .zshrc so that it recognizes your .bashrc commands, something similar to yours was happening to me.

```<code>[[ -e ~/.profile ]] && emulate sh -c 'source ~/.profile'
</code>```

for more information: How can you export your .bashrc to .zshrc?

Body:
Installed pre-commit successfully using the following command in VSCode:

python3 -m pip install pre-commit --user

but when I try to do the pre-commit install, I get the error message:

zsh: command not found: pre-commit

Body:
Try adding this command to your .zshrc so that it recognizes your .bashrc commands, something similar to yours was happening to me.

[[ -e ~/.profile ]] && emulate sh -c 'source ~/.profile'

for more information: How can you export your .bashrc to .zshrc?


问:
add hostname mappings using --add-host parameter not working for scratch image
Add hostname mappings using the --add-host parameter is not working for a scratch image.

I configure it as following:

```<code>extra_hosts:
  - "op.swish-cloud.com:10.170.0.2"
</code>```

But the actual id of requests from the container is the external internet ip of op.swish-cloud.com rather than 10.170.0.2

答: In case anyone ends up here from a Google search, this is going to be expected behavior. You need to mount a file as /etc/hosts or at least make sure the file exists in order for --add-host to work in the scratch image.

Body:
Add hostname mappings using the --add-host parameter is not working for a scratch image.

I configure it as following:

extra_hosts:
  - "op.swish-cloud.com:10.170.0.2"

But the actual id of requests from the container is the external internet ip of op.swish-cloud.com rather than 10.170.0.2


问:
Schematic input does not validate against the Schema: {"name":"testng7"} on Angular 7
I updated the Angular CLI to the latest @angular/cli@7.0.2 on a Mac OS. When issuing the command ng new testng7, I get this error:

```<code>Schematic input does not validate against the Schema: {"name":"testng7"}
Errors:
  Data path "" should have required property 'version'.
</code>```

And nothing is created. Any clues how to fix?

答:
none of the solutions helped me or does not deal with the root cause.
I found this in my angular.json

```<code>  "schematics": {
"@schematics/angular:component": {
  "styleext": "scss"
 }
}
</code>```

Also my IDE was showing styletext property was not allowed. So I changed the above to this and it works.

```<code>    "@schematics/angular:component": {
      "skipTests": true
    }
  }
</code>```

Body:
I updated the Angular CLI to the latest @angular/cli@7.0.2 on a Mac OS. When issuing the command ng new testng7, I get this error:

Schematic input does not validate against the Schema: {"name":"testng7"}
Errors:
  Data path "" should have required property 'version'.

And nothing is created. Any clues how to fix?

Body:
none of the solutions helped me or does not deal with the root cause.
I found this in my angular.json

  "schematics": {
"@schematics/angular:component": {
  "styleext": "scss"
 }
}

Also my IDE was showing styletext property was not allowed. So I changed the above to this and it works.

    "@schematics/angular:component": {
      "skipTests": true
    }
  }


问:
Vue style is not being applied
I am facing a strange problem in which the style in my vue component is not being compiled and applied along with the template and script.

I've included my code below. The intention is to animate a slide fade on the hidden text when I click the button. The actual result is the text becomes visible but the css is not applied to it.

app.vue

```<code><template>
  <div>
    <button @click="show = !show">
      Click Me
    </button>
    <transition name="slide-fade">
      <p class="test-style" v-if="show">This is a hidden message.</p>
    </transition>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        show: false,
      };
    },
  };
</script>

<style scoped>
  .test-style {
    color: red;
  }
  .slide-fade-enter-active {
    transition: all .3s ease;
  }
  .slide-fade-leave-active {
    transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
  }
  .slide-fade-enter, .slide-fade-leave-to {
    transform: translateX(10px);
    opacity: 0;
  }
</style>
</code>```

app.js

```<code>import Vue from 'vue'
import App from './app.vue'

new Vue({
  el: '#app',
  render: h => h(App),
});
</code>```

Edit - Aug 10th, 2020

This is my package.json

```<code>{
  "name": "www",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "dependencies": {
    "vue": "^2.6.11"
  },
  "devDependencies": {
    "css-loader": "^4.2.1",
    "nodemon-webpack-plugin": "^4.3.2",
    "vue-loader": "^15.9.3",
    "vue-style-loader": "^4.1.2",
    "vue-template-compiler": "^2.6.11",
    "webpack": "^4.44.1",
    "webpack-cli": "^3.3.12"
  },
  "scripts": {
    "build": "webpack",
    "dev": "webpack --watch",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

</code>```

答:
I am just learning VueJS 3 along with Larave 8 and I was experimenting the same problem, but it was because I didn't run the

npm run dev

command in the console.

Title: Vue style is not being applied

Body:
I am facing a strange problem in which the style in my vue component is not being compiled and applied along with the template and script.

I've included my code below. The intention is to animate a slide fade on the hidden text when I click the button. The actual result is the text becomes visible but the css is not applied to it.

app.vue

<template>

    <button @click="show = !show">
      Click Me
    </button>
    <transition name="slide-fade">

This is a hidden message.

    </transition>

</template>

app.js

import Vue from 'vue'
import App from './app.vue'

new Vue({
  el: '#app',
  render: h => h(App),
});

Edit - Aug 10th, 2020

This is my package.json

{
  "name": "www",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "dependencies": {
    "vue": "^2.6.11"
  },
  "devDependencies": {
    "css-loader": "^4.2.1",
    "nodemon-webpack-plugin": "^4.3.2",
    "vue-loader": "^15.9.3",
    "vue-style-loader": "^4.1.2",
    "vue-template-compiler": "^2.6.11",
    "webpack": "^4.44.1",
    "webpack-cli": "^3.3.12"
  },
  "scripts": {
    "build": "webpack",
    "dev": "webpack --watch",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}


问:
How to fetch private data using Googlesheets API to my website using nodeJs
I need to access some data from a private Google Sheets document that only my google account has access to – it is not shared with anyone else.

From here: https://developers.google.com/sheets/guides/authorizing

When your application requests private data, the request must be
authorized by an authenticated user who has access to that data.

Again, that user would be me – the application developer. The users of my application will not have these sheets shared with them.

From what I’m reading in the Google API docs, I’m not sure this is possible – but it seems to me like it should be. I am using nodeJs.

Can anyone help me out?

答:
You'll want to use Google's OAuth flow (here) in order to get access to private sheets. If only you need to be able to access the sheet then you can keep the OAuth as only tied to yourself and make requests to the endpoint in your app.

Example Implementation
View in Fusebit

  // Create a sheet object for the client + auth
  const sheets = google.sheets({
    version: 'v4',
    auth
  })

  // Pull the data from our spreadsheet
  const data = (await sheets.spreadsheets.values.get({
      // See: https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
      spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms', // ID of the spreadsheet
      range: 'Class Data!A2:E', // This gets all of the data in the sheet that we care about
  })).data;

  // Your rows/columns go into "data.values"
  const rows = data.values;
});
```


问:
T4 Template not working with List as a parameter
I have a T4 template.

```<code><#@ template language="C#" #>
<#@ import namespace="System.Collections.Generic"#>
<#@parameter name="Stats" type="System.Collections.Generic.List<SiteStat>" #>
<#@parameter name="Cnt" type="System.Int32" #>

    This is a test.  Why is this not working <#= Cnt #>
    <table>
        <# foreach (SiteStat stat in Stats)
           { #>
             <tr><td>Test name <#= stat.node #> </td>
                 <td>Test value <#= stat.region #> </td> </tr>
        <# } #>
     </table>
</code>```

The simple integer is passing into the system fine
but the more complex List is not.

It does not generate any content inside the table tags.

Edit 4/26/2021:
My SiteStat is defined as follows

```<code>namespace ScheduledJobsService
{
    [Serializable]
    public struct SiteStat
    {
        public string region { get; set; }
        public string district { get; set; }
        public string system { get; set; }
        public string node { get; set; }
        public float a1score { get; set; }
        public float a1delta { get; set; }
        public float a7score { get; set; }
        public float a7delta { get; set; }
        public SiteStat(string region, string district, string system, string node, float a1score, float a1delta, float a7score, float a7delta)
        {
            this.region = region;
            this.district = district;
            this.system = system;
            this.node = node;
            this.a1score = a1score;
            this.a1delta = a1delta;
            this.a7score = a7score;
            this.a7delta = a7delta;
        }
    }
}
</code>```

I tried using ScheduledJobsService.SiteStat inside my teplate as so

```<code><#@parameter name="Stats" type="System.Collections.Generic.List<ScheduledJobsService.SiteStat>" #>
</code>```

But it wont compile claiming that SiteStat does not exist in the ScheduledJobsService namespace

答:
At the end of the .tt file add your parameters as public class members inside a "Class feature control block".
This block must go to the end of the file.

```<code><#+
public SiteStat Stats{ get; set; }
#>
</code>```

you can use your template as follows:

```<code>YourTemplate t = new YourTemplate
{
    Stats = yourStatsObj
};
</code>```

For more information regarding the T4 syntax, see MSDN article Writing a T4 Text Template. Writing a T4 Text Template

Body:
I have a T4 template.

<#@ template language="C#" #>
<#@ import namespace="System.Collections.Generic"#>
<#@parameter name="Stats" type="System.Collections.Generic.List<SiteStat>" #>
<#@parameter name="Cnt" type="System.Int32" #>

    This is a test.  Why is this not working <#= Cnt #>

        <# foreach (SiteStat stat in Stats)
           { #>

Test name <#= stat.node #>
                 Test value <#= stat.region #>

        <# } #>

The simple integer is passing into the system fine
but the more complex List is not.

It does not generate any content inside the table tags.

Edit 4/26/2021:
My SiteStat is defined as follows

namespace ScheduledJobsService
{
    [Serializable]
    public struct SiteStat
    {
        public string region { get; set; }
        public string district { get; set; }
        public string system { get; set; }
        public string node { get; set; }
        public float a1score { get; set; }
        public float a1delta { get; set; }
        public float a7score { get; set; }
        public float a7delta { get; set; }
        public SiteStat(string region, string district, string system, string node, float a1score, float a1delta, float a7score, float a7delta)
        {
            this.region = region;
            this.district = district;
            this.system = system;
            this.node = node;
            this.a1score = a1score;
            this.a1delta = a1delta;
            this.a7score = a7score;
            this.a7delta = a7delta;
        }
    }
}

I tried using ScheduledJobsService.SiteStat inside my teplate as so

<#@parameter name="Stats" type="System.Collections.Generic.List<ScheduledJobsService.SiteStat>" #>

But it wont compile claiming that SiteStat does not exist in the ScheduledJobsService namespace

Body:
At the end of the .tt file add your parameters as public class members inside a "Class feature control block".
This block must go to the end of the file.

<#+
public SiteStat Stats{ get; set; }
#>

you can use your template as follows:

YourTemplate t = new YourTemplate
{
    Stats = yourStatsObj
};

For more information regarding the T4 syntax, see MSDN article Writing a T4 Text Template. Writing a T4 Text Template


问:
intern() behaving differently in Java 6 and Java 7
```<code>class Test {
    public static void main(String...args) {
        String s1 = "Good";
        s1 = s1 + "morning";
        System.out.println(s1.intern());
        String s2 = "Goodmorning";
        if (s1 == s2) {
            System.out.println("both are equal");
        }
    }
}
</code>```

This code produces different outputs in Java 6 and Java 7.
In Java 6 the s1==s2 condition returns false and in Java 7 the s1==s2 returns true. Why?

Why does this program produces different output in Java 6 and Java 7?

答:
FIRST CASE:

In the first code snipped you are actually adding three Strings in the Pool of Strings.
1. s1 = "Good"

2. s1 = "Goodmorning" (after concatenating)
3. s2 = "Goodmorining"

While doing if(s1==s2), the objects are same but reference as different hence it is false.

SECOND CASE:

In this case you are using s1.intern(), which implies that if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

s1 = "Good"

s1 = "Goodmorning" (after concatenating)

For String s2="Goodmorning", new String is not added to the pool and you get reference of existing one for s2. Hence if(s1==s2) returns true.

Body:
class Test {
    public static void main(String...args) {
        String s1 = "Good";
        s1 = s1 + "morning";
        System.out.println(s1.intern());
        String s2 = "Goodmorning";
        if (s1 == s2) {
            System.out.println("both are equal");
        }
    }
}

This code produces different outputs in Java 6 and Java 7.
In Java 6 the s1==s2 condition returns false and in Java 7 the s1==s2 returns true. Why?

Why does this program produces different output in Java 6 and Java 7?


问:
NestJS and passport-local : AuthGuard('local') validate() never get called
I've followed the official Nest doc (https://docs.nestjs.com/security/authentication) step by step, but I can't get validate() method called when using @AuthGuard('local') or @AuthGuard(LocalAuthGuard) on login action.

If I don't use that guard decorator, all works as expected (but I need to use it to get my token added to request object).

auth.controller.ts

  @UseGuards(AuthGuard('local')) // or AuthGuard(LocalAuthGuard)
  @Post('login')
  async login(
    @Request() req
  ) {
    const { access_token } = await this.authService.login(req.user);
    return access_token;
  }
}
```
<p><strong>local.strategy.ts</strong></p>
<pre class="lang-js prettyprint-override"><code>@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({ usernameField: 'email' });
  }

  async validate(email: string, password: string): Promise<any> { // class is constructed but this method is never called
    const user: UserDto = await this.authService.login({
      email,
      password,
    });

    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}
</code>```

auth.module.ts

@Module({
  imports: [
    UsersModule,
    PassportModule,
    JwtModule.register({
      secret: "bidon",
      signOptions: {
        expiresIn: '3600',
      },
    }),
  ],
  providers: [AuthService, LocalStrategy, JwtStrategy],
  exports: [AuthService, PassportModule, JwtModule],
  controllers: [AuthController],
})
export class AuthModule {}
```

PS : I've already read all stack overflow related posts (for exemple : NestJS' Passport Local Strategy "validate" method never called) but they didn't help me.

答:
I found that if we don't pass email or password, also the wrong value of both, the guard will response Unauthorized message. The problem is how to ensure that validation of the required field before run guard logic if it not defined, In other words, frontend not pass it to server. If we add @Body() data: loginDto in controller method, it won't validate the body params.

to solve it, I add some validation code in local.guard.ts file. Here is my code in my project:

import { HttpException, HttpStatus, Injectable, UnauthorizedException } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";

@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {
  handleRequest(err, user, info, context, status) {
    const request = context.switchToHttp().getRequest();
    const { mobile, password } = request.body;
    if (err || !user) {
      if (!mobile) {
        throw new HttpException({ message: '手机号不能为空' }, HttpStatus.OK);
      } else if (!password) {
        throw new HttpException({ message: '密码不能为空' }, HttpStatus.OK);
      } else {
        throw err || new UnauthorizedException();
      }
    }
    return user;
  }
}
```

Body:
I've followed the official Nest doc (https://docs.nestjs.com/security/authentication) step by step, but I can't get validate() method called when using @AuthGuard('local') or @AuthGuard(LocalAuthGuard) on login action.

If I don't use that guard decorator, all works as expected (but I need to use it to get my token added to request object).

auth.controller.ts

  @UseGuards(AuthGuard('local')) // or AuthGuard(LocalAuthGuard)
  @Post('login')
  async login(
    @Request() req
  ) {
    const { access_token } = await this.authService.login(req.user);
    return access_token;
  }
}

local.strategy.ts

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({ usernameField: 'email' });
  }

  async validate(email: string, password: string): Promise<any> { // class is constructed but this method is never called
    const user: UserDto = await this.authService.login({
      email,
      password,
    });

    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

auth.module.ts

@Module({
  imports: [
    UsersModule,
    PassportModule,
    JwtModule.register({
      secret: "bidon",
      signOptions: {
        expiresIn: '3600',
      },
    }),
  ],
  providers: [AuthService, LocalStrategy, JwtStrategy],
  exports: [AuthService, PassportModule, JwtModule],
  controllers: [AuthController],
})
export class AuthModule {}

PS : I've already read all stack overflow related posts (for exemple : NestJS' Passport Local Strategy "validate" method never called) but they didn't help me.


问:
Ionic build time error "No installed build tools found. Install the Android build tools version 30.0.3 or higher"
I'm stack on one error in on build time with Cordova.
I have already installed android build tools but ionic through error "No installed build tools found. Install the Android build tools version 30.0.3 or higher". I do not understand why this error show. Below mentioned error, please check and help me.

ANDROID_HOME=C:\Users\prade\AppData\Local\Android\Sdk (DEPRECATED)
Using Android SDK: C:\Users\prade\AppData\Local\Android\Sdk\build-tools\32.0.0
Subproject Path: CordovaLib
Subproject Path: app

FAILURE: Build failed with an exception.

Where:
Script 'C:\ionic\demoApp\platforms\android\CordovaLib\cordova.gradle' line: 69

What went wrong:
A problem occurred evaluating script.

No installed build tools found. Install the Android build tools version 30.0.3 or higher.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.1.1/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 1s
Command failed with exit code 1: C:\ionic\demoApp\platforms\android\gradlew :app:bundleRelease -b C:\ionic\demoApp\platforms\android\build.gradle
[ERROR] An error occurred while running subprocess cordova.

```<code>    cordova.cmd build android --release exited with exit code 1.

    Re-running this command with the --verbose flag may provide more information.
</code>```

答:
The error produced by Cordova is misleading (there is an open issue here).

Cordova by default is looking for build tools version >= 30.0.3 but still within version 30. The purpose for this behaviour is so Cordova doesn't automatically pick up a build tools version that it is likely not compatible with.

Using <preference name="android-buildToolsVersion" value="32.0.0" /> should allow you to override this behaviour and Cordova will use the desired build tools version as requested.

However there are known incompatiblities with Build tools version 31, and I doubt build tools 32 will work either. I'd highly suggest installing build tools 30.0.3 as that's the version that is tested against the current version of cordova.

Body:
I'm stack on one error in on build time with Cordova.
I have already installed android build tools but ionic through error "No installed build tools found. Install the Android build tools version 30.0.3 or higher". I do not understand why this error show. Below mentioned error, please check and help me.

ANDROID_HOME=C:\Users\prade\AppData\Local\Android\Sdk (DEPRECATED)
Using Android SDK: C:\Users\prade\AppData\Local\Android\Sdk\build-tools\32.0.0
Subproject Path: CordovaLib
Subproject Path: app

FAILURE: Build failed with an exception.

Where:
Script 'C:\ionic\demoApp\platforms\android\CordovaLib\cordova.gradle' line: 69

What went wrong:
A problem occurred evaluating script.

No installed build tools found. Install the Android build tools version 30.0.3 or higher.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.1.1/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 1s
Command failed with exit code 1: C:\ionic\demoApp\platforms\android\gradlew :app:bundleRelease -b C:\ionic\demoApp\platforms\android\build.gradle
[ERROR] An error occurred while running subprocess cordova.

    cordova.cmd build android --release exited with exit code 1.

    Re-running this command with the --verbose flag may provide more information.


问:
cannot add to the index - missing --add option?
I'm using Github Desktop and tried pushing a new project into a React_Native repository, however when I try committing the code I'm prompted with "cannot add to the index - missing --add option?", I noticed that this problem occurs after I run "expo init client" to initiate my program. Any help is greatly appreciated.

答: I was very silly and hadn't committed the file yet. Git has to be tracking it first so the files you apply this to can't be new, must be committed first</p>


问:
Best way to accept multiple tcp clients?
I have a client/server infrastructure. At present they use a TcpClient and TcpListener to send a receive data between all the clients and server.

What I currently do is when data is received (on it's own thread), it is put in a queue for another thread to process in order to free the socket so it is ready and open to receive new data.

```<code>                // Enter the listening loop.
                while (true)
                {
                    Debug.WriteLine("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    using (client = server.AcceptTcpClient())
                    {
                        data = new List<byte>();

                        // Get a stream object for reading and writing
                        using (NetworkStream stream = client.GetStream())
                        {
                            // Loop to receive all the data sent by the client.
                            int length;

                            while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                            {
                                var copy = new byte[length];
                                Array.Copy(bytes, 0, copy, 0, length);
                                data.AddRange(copy);
                            }
                        }
                    }

                    receivedQueue.Add(data);
                }
</code>```

However I wanted to find out if there is a better way to do this. For example if there are 10 clients and they all want to send data to the server at the same time, one will get through while all the others will fail.Or if one client has a slow connection and hogs the socket all other communication will halt.

Is there not some way to be able to receive data from all clients at the same time and add the received data in the queue for processing when it has finished downloading?

答:
What I do usually is using a thread pool with several threads.
Upon each new connection I'm running the connection handling (in your case - everything you do in the using clause) in one of the threads from the pool.

By that you achieve both performance since you're allowing several simultaneously accepted connection and you also limiting the number of resources (threads, etc') you allocate for handling incoming connections.

You have a nice example here

Good Luck

Body:
I have a client/server infrastructure. At present they use a TcpClient and TcpListener to send a receive data between all the clients and server.

What I currently do is when data is received (on it's own thread), it is put in a queue for another thread to process in order to free the socket so it is ready and open to receive new data.

                // Enter the listening loop.
                while (true)
                {
                    Debug.WriteLine("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    using (client = server.AcceptTcpClient())
                    {
                        data = new List<byte>();

                        // Get a stream object for reading and writing
                        using (NetworkStream stream = client.GetStream())
                        {
                            // Loop to receive all the data sent by the client.
                            int length;

                            while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                            {
                                var copy = new byte[length];
                                Array.Copy(bytes, 0, copy, 0, length);
                                data.AddRange(copy);
                            }
                        }
                    }

                    receivedQueue.Add(data);
                }

However I wanted to find out if there is a better way to do this. For example if there are 10 clients and they all want to send data to the server at the same time, one will get through while all the others will fail.Or if one client has a slow connection and hogs the socket all other communication will halt.

Is there not some way to be able to receive data from all clients at the same time and add the received data in the queue for processing when it has finished downloading?