问:
How to remove the DataTable's Row without using loops?
I have one datatable which has

DataTable:

```<code>         SeqNo        ItemID        ItemName
        -------       ------        --------
           1            10           AAA
           2            20           BBB
           3            30           CCC
</code>```

Now I want to remove the Row which has the SeqNo "3".

Now I am doing like this in GridView RowCommand Event:

```<code>    if (e.CommandName == "Delete")
        {
            string SeqNo = e.CommandArgument.ToString();
            for (int i = 0; i < DTItem.Rows.Count; i++)
            {
                if (SeqNo == DTItem.Rows[i]["SeqNo"].ToString())
                {
                    DTItem.Rows.Remove(DTItem.Rows[i]);
                }
            }
        }
</code>```

But without loops, How to remove the row based on this condition?

答:
Try this:</p>

```<code>DataRow[] rows = DTItem.Select("SeqNo = " + SeqNo);
foreach (DataRow row in rows) {
    DTItem.Rows.Remove(row);
}
</code>```

Body:
I have one datatable which has

DataTable:

         SeqNo        ItemID        ItemName
        -------       ------        --------
           1            10           AAA
           2            20           BBB
           3            30           CCC

Now I want to remove the Row which has the SeqNo "3".

Now I am doing like this in GridView RowCommand Event:

    if (e.CommandName == "Delete")
        {
            string SeqNo = e.CommandArgument.ToString();
            for (int i = 0; i < DTItem.Rows.Count; i++)
            {
                if (SeqNo == DTItem.Rows[i]["SeqNo"].ToString())
                {
                    DTItem.Rows.Remove(DTItem.Rows[i]);
                }
            }
        }

But without loops, How to remove the row based on this condition?

Body:
Try this:

DataRow[] rows = DTItem.Select("SeqNo = " + SeqNo);
foreach (DataRow row in rows) {
    DTItem.Rows.Remove(row);
}


来源: stackexchange

问:
Multiple Virtual Machines on browser
I always wondered how the Hack the box acadamy hosts thousand computers on your browser. If you dont know what i mean this is what it looks like.

So basically you can just press "Spawn Instance" and after a few seconds a new Parrot os boots up in your browser. how did they do that?
I looked through the internet and found something called "VM Ware ESXI". Am i on the right way? Or is it something diffrent?

Im curiously waiting for an answer!
Thanks!

答: Basically,the opearting-systems seeming to run on web browser are connected by VNC on web.VM Ware ESXI is a hypervistor software of virtual machines which running on their own sever.Actually they seldom provide with high performance and heavy operating-systems will not run there(Linux target can run in minimal status e.g. 100MiB Memorywith sharing CPU) it costs little.</p>

ContentLicense: CC BY-SA 4.0

Title: Multiple Virtual Machines on browser


问:
Delete all rows in a table which a column has the same name repeated 2 or more times (but i don't know their names)
I would like to delete all the rows in a table where the names of a column are the same...

But I do not know the names of the values in column_1.

Always column_1 will be the one with repeats... column_2 will not. It's possible to do that? Thank you.

Example:

column_1
column_2

1
2

2
3

3
4

3
5

4
6

5
7

5
8

5
9

Expected:

column_1
column_2

1
2

2
3

4
6

答:
Use a subquery to help you with that:</p>
```<code>DELETE  FROM `TableName` where column_1 in
    (select column_1 FROM
        (select column_1 FROM `TableName` GROUP BY `column_1` HAVING count(column_1)>1) AS t1
    )
</code>```

Body:
Use a subquery to help you with that:

DELETE  FROM `TableName` where column_1 in
    (select column_1 FROM
        (select column_1 FROM `TableName` GROUP BY `column_1` HAVING count(column_1)>1) AS t1
    )


问:
Rails: Reset a model attribute at specific time each day
I have a rails app with a Location model, which has a rating, and a rating_count field. Now, I need to reset every Location's rating and rating_countattributes to 0 at a specific time everyday, lets say 12:00:00 UTC.

How would I accomplish this? I'm using the default sqlite3 databases.

答: If you're on a *nix box, write a script to do the updates (eg. in PHP, or Perl) and simply add it to crontab. Check out cron.</p>

ContentLicense: CC BY-SA 3.0


问:
Is there a way to preview how pages will break in Markdown?
I am writing documentation in Markdown which I will need to convert into a PDF. However, when converting to a PDF using this Visual Studio Code plugin it adds pages and occasionally the pages will break at awkward moments.

Is there a way to view how these pages will break before converting to a PDF?

答:
I don't see anything about previewing breaks in the docs, but you can manually insert page breaks:

Please use the following to insert a page break.

```<code><div class="page"/>
</code>```

Breaking before headings, for example, might be a good way to partly mitigate this issue.

Body:
I don't see anything about previewing breaks in the docs, but you can manually insert page breaks:

Please use the following to insert a page break.

<div class="page"/>

Breaking before headings, for example, might be a good way to partly mitigate this issue.


问:
Not a primitive array JsonException When i parse JsonArray
Here is the Response i am getting in this format

[{"id":15395,"firstName":"Real","lastName":"Me","phone":"(555) 455-6666","address1":"9800 Fredericksburg Road ","address2":null,"city":"San Antonio","state":"TX","zip":"78288"}]

If i parse the response as Json array i am getting JSONException.

Parsing the data as val jsonArray = JSONArray(response.body()!!)

but i am getting error as
Not a primitive array: class okhttp3.internal.http.RealResponseBody

Here is How i am calling api

```<code>val client = OkHttpClient().newBuilder()
            .build()
        val mediaType = MediaType.parse("application/json")
        val body = RequestBody.create(mediaType, setPayloadSearch(value))
        val request: Request = Request.Builder()
            .url("https://api.etruckingsoft.com/ets/api/driver/searchDrivers")
            .method("POST", body)
            .addHeader(
                "Authorization",
                "----------------"
            )
            .addHeader("Content-Type", "application/json")
            .build()
        val response = client.newCall(request).execute()
</code>```

答:
response.body() returns a ResponseBody object. Due to this you are then calling the JSONArray(Object) constructor which expects the argument to be a Java array object, and therefore fails with a JSONException.

Instead (as mentioned in the comments) you should call response.body().string() to get the actual JSON content of the response and then call the JSONArray(String) constructor which parses the JSON data.

Body:
Here is the Response i am getting in this format

[{"id":15395,"firstName":"Real","lastName":"Me","phone":"(555) 455-6666","address1":"9800 Fredericksburg Road ","address2":null,"city":"San Antonio","state":"TX","zip":"78288"}]

If i parse the response as Json array i am getting JSONException.

Parsing the data as val jsonArray = JSONArray(response.body()!!)

but i am getting error as
Not a primitive array: class okhttp3.internal.http.RealResponseBody

Here is How i am calling api

val client = OkHttpClient().newBuilder()
            .build()
        val mediaType = MediaType.parse("application/json")
        val body = RequestBody.create(mediaType, setPayloadSearch(value))
        val request: Request = Request.Builder()
            .url("https://api.etruckingsoft.com/ets/api/driver/searchDrivers")
            .method("POST", body)
            .addHeader(
                "Authorization",
                "----------------"
            )
            .addHeader("Content-Type", "application/json")
            .build()
        val response = client.newCall(request).execute()


问:
How to parse/map a JSON in C# and locate specific classes to output
I'm looking for a elaborated answer and/or explanation (with examples).

Q: The goal is to parse a JSON file with the following format (example link provided). Only the url(s) should be outputted to the console (using a array).

The expected output is

```<code>001
002
003
004
005
</code>```

JSON Example on Hastebin

I was told repeatedly the answer is....

```<code>using System.Text.Json;

var json = "{ \"entries\": [ { \"value\": \"hello\", \"anotherValue\": 0 } ]"
var thing = JsonSerializer.Deserialize<Thing>(json);
foreach (var entry in thing.Entries) {
  // do thing with entry.Value and entry.AnotherValue
}
record Thing(OtherThing[] Entries);
record OtherThing(string Value, int AnotherValue);
</code>```

But I'm clueless. Though this is a proven method that work?

My progress:

```<code>    internal class Thing
    {

        public class Download
        {
            public string sha1 { get; set; }
            public string url { get; set; }
        }

        public class Root
        {
            public string _id { get; set; }
            public string name { get; set; }
            public string description { get; set; }
            public string image { get; set; }
            public string url { get; set; }
            public List<Download> download { get; set; }
        }
</code>```
```<code>        public void LoadJson()
        {
            using (StreamReader r = new StreamReader("test2json.json"))
            {
                string json = r.ReadToEnd();
                Root file = JsonConvert.DeserializeObject<Root>(json);
                Trace.WriteLine(json);
            }
        }
</code>```

In a similar method...I was able to parse a JSON url using...

```<code>             //Parse JSON Directory.
var fileName = (@"C:\Users\Icarus\Desktop\test2json.json");
dynamic json = JsonConvert.DeserializeObject(File.ReadAllText(fileName));
string SearchFor = json["Name"]["Url"];

</code>```

But this is not a desired result.

I'm using C# and the application uses WPF.

答:
Firstly, you need to create model class which represents properties of the json object.
For example based on your json file, you can create the following class:

```<code>public class RootItem // or whatever name of the root object
{
    [JsonPropertyName("_id")]
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Image { get; set; }

    [JsonPropertyName("download")]
    public IEnumerable<Download> Downloads { get; set; }
}

public class Download
{
    public string Sha1 { get; set; }
    public string Url { get; set; }
}
</code>```

Secondly, you need to deserialize object (extracting data from a json file). You can use built-in json serializer from System.Text.Json, or you can use Newtonsoft.Json if you are using old frameworks.

In the following example I used default System.Text.Json serializer:

```<code>var jsonData = File.ReadAllText("here path of the json file");
var serializerOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var rootObj = JsonSerializer.Deserialize<RootItem>(jsonData, serializerOptions);
</code>```

Then get whatever data from deserialized object (in our case it's rootObj)
If you want to print all urls then you can do something like:

```<code>foreach(var download in rootObj.Downloads)
{
    Console.WriteLine(download.Url)
}
</code>```

Body:
I'm looking for a elaborated answer and/or explanation (with examples).

Q: The goal is to parse a JSON file with the following format (example link provided). Only the url(s) should be outputted to the console (using a array).

The expected output is

001
002
003
004
005

JSON Example on Hastebin

I was told repeatedly the answer is....

using System.Text.Json;

var json = "{ \"entries\": [ { \"value\": \"hello\", \"anotherValue\": 0 } ]"
var thing = JsonSerializer.Deserialize<Thing>(json);
foreach (var entry in thing.Entries) {
  // do thing with entry.Value and entry.AnotherValue
}
record Thing(OtherThing[] Entries);
record OtherThing(string Value, int AnotherValue);

But I'm clueless. Though this is a proven method that work?

My progress:

    internal class Thing
    {

        public class Download
        {
            public string sha1 { get; set; }
            public string url { get; set; }
        }

        public class Root
        {
            public string _id { get; set; }
            public string name { get; set; }
            public string description { get; set; }
            public string image { get; set; }
            public string url { get; set; }
            public List<Download> download { get; set; }
        }

        public void LoadJson()
        {
            using (StreamReader r = new StreamReader("test2json.json"))
            {
                string json = r.ReadToEnd();
                Root file = JsonConvert.DeserializeObject<Root>(json);
                Trace.WriteLine(json);
            }
        }

In a similar method...I was able to parse a JSON url using...

             //Parse JSON Directory.
var fileName = (@"C:\Users\Icarus\Desktop\test2json.json");
dynamic json = JsonConvert.DeserializeObject(File.ReadAllText(fileName));
string SearchFor = json["Name"]["Url"];

But this is not a desired result.

I'm using C# and the application uses WPF.

Body:
Firstly, you need to create model class which represents properties of the json object.
For example based on your json file, you can create the following class:

public class RootItem // or whatever name of the root object
{
    [JsonPropertyName("_id")]
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Image { get; set; }

    [JsonPropertyName("download")]
    public IEnumerable<Download> Downloads { get; set; }
}

public class Download
{
    public string Sha1 { get; set; }
    public string Url { get; set; }
}

Secondly, you need to deserialize object (extracting data from a json file). You can use built-in json serializer from System.Text.Json, or you can use Newtonsoft.Json if you are using old frameworks.

In the following example I used default System.Text.Json serializer:

var jsonData = File.ReadAllText("here path of the json file");
var serializerOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var rootObj = JsonSerializer.Deserialize<RootItem>(jsonData, serializerOptions);

Then get whatever data from deserialized object (in our case it's rootObj)
If you want to print all urls then you can do something like:

foreach(var download in rootObj.Downloads)
{
    Console.WriteLine(download.Url)
}


问:
Image segmentation - Split and Merge (Quadtrees)
Is there an implementation for the split and merge method of image segmentation?
any advice would be much appreciated.</p>

答:
What segmentation is about?

Segmentation means division of your image into several connected regions. Basically, you could do segmentation with two definitions of region: you could define a region as a group of connected similar pixels, or a set of connected pixels surrounded by discontinuities (edges). Split and merge uses the first approach.

Mathematically speaking: if your whole image is represented by the set of pixels (called R), than you would like to get subsets such as

Segmentation is complete, so all subregions sum up to the whole R. Union of all regions is R1 U R2 U ... U Rn = R.

Ri is connected.

Regions are distinct. Ri∩Rj=∅ given that i≠j

Regions have similar properties. This could be expressed by a function called the homogenity criterion (P). It should give TRUE for the members of the given region, and FALSE for all the other regions.

Neighbor regions cannot been merged. For all regions P(Ri U Rj)=FALSE given that i≠j.

What split and merge algorithm is about?

So first, we have to choose a homogenity criterion. A homogenity criterion could be global (depending on the whole region) or local (depending on a small window of the region, and if it's true for all windows, than it's true for the region). A simple example could be the deviation from average should be smaller than a threshold. ∀pi∈Ri: |pi-μ|≤f*σ.

The split and merge algorithm have two phases: the split, and the merge phase.
In the split phase we recursively split regions into four subregions (starting with the whole image as one region) until our homogenity criterion is met in all subregions. It's easy to see that the 1-4 conditions of segmentation are met. We proceed to merge step in order to satisfy the 5th condition.

In the merge step we check that P(Ri U Rj)=TRUE for each two neighbor regions, and merge the two regions. We repeat this step until no more changes are necessary. Now we met all the conditions, we had our image segmented into subregions.

Pseudocode

Here is a pseudocode to split and merge algorithm:

Init: we have only one big region (the whole image).

Split: If P(Ri)=TRUE proceed to next step. Otherwise subdivide Ri to four subregions and perform step 2 on them.

Merge: If Ri and Rj are neighbors and P(Ri U Rj) = TRUE, merge the two regions, than repeat step 3. If there are no such regions we are finished.


问:
Returning the full object in response body using NET Core controller
What is the best way to return all details of complex objects in the body of a HTTP response?

I made some simple test classes:

```<code>public class Parent { }

public class Child : Parent
{
    public Child(string _name) { name = _name; }
    public string name { get; }
}
</code>```

I want to return a list as a response, which contains full detail about all the objects in it. My controller looks like this:

```<code>[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpGet]
    public List<Parent> Index()
    {
        Parent o1 = new Child("Alice");
        Parent o2 = new Child("Bob");
        return new List<Parent>() { o1, o2 };
    }
}
</code>```

This leads to an output of [{},{}]

If I replace the definitions to work with the List<Child> return type, it is able to recognise the details as
[{"name":"Alice"},{"name":"Bob"}], however I may have different child types in the list, so this would not work.

What function does NET Core use to convert the object into the JSON response body? Is the best way to tackle this problem to convert it to JSON myself and output the resulting string?

答:
You can try to use Object:

```<code>[HttpGet]
    public List<Object> Index()
    {
        Object o1 = new Child("Alice");
        Object o2 = new Child("Bob");
        return new List<Object>() { o1, o2 };
    }
</code>```

result:

Body:
What is the best way to return all details of complex objects in the body of a HTTP response?

I made some simple test classes:

public class Parent { }

public class Child : Parent
{
    public Child(string _name) { name = _name; }
    public string name { get; }
}

I want to return a list as a response, which contains full detail about all the objects in it. My controller looks like this:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpGet]
    public List<Parent> Index()
    {
        Parent o1 = new Child("Alice");
        Parent o2 = new Child("Bob");
        return new List<Parent>() { o1, o2 };
    }
}

This leads to an output of [{},{}]

If I replace the definitions to work with the List<Child> return type, it is able to recognise the details as
[{"name":"Alice"},{"name":"Bob"}], however I may have different child types in the list, so this would not work.

What function does NET Core use to convert the object into the JSON response body? Is the best way to tackle this problem to convert it to JSON myself and output the resulting string?

Body:
You can try to use Object:

[HttpGet]
    public List<Object> Index()
    {
        Object o1 = new Child("Alice");
        Object o2 = new Child("Bob");
        return new List<Object>() { o1, o2 };
    }

result:


问:
How to use ELK with SCDF stream applications?
In our company, we use ELK stack for logging through Spring Cloud Config and logback.

I would like to use ELK with SCDF too.

For our own applications, we can add the logstash-logback-encoder dependency to make it work.

But with standard stream applications which do not include this dependency, I have an exception because LogstashTcpSocketAppender is not defined ?

Is there a way to use ELK with stream applications like time-source or log-sink in ticktock stream for example ?

答:
The generated apps are currently packaged into a Spring Boot executable jar using the default JarLauncher. They would instead need to use the PropertiesLauncher in order to support adding external dependencies like this. That being said, we are interested and exploring adding this ability to the generated apps. More details can be found here.

For now, Soby's suggestion is the recommended approach.


问:
How can I find the sum of a string's indices in Python?
I am working on creating a program that has a function that takes in a string and prints the number of capital letters and also the sum of their indices.
like:
"hEllo, World"
2
8

I have figured out the capital letters but I am having trouble with the indices.

Here is what I have:

```<code>import sys

def Count(str):

str = sys.argv[1]

upper, lower, number, special = 0,0,0,0

for i in range(len(str)):
    if str[i].isupper():
        upper += 1
    elif str[i].islower():
        lower += 1
    elif str[i].isdigit():
        number +=1
    else:
        special += 1

print(upper)
print(lower)

Count(str)
</code>```

答:
You can do this by first making a list of the upper-case character positions then getting the length and sum of that list, like this

def count_upper(inp_str):
    # Get a list of the indices of the upper-case characters,
    # enumerate returns a list of index,character pairs, then you
    # keep only the indices with an upper case character
    uppers = [i for i,s in enumerate(inp_str) if s.isupper()]

    # number of upper-case chars is the length of the list of indices
    num_uppers = len(uppers)

    # index sum is straightforward
    sum_indices = sum(uppers)

    return num_uppers, sum_indices

print(count_upper("hEllo, World"))
```
<p>which returns</p>
<pre class="lang-py prettyprint-override"><code>(2, 8)
</code>```

If you want to print it on two lines, just get the tuple values and print them individually, like this:

c,s = count_upper("hEllo, World")
print(c)
print(s)
```
<p>or if you want to format it, you can use something like this</p>
<pre class="lang-py prettyprint-override"><code>print("%d and %d" % (c,s))
print(f"{c} and {s}") # with python 3 f-strings
</code>```

Body:
I am working on creating a program that has a function that takes in a string and prints the number of capital letters and also the sum of their indices.
like:
"hEllo, World"
2
8

I have figured out the capital letters but I am having trouble with the indices.

Here is what I have:

import sys

def Count(str):

str = sys.argv[1]

upper, lower, number, special = 0,0,0,0

for i in range(len(str)):
    if str[i].isupper():
        upper += 1
    elif str[i].islower():
        lower += 1
    elif str[i].isdigit():
        number +=1
    else:
        special += 1

print(upper)
print(lower)

Count(str)

Body:
You can do this by first making a list of the upper-case character positions then getting the length and sum of that list, like this

def count_upper(inp_str):
    # Get a list of the indices of the upper-case characters,
    # enumerate returns a list of index,character pairs, then you
    # keep only the indices with an upper case character
    uppers = [i for i,s in enumerate(inp_str) if s.isupper()]

    # number of upper-case chars is the length of the list of indices
    num_uppers = len(uppers)

    # index sum is straightforward
    sum_indices = sum(uppers)

    return num_uppers, sum_indices

print(count_upper("hEllo, World"))

which returns

(2, 8)

If you want to print it on two lines, just get the tuple values and print them individually, like this:

c,s = count_upper("hEllo, World")
print(c)
print(s)

or if you want to format it, you can use something like this

print("%d and %d" % (c,s))
print(f"{c} and {s}") # with python 3 f-strings


问:
How do i pass data to a function under data in vuejs
I tried to reference this.items in the function in taskList.cls.cls

the main idea is to run a task in vue-terminal then pass the result of the post request to this.items but it's returning undefined

```<code>  data() {
    return {
//this is the data i want to pass the post response to
      items: [],
      query: '',
      taskList: {
        // your tasks
        cls: {
          description: 'Clear Terminal',
          cls: this, async(pushToList) {
            const p = new Promise(resolve => {
              this.query = 'SELECT * FROM notifications'
              const token = localStorage.getItem('token')
              axios.post('/query', {'query': this.query}, {
                'headers': {
                  'Content-Type': 'application/json',
                  'Authorization': 'Bearer ' + token
                }
              }).then(res => {
                //i want to reference
                **this.items = res.data.data.result**
                //
                pushToList({type: 'system', label: 'Running query', message: 'Please wait!!'})

              }).catch(err => {
                console.log(err)
              })
              setTimeout(() => {
                resolve({type: 'success', label: 'Success', message: 'Success!'})
                this.test = "worked"

              }, 2000)
            })
            return p
          }
        }
      },
      commandList: {
        // your commands

      }
    }
  },
</code>```

答: Don't do that, call api on "mount()".

Body:
I tried to reference this.items in the function in taskList.cls.cls

the main idea is to run a task in vue-terminal then pass the result of the post request to this.items but it's returning undefined

  data() {
    return {
//this is the data i want to pass the post response to
      items: [],
      query: '',
      taskList: {
        // your tasks
        cls: {
          description: 'Clear Terminal',
          cls: this, async(pushToList) {
            const p = new Promise(resolve => {
              this.query = 'SELECT * FROM notifications'
              const token = localStorage.getItem('token')
              axios.post('/query', {'query': this.query}, {
                'headers': {
                  'Content-Type': 'application/json',
                  'Authorization': 'Bearer ' + token
                }
              }).then(res => {
                //i want to reference
                **this.items = res.data.data.result**
                //
                pushToList({type: 'system', label: 'Running query', message: 'Please wait!!'})

              }).catch(err => {
                console.log(err)
              })
              setTimeout(() => {
                resolve({type: 'success', label: 'Success', message: 'Success!'})
                this.test = "worked"

              }, 2000)
            })
            return p
          }
        }
      },
      commandList: {
        // your commands

      }
    }
  },

Body: Don't do that, call api on "mount()".


问:
OSStatus error 1718449215
I have created an iPhone application to record our voice. When I try to record, I am getting error message in following statement.

```<code>
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
</code>```

Error Domain=NSOSStatusErrorDomain Code=1718449215 "Operation could not be completed. (OSStatus error 1718449215.)"

If I tried to record in .caf file, it is working fine. If I tried with .m4a, I am getting this error message.

Please help me to resolve it.

Thanks.

答:
If you're in c or cpp code you can do this.</p>

```<code>char code[4];
*((SInt32*)&code[0]) = error;
</code>```

ContentLicense: CC BY-SA 2.5

Title: OSStatus error 1718449215

Body:
I have created an iPhone application to record our voice. When I try to record, I am getting error message in following statement.

recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];

Error Domain=NSOSStatusErrorDomain Code=1718449215 "Operation could not be completed. (OSStatus error 1718449215.)"

If I tried to record in .caf file, it is working fine. If I tried with .m4a, I am getting this error message.

Please help me to resolve it.

Thanks.

Body:
If you're in c or cpp code you can do this.

char code[4];
*((SInt32*)&code[0]) = error;


问:
How do I deal with 'package ‘mudata’ is not available for this version of R'
I tried to install the mudata package in the RStudio Cloud using:

```<code>install.packages("mudata")
library(mudata)
</code>```

I get the following output:

```<code>Warning in install.packages :
  package ‘mudata’ is not available for this version of R

A version of this package for your version of R might be available elsewhere,
see the ideas at
https://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages
</code>```

I followed the link but found nothing about the mudata package.
Does anyone have any ideas how to go about that?

Thanks

答:
Solved.
The package 'mudata' is now 'mudata2'.</p>

Body:
I tried to install the mudata package in the RStudio Cloud using:

install.packages("mudata")
library(mudata)

I get the following output:

Warning in install.packages :
  package ‘mudata’ is not available for this version of R

A version of this package for your version of R might be available elsewhere,
see the ideas at
https://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages

I followed the link but found nothing about the mudata package.
Does anyone have any ideas how to go about that?

Thanks


问:
Need help updating time element with output from jq?
Current object with proposed format

```<code>[
  {
    "time": "2022-01-28T17:50:31.620Z"
  }
]
</code>```

Command executed to convert from iso8601 to unix

jq '.[].time | sub("\.[0-9]+Z$"; "Z") | fromdate' time_test.json

Output
1643392231

I've tried varying combinations but how to do I update the time value in the object. I can get the conversion to work but can't seem to update the value with the output.

Expected Result -

```<code>[
  {
    "time": "1643392231"
  }
]
</code>```

答:
You mapped all the values in the array but you're not actually modifying or recreating the array.

To modify, use an assignment: (you were almost there)

```<code>.[].time |= (sub("\\.\\d+Z$"; "Z") | fromdate)
</code>```

To recreate, map it.

```<code>map(.time |= (sub("\\.\\d+Z$"; "Z") | fromdate))
</code>```

Body:
Current object with proposed format

[
  {
    "time": "2022-01-28T17:50:31.620Z"
  }
]

Command executed to convert from iso8601 to unix

jq '.[].time | sub("\.[0-9]+Z$"; "Z") | fromdate' time_test.json

Output
1643392231

I've tried varying combinations but how to do I update the time value in the object. I can get the conversion to work but can't seem to update the value with the output.

Expected Result -

[
  {
    "time": "1643392231"
  }
]

Body:
You mapped all the values in the array but you're not actually modifying or recreating the array.

To modify, use an assignment: (you were almost there)

.[].time |= (sub("\\.\\d+Z$"; "Z") | fromdate)

To recreate, map it.

map(.time |= (sub("\\.\\d+Z$"; "Z") | fromdate))


问:
How to add background image to JTextField?
I know how to add background image to JPanel (creating ImagePanel class that extends JPanel and overload it's paintComponent() method), BUT this trick with JTextField not working properly: Displays image, but not text.
So, how to add background image to JTextField properly?</p>

答:
Create a new Class and extend to JComponet
Below is a newly created component that styles an textfield. of course with the background image attached. Save attached image as input_field.png and save it in your project root.

```<code>public class InputField extends JComponent
{

    JTextField textField = new JTextField();

    Color componentColor = Color.decode("#FF9933");
    Font componentFont = new Font(Font.MONOSPACED, Font.PLAIN, 14);

    InputField()
    {
        this.setOpaque(false);
        this.setBackground(Color.decode("#4D4D4D"));

        textField.setBounds(8, 2, 550, 27);
        textField.setCaretColor(Color.WHITE);
        textField.setOpaque(false);
        textField.setFont(componentFont);
        textField.setForeground(componentColor);
        textField.setBackground(Color.WHITE);
        textField.setBorder(BorderFactory.createEmptyBorder());

        this.add(textField);
    }

    @Override
    protected void paintComponent(Graphics g)
    {
               g.drawImage(Toolkit.getDefaultToolkit().getImage("input_field.png"), 0, -1, this);
    }
}
</code>```

input_field.png [Save this]

HERES HOW IT LOOKS LIKE. THE BORDER IS A LIGHT COLOR SO IT MAY NOT BE VERY VISIBLE UNLESS PUT ON A DARK BACKGROUND.

Body:
Create a new Class and extend to JComponet
Below is a newly created component that styles an textfield. of course with the background image attached. Save attached image as input_field.png and save it in your project root.

public class InputField extends JComponent
{

    JTextField textField = new JTextField();

    Color componentColor = Color.decode("#FF9933");
    Font componentFont = new Font(Font.MONOSPACED, Font.PLAIN, 14);

    InputField()
    {
        this.setOpaque(false);
        this.setBackground(Color.decode("#4D4D4D"));

        textField.setBounds(8, 2, 550, 27);
        textField.setCaretColor(Color.WHITE);
        textField.setOpaque(false);
        textField.setFont(componentFont);
        textField.setForeground(componentColor);
        textField.setBackground(Color.WHITE);
        textField.setBorder(BorderFactory.createEmptyBorder());

        this.add(textField);
    }

    @Override
    protected void paintComponent(Graphics g)
    {
               g.drawImage(Toolkit.getDefaultToolkit().getImage("input_field.png"), 0, -1, this);
    }
}

input_field.png [Save this]

HERES HOW IT LOOKS LIKE. THE BORDER IS A LIGHT COLOR SO IT MAY NOT BE VERY VISIBLE UNLESS PUT ON A DARK BACKGROUND.


问:
How to point to localhost:8000 with the Dart http package in Flutter?
I'm following the Flutter Networking/HTTP tutorial to do a GET request to a server running on my localhost:8000. Visiting my localhost via my browser works fine. My code looks like this:

```<code>var url = 'http://localhost:8000';
Future<String> getUnits(String category) async {
    var response = await httpClient.get('$url/$category');
    return response.body;
}
</code>```

This works fine when I point to any real URL, such as https://example.com, but when I point to https://localhost:8000 or https://localhost (or any variations of these), I get an error starting with:

```<code>E/flutter ( 4879): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter ( 4879): SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 47060
E/flutter ( 4879): #0      IOClient.send (package:http/src/io_client.dart:30:23)
</code>```

The port in the error above changes each time I reload the app. I looked in the http package code and it doesn't seem like there is a way to specify the port for the URL. How do I point to my localhost?

答:
If your backend is on LARAVEL, make sure to serve the domain to your IP address and port before using it on your flutter application

To serve do this

php artisan serve --host=192.168.1.100 --port=8000

That should solve the problem.

Body:
I'm following the Flutter Networking/HTTP tutorial to do a GET request to a server running on my localhost:8000. Visiting my localhost via my browser works fine. My code looks like this:

var url = 'http://localhost:8000';
Future<String> getUnits(String category) async {
    var response = await httpClient.get('$url/$category');
    return response.body;
}

This works fine when I point to any real URL, such as https://example.com, but when I point to https://localhost:8000 or https://localhost (or any variations of these), I get an error starting with:

E/flutter ( 4879): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter ( 4879): SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 47060
E/flutter ( 4879): #0      IOClient.send (package:http/src/io_client.dart:30:23)

The port in the error above changes each time I reload the app. I looked in the http package code and it doesn't seem like there is a way to specify the port for the URL. How do I point to my localhost?


问:
Dates returned as columns in SQL Select
My user will submit a FromDate and a ToDate. What I want to happen is to select the dates that fall in between these dates, which I have accomplished with the script below. The dates will by dynamic.

```<code>DECLARE @fromDateParam DATETIME = '2022-01-24 00:00:00.000'
DECLARE @toDateParam DATETIME = '2022-01-29 00:00:00.000'

;WITH fnDateNow(DayOfDate) AS
(
    SELECT @fromDateParam AS TransactionDate

    UNION ALL

    SELECT DayOfDate + 1
    FROM fnDateNow
    WHERE DayOfDate < @toDateParam
)
SELECT fnDateNow.DayOfDate AS TransactionDate
FROM fnDateNow
</code>```

This returns that dates as rows. What I am looking for is a way to make these dates return as the columns for a different script.

This table is called DailyTransactionHeader and it has a column [TransactionDate] and another one called [Amount].

There is the probability that their is not a DailyTransactionHeader with the specified Date for this I am looking to return 0.

So I am trying to have the data look like this (I formatted the date) There would be more than one row, but I just wanted to show an example of what I am trying to accomplish.

I appreciate any help,

Thanks

答:
You can do it using dynamic sql. For example:

```<code>CREATE PROCEDURE [GET_DATE_TABLE]
(
    @FROMDATE DATETIME,
    @TODATE DATETIME
)
AS
DECLARE @PDATE DATETIME
DECLARE @SQL VARCHAR(MAX)
DECLARE @SEP VARCHAR(10)

    SET @PDATE = @FROMDATE
    SET @SQL = 'SELECT '
    SET @SEP = ''

    WHILE @PDATE < @TODATE
    BEGIN
        SET @SQL = @SQL + @SEP + 'NULL as [' + CONVERT(VARCHAR, CONVERT(DATE, @PDATE)) + ']'

        SET @PDATE = @PDATE + 1
        SET @SEP = ', '
    END;

    EXEC(@SQL)
</code>```

Test Example:

```<code>DECLARE @fromDateParam DATETIME = '2022-01-24 00:00:00.000'
DECLARE @toDateParam DATETIME = '2022-01-29 00:00:00.000'
exec dbo.GET_DATE_TABLE @fromDateParam, @toDateParam
</code>```

Title: Dates returned as columns in SQL Select

Body:
My user will submit a FromDate and a ToDate. What I want to happen is to select the dates that fall in between these dates, which I have accomplished with the script below. The dates will by dynamic.

DECLARE @fromDateParam DATETIME = '2022-01-24 00:00:00.000'
DECLARE @toDateParam DATETIME = '2022-01-29 00:00:00.000'

;WITH fnDateNow(DayOfDate) AS
(
    SELECT @fromDateParam AS TransactionDate

    UNION ALL

    SELECT DayOfDate + 1
    FROM fnDateNow
    WHERE DayOfDate < @toDateParam
)
SELECT fnDateNow.DayOfDate AS TransactionDate
FROM fnDateNow

This returns that dates as rows. What I am looking for is a way to make these dates return as the columns for a different script.

This table is called DailyTransactionHeader and it has a column [TransactionDate] and another one called [Amount].

There is the probability that their is not a DailyTransactionHeader with the specified Date for this I am looking to return 0.

So I am trying to have the data look like this (I formatted the date) There would be more than one row, but I just wanted to show an example of what I am trying to accomplish.

I appreciate any help,

Thanks

Body:
You can do it using dynamic sql. For example:

CREATE PROCEDURE [GET_DATE_TABLE]
(
    @FROMDATE DATETIME,
    @TODATE DATETIME
)
AS
DECLARE @PDATE DATETIME
DECLARE @SQL VARCHAR(MAX)
DECLARE @SEP VARCHAR(10)

    SET @PDATE = @FROMDATE
    SET @SQL = 'SELECT '
    SET @SEP = ''

    WHILE @PDATE < @TODATE
    BEGIN
        SET @SQL = @SQL + @SEP + 'NULL as [' + CONVERT(VARCHAR, CONVERT(DATE, @PDATE)) + ']'

        SET @PDATE = @PDATE + 1
        SET @SEP = ', '
    END;

    EXEC(@SQL)

Test Example:

DECLARE @fromDateParam DATETIME = '2022-01-24 00:00:00.000'
DECLARE @toDateParam DATETIME = '2022-01-29 00:00:00.000'
exec dbo.GET_DATE_TABLE @fromDateParam, @toDateParam


问:
How do I clear a c variable after use to use it again?
If I send a message over serial the first time it receves the right code it works but after that it stops working.

```<code>    const unsigned int MAX_MESSAGE_LENGTH = 32;
    const char EMPTY[1] = {'\0'};

    void setup() {
      Serial.begin(9600);//bPS
    }

    String readserial(){
      char message[MAX_MESSAGE_LENGTH];
      static unsigned int message_pos = 0;
      while (Serial.available() > 0 ){

        char inbyte = Serial.read();
        if(inbyte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1)){
          message[message_pos] = inbyte;
          message_pos += 1;
        } else {
          message[message_pos] = '\0';
          //Serial.println(message);
          return message;
        }
      }
      return EMPTY;
    }

    void loop() {
      static String message;
      message = readserial();

      if(message == "Hi"){
        Serial.println("Hello");
      }else{
        //Serial.println(message);
      }
    }
</code>```

the output shows hello only if I say Hi first if I put anything else it just doesn't work.
I have tried looking for an answer elsewhere but I am stuck.

答:
I assume you want to start a new string upon encountering a newline character. That being the case you just need to reset message_pos back to 0 in the else.

```<code>if(inbyte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1)){
    message[message_pos] = inbyte;
    message_pos += 1;
} else {
    message[message_pos] = '\0';
    message_pos = 0;  // <<---- THIS LINE ADDED
    return message;
}
</code>```

Body:
If I send a message over serial the first time it receves the right code it works but after that it stops working.

    const unsigned int MAX_MESSAGE_LENGTH = 32;
    const char EMPTY[1] = {'\0'};

    void setup() {
      Serial.begin(9600);//bPS
    }

    String readserial(){
      char message[MAX_MESSAGE_LENGTH];
      static unsigned int message_pos = 0;
      while (Serial.available() > 0 ){

        char inbyte = Serial.read();
        if(inbyte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1)){
          message[message_pos] = inbyte;
          message_pos += 1;
        } else {
          message[message_pos] = '\0';
          //Serial.println(message);
          return message;
        }
      }
      return EMPTY;
    }

    void loop() {
      static String message;
      message = readserial();

      if(message == "Hi"){
        Serial.println("Hello");
      }else{
        //Serial.println(message);
      }
    }

the output shows hello only if I say Hi first if I put anything else it just doesn't work.
I have tried looking for an answer elsewhere but I am stuck.

Body:
I assume you want to start a new string upon encountering a newline character. That being the case you just need to reset message_pos back to 0 in the else.

if(inbyte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1)){
    message[message_pos] = inbyte;
    message_pos += 1;
} else {
    message[message_pos] = '\0';
    message_pos = 0;  // <<---- THIS LINE ADDED
    return message;
}


问:
Testing whether a large list of alpha characters is contained in a string (without using RegEx)
Without using RegEx, I'd like to be able to test whether a given string contains certain lowercase characters (e.g. 22 of the 26 lower-case characters in the alphabet).

For example:

```<code>my_str = 'foobar'
if 'c' in str or 'd' in my_str or 'e' in my_str:   # I don't want to enumerate the entire alphabet
    print('fails the test')
else:
    print('passes the test')
</code>```

This approach works, but I would have to enumerate most of the lowercase alphabet.  This is a hacky approach!

Is there another way to do this?  (yes, I know that RegEx would be a good choice, but not for my use case)

Thanks!

答:
Just make a set and perform a set &:

```<code>>>> set('foobar') & set('cde')
set()
</code>```

An empty set is equivalent to all your or's

And it will work with 22 characters.

So your if could be written as:

```<code>t = ('foobar','coobar')
for s in t:
    if set(s) & set('cde'):
        print(f'"{s}" fails the test')
    else:
        print(f'"{s}" passes the test')
</code>```

Prints:

```<code>"foobar" passes the test
"coobar" fails the test
</code>```

Body:
Without using RegEx, I'd like to be able to test whether a given string contains certain lowercase characters (e.g. 22 of the 26 lower-case characters in the alphabet).

For example:

my_str = 'foobar'
if 'c' in str or 'd' in my_str or 'e' in my_str:   # I don't want to enumerate the entire alphabet
    print('fails the test')
else:
    print('passes the test')

This approach works, but I would have to enumerate most of the lowercase alphabet.  This is a hacky approach!

Is there another way to do this?  (yes, I know that RegEx would be a good choice, but not for my use case)

Thanks!

Body:
Just make a set and perform a set &:

>>> set('foobar') & set('cde')
set()

An empty set is equivalent to all your or's

And it will work with 22 characters.

So your if could be written as:

t = ('foobar','coobar')
for s in t:
    if set(s) & set('cde'):
        print(f'"{s}" fails the test')
    else:
        print(f'"{s}" passes the test')

Prints:

"foobar" passes the test
"coobar" fails the test


问:
SQL Query to get the count of events in the last 30days per user based on the max date
I have an event table that looks like this.

```<code>
| id | event_id| date       |
|----|---------|------------|
| 1  | d-paiin | 28/01/2022 |
| 1  | 123gin  | 02/01/2022 |
| 1  | dhsdel  | 01/01/2022 |
| 1  | sigshwy | 31/12/2021 |
| 1  | dsiwuef | 31/12/2021 |
| 2  | shau346 | 10/02/2022 |
| 2  | akdnjsfm| 04/02/2022 |
| 2  | asjufbe | 04/02/2022 |
| 2  | jladiurn| 01/02/2022 |

</code>```

I want to write a query that finds  id and  their number of events in the last 30days using the MAX Date of each user as a reference point. i.e count of event per id where date > (MAX(Date) of each user) - 30 days.

Expected result looks like this:

```<code>
| id | count_event|
| 1  | 5          |
| 2  | 4          |

</code>```

Thanks.

答:
The first select searches for a max date for each user.

The second select filter records in the range of 30 days by previously obtained values.

```<code>with f as (
 select
  "id", max("date") as md
 from mytable
 group by "id"
)
select e.id, count(e.id)
from mytable as e left join f on e.id = f.id
where e.date > f.md - 30
group by e.id
order by 1
;
</code>```

Output:

id
count

1
5

2
4

DDL:

I added older values to show that the query really only takes 30 days.

```<code>CREATE TABLE mytable
    ("id" varchar(4), "event_id" varchar(9), "date" date)
;

INSERT INTO mytable
    ("id", "event_id", "date")
VALUES
    ('1', 'd-iin', to_date('28/01/2020','dd/mm/yyyy')),
    ('1', 'd-paiin', to_date('28/01/2022','dd/mm/yyyy')),
    ('1', '123gin', to_date('02/01/2022','dd/mm/yyyy')),
    ('1', 'dhsdel', to_date('01/01/2022','dd/mm/yyyy')),
    ('1', 'sigshwy', to_date('31/12/2021','dd/mm/yyyy')),
    ('1', 'dsiwuef', to_date('31/12/2021','dd/mm/yyyy')),
    ('2', 'shau3', to_date('5/01/2022','dd/mm/yyyy')),
    ('2', 'shau346', to_date('10/02/2022','dd/mm/yyyy')),
    ('2', 'akdnjsfm', to_date('04/02/2022','dd/mm/yyyy')),
    ('2', 'asjufbe', to_date('04/02/2022','dd/mm/yyyy')),
    ('2', 'jladiurn', to_date('01/02/2022','dd/mm/yyyy'))
;
</code>```

Body:
I have an event table that looks like this.

| id | event_id| date       |
|----|---------|------------|
| 1  | d-paiin | 28/01/2022 |
| 1  | 123gin  | 02/01/2022 |
| 1  | dhsdel  | 01/01/2022 |
| 1  | sigshwy | 31/12/2021 |
| 1  | dsiwuef | 31/12/2021 |
| 2  | shau346 | 10/02/2022 |
| 2  | akdnjsfm| 04/02/2022 |
| 2  | asjufbe | 04/02/2022 |
| 2  | jladiurn| 01/02/2022 |

I want to write a query that finds  id and  their number of events in the last 30days using the MAX Date of each user as a reference point. i.e count of event per id where date > (MAX(Date) of each user) - 30 days.

Expected result looks like this:

| id | count_event|
| 1  | 5          |
| 2  | 4          |

Thanks.

Body:
The first select searches for a max date for each user.

The second select filter records in the range of 30 days by previously obtained values.

with f as (
 select
  "id", max("date") as md
 from mytable
 group by "id"
)
select e.id, count(e.id)
from mytable as e left join f on e.id = f.id
where e.date > f.md - 30
group by e.id
order by 1
;

Output:

id
count

1
5

2
4

DDL:

I added older values to show that the query really only takes 30 days.

CREATE TABLE mytable
    ("id" varchar(4), "event_id" varchar(9), "date" date)
;

INSERT INTO mytable
    ("id", "event_id", "date")
VALUES
    ('1', 'd-iin', to_date('28/01/2020','dd/mm/yyyy')),
    ('1', 'd-paiin', to_date('28/01/2022','dd/mm/yyyy')),
    ('1', '123gin', to_date('02/01/2022','dd/mm/yyyy')),
    ('1', 'dhsdel', to_date('01/01/2022','dd/mm/yyyy')),
    ('1', 'sigshwy', to_date('31/12/2021','dd/mm/yyyy')),
    ('1', 'dsiwuef', to_date('31/12/2021','dd/mm/yyyy')),
    ('2', 'shau3', to_date('5/01/2022','dd/mm/yyyy')),
    ('2', 'shau346', to_date('10/02/2022','dd/mm/yyyy')),
    ('2', 'akdnjsfm', to_date('04/02/2022','dd/mm/yyyy')),
    ('2', 'asjufbe', to_date('04/02/2022','dd/mm/yyyy')),
    ('2', 'jladiurn', to_date('01/02/2022','dd/mm/yyyy'))
;


问:
How to change the location of .pdb files for static libraries?
Now I found out I can change the .pdb file location for C++ executable projects in Linking -> Debugger in the project settings.

How can I change the location for static library projects? As they do not have the Linker menu.

I tried changing C/C++ -> Output files -> Program Database File Name, but without luck. They are still added to the same directory as the compiled executable.

答: After changing the Program Database File Name,  pdb will be added to the specified directory. In addition, if the lib file directories are not changed,  another pdb file will also be added aside the lib. This may be why you think it was unsuccessful, but in fact it has been done.


问:
How to Populate CollectionView with Sql Query with combination of Distinct, Sum and Count .... in Xamarin
SQL QUERY SAMPLE

```<code>using (SQLiteConnection conn = new SQLiteConnection(con.dBasePath))
                {
                    SalesRecords.ItemsSource = conn.Query<DATA_BINDING.PURCHASED_PRODUCTS>
                    ("SELECT DISTINCT([soldProduct]), (SUM ([soldAmount])) FROM
                    [PURCHASED_PRODUCTS] " +
                    "WHERE salesDate BETWEEN '" + btnDateFrom.Date.ToString("dd MMM yy")
                    + "' AND '" + btnDateTo.Date.ToString("dd MMM yy") + "'");

                }]
</code>```

.....XAMARIN CODE.....

```<code>     <Label **Text="{Binding soldProduct}"** HorizontalOptions="Start" Margin="8,0,0,0" FontSize="14" FontAttributes="Bold" TextColor="White"></Label>

<Label **Text="{Binding soldAmount}"** TextColor="#2ABD8F" HorizontalOptions="CenterAndExpand" FontSize="22" HorizontalTextAlignment="Center"  FontAttributes="Bold" VerticalOptions="CenterAndExpand"
                                                           LineBreakMode="TailTruncation" Margin="0,-11,0,0"></Label>
</code>```

Please how can i make this possible, with the distinct and sum at same time

答:
Use GROUP BY instead of DISTINCT.

DISTINCT is used to select distinct elements , nothing more . If you want to aggregate(SUM) the items you need to use GROUP BY.

```<code>"SELECT soldProduct, (SUM ([soldAmount])) FROM [PURCHASED_PRODUCTS] " +
 "WHERE salesDate BETWEEN '" + btnDateFrom.Date.ToString("dd MMM yy")
+ "' AND '" + btnDateTo.Date.ToString("dd MMM yy") + "'" + "GROUP BY soldProduct"
</code>```

Refer to

How to combine SELECT DISTINCT and SUM()

SQL query with distinct and sum

Body:
SQL QUERY SAMPLE

using (SQLiteConnection conn = new SQLiteConnection(con.dBasePath))
                {
                    SalesRecords.ItemsSource = conn.Query<DATA_BINDING.PURCHASED_PRODUCTS>
                    ("SELECT DISTINCT([soldProduct]), (SUM ([soldAmount])) FROM
                    [PURCHASED_PRODUCTS] " +
                    "WHERE salesDate BETWEEN '" + btnDateFrom.Date.ToString("dd MMM yy")
                    + "' AND '" + btnDateTo.Date.ToString("dd MMM yy") + "'");

                }]

.....XAMARIN CODE.....

Please how can i make this possible, with the distinct and sum at same time

Body:
Use GROUP BY instead of DISTINCT.

DISTINCT is used to select distinct elements , nothing more . If you want to aggregate(SUM) the items you need to use GROUP BY.

"SELECT soldProduct, (SUM ([soldAmount])) FROM [PURCHASED_PRODUCTS] " +
 "WHERE salesDate BETWEEN '" + btnDateFrom.Date.ToString("dd MMM yy")
+ "' AND '" + btnDateTo.Date.ToString("dd MMM yy") + "'" + "GROUP BY soldProduct"

Refer to

How to combine SELECT DISTINCT and SUM()

SQL query with distinct and sum


问:
Is it possible to call a method that is both final and protected from a unit test?
I have this example class

```<code>class Foo extends Parent {
  final override protected def test(): String = "hello world"
}
</code>```

As it is now, I am unable to call this method directly within my unit test. I am using Mockito and from what I've read so far, I either need to

remove the final so I can extend and override the access modifier (turn protected to private[package]) with another child class (Bar extends Foo)

update the Foo class to be private[package].

Neither options are desirable. Is there a way to keep the signature while still exposing the method to be unit testable?

答:
You can make test indirectly accessible by extending Foo in the test with a subclass declaring a public method that calls test.

You didn't mention which test execution framework you're using, but here's an example using ScalaTest with the FlatSpec style:

```<code>import org.scalatest.flatspec.AnyFlatSpec

class FooSpec extends AnyFlatSpec {
  class TestingFoo extends Foo {
    def accessibleTest: String = test
  }
  it should "say hello" in {
    assert(new TestingFoo().accessibleTest == "hello world")
  }
}
</code>```

The overall approach would be similar with other testing frameworks.

Body:
I have this example class

class Foo extends Parent {
  final override protected def test(): String = "hello world"
}

As it is now, I am unable to call this method directly within my unit test. I am using Mockito and from what I've read so far, I either need to

remove the final so I can extend and override the access modifier (turn protected to private[package]) with another child class (Bar extends Foo)

update the Foo class to be private[package].

Neither options are desirable. Is there a way to keep the signature while still exposing the method to be unit testable?

Body:
You can make test indirectly accessible by extending Foo in the test with a subclass declaring a public method that calls test.

You didn't mention which test execution framework you're using, but here's an example using ScalaTest with the FlatSpec style:

import org.scalatest.flatspec.AnyFlatSpec

class FooSpec extends AnyFlatSpec {
  class TestingFoo extends Foo {
    def accessibleTest: String = test
  }
  it should "say hello" in {
    assert(new TestingFoo().accessibleTest == "hello world")
  }
}

The overall approach would be similar with other testing frameworks.


问:
Groovy 4, JDK 11: Caught: Assertion failed
I mimic code snippet at reference document at https://groovy-lang.org/syntax.html#_groovydoc_comment

Program

```<code>print 'hello'

/**@
 * FFF
 */
class Oho {
    /**@
     * KKK
     */
    void run() {
    }
}

assert Oho.class.groovydoc.content.contains('FFF')
assert Oho.class.getMethod('run', new Class[0]).groovydoc.content.contains('KKK')
</code>```

```<code>"C:\Program Files\Java\jdk-11.0.12\bin\java.exe" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:51991,suspend=y,server=n -Dgroovy.home=C:\dovy\tools\groovy-4.0.0 -Dgroovy.starter.conf=C:\dovy\tools\groovy-4.0.0\conf\groovy-starter.conf -javaagent:C:\Users\Administrator\AppData\Local\JetBrains\IntelliJIdea2021.3\groovyHotSwap\gragent.jar -javaagent:C:\Users\Administrator\AppData\Local\JetBrains\IntelliJIdea2021.3\captureAgent\debugger-agent.jar -Dfile.encoding=UTF-8 -classpath "C:\dovy\tools\groovy-4.0.0\lib\groovy-4.0.0.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2021.3\lib\idea_rt.jar" org.codehaus.groovy.tools.GroovyStarter --conf C:\dovy\tools\groovy-4.0.0\conf\groovy-starter.conf --main groovy.ui.GroovyMain --classpath .;C:\Users\Administrator\Documents\groovy_projects\proj2022\out\production\proj2022;C:\dovy\tools\groovy-4.0.0\lib\ant-1.10.12.jar;C:\dovy\tools\groovy-4.0.0\lib\ant-antlr-1.10.12.jar;C:\dovy\tools\groovy-4.0.0\lib\ant-junit-1.10.12.jar;C:\dovy\tools\groovy-4.0.0\lib\ant-launcher-1.10.12.jar;C:\dovy\tools\groovy-4.0.0\lib\commons-cli-1.5.0.jar;C:\dovy\tools\groovy-4.0.0\lib\gpars-1.2.1.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-ant-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-astbuilder-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-cli-commons-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-cli-picocli-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-console-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-contracts-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-datetime-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-dateutil-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-docgenerator-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-ginq-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-groovydoc-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-groovysh-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-jmx-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-json-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-jsr223-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-macro-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-macro-library-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-nio-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-servlet-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-sql-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-swing-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-templates-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-test-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-test-junit5-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-testng-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-toml-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-typecheckers-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-xml-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-yaml-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\hamcrest-core-1.3.jar;C:\dovy\tools\groovy-4.0.0\lib\ivy-2.5.0.jar;C:\dovy\tools\groovy-4.0.0\lib\jackson-annotations-2.13.1.jar;C:\dovy\tools\groovy-4.0.0\lib\jackson-core-2.13.1.jar;C:\dovy\tools\groovy-4.0.0\lib\jackson-databind-2.13.1.jar;C:\dovy\tools\groovy-4.0.0\lib\jackson-dataformat-toml-2.13.1.jar;C:\dovy\tools\groovy-4.0.0\lib\jackson-dataformat-yaml-2.13.1.jar;C:\dovy\tools\groovy-4.0.0\lib\jansi-2.4.0.jar;C:\dovy\tools\groovy-4.0.0\lib\javaparser-core-3.24.0.jar;C:\dovy\tools\groovy-4.0.0\lib\jcommander-1.78.jar;C:\dovy\tools\groovy-4.0.0\lib\jline-2.14.6.jar;C:\dovy\tools\groovy-4.0.0\lib\jquery-3.5.1.jar;C:\dovy\tools\groovy-4.0.0\lib\jsr166y-1.7.0.jar;C:\dovy\tools\groovy-4.0.0\lib\junit-4.13.2.jar;C:\dovy\tools\groovy-4.0.0\lib\junit-jupiter-api-5.8.2.jar;C:\dovy\tools\groovy-4.0.0\lib\junit-jupiter-engine-5.8.2.jar;C:\dovy\tools\groovy-4.0.0\lib\junit-platform-commons-1.8.2.jar;C:\dovy\tools\groovy-4.0.0\lib\junit-platform-engine-1.8.2.jar;C:\dovy\tools\groovy-4.0.0\lib\junit-platform-launcher-1.8.2.jar;C:\dovy\tools\groovy-4.0.0\lib\multiverse-core-0.7.0.jar;C:\dovy\tools\groovy-4.0.0\lib\mxparser-1.2.2.jar;C:\dovy\tools\groovy-4.0.0\lib\opentest4j-1.2.0.jar;C:\dovy\tools\groovy-4.0.0\lib\org.abego.treelayout.core-1.0.3.jar;C:\dovy\tools\groovy-4.0.0\lib\qdox-1.12.1.jar;C:\dovy\tools\groovy-4.0.0\lib\slf4j-api-1.7.32.jar;C:\dovy\tools\groovy-4.0.0\lib\snakeyaml-1.28.jar;C:\dovy\tools\groovy-4.0.0\lib\testng-7.5.jar;C:\dovy\tools\groovy-4.0.0\lib\xstream-1.4.18.jar --encoding=UTF-8 C:\Users\Administrator\Documents\groovy_projects\proj2022\src\sample\Auto.groovy --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.invoke=ALL-UNNAMED
Connected to the target VM, address: '127.0.0.1:51991', transport: 'socket'
helloDisconnected from the target VM, address: '127.0.0.1:51991', transport: 'socket'
Caught: Assertion failed:

assert Oho.class.groovydoc.content.contains('FFF')
                 |         |       |
                 |         ''      false
                 groovy.lang.groovydoc.Groovydoc$1@682c1e93 (toString() == "")

Assertion failed:

assert Oho.class.groovydoc.content.contains('FFF')
                 |         |       |
                 |         ''      false
                 groovy.lang.groovydoc.Groovydoc$1@682c1e93 (toString() == "")

    at Auto.run(Auto.groovy:14)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

Process finished with exit code 1

</code>```

How to fix error?

答:
Thank @tim_yates, Set VM option

```<code>-Dgroovy.attach.runtime.groovydoc=true
</code>```

Body:
I mimic code snippet at reference document at https://groovy-lang.org/syntax.html#_groovydoc_comment

Program

print 'hello'

/**@
 * FFF
 */
class Oho {
    /**@
     * KKK
     */
    void run() {
    }
}

assert Oho.class.groovydoc.content.contains('FFF')
assert Oho.class.getMethod('run', new Class[0]).groovydoc.content.contains('KKK')

"C:\Program Files\Java\jdk-11.0.12\bin\java.exe" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:51991,suspend=y,server=n -Dgroovy.home=C:\dovy\tools\groovy-4.0.0 -Dgroovy.starter.conf=C:\dovy\tools\groovy-4.0.0\conf\groovy-starter.conf -javaagent:C:\Users\Administrator\AppData\Local\JetBrains\IntelliJIdea2021.3\groovyHotSwap\gragent.jar -javaagent:C:\Users\Administrator\AppData\Local\JetBrains\IntelliJIdea2021.3\captureAgent\debugger-agent.jar -Dfile.encoding=UTF-8 -classpath "C:\dovy\tools\groovy-4.0.0\lib\groovy-4.0.0.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2021.3\lib\idea_rt.jar" org.codehaus.groovy.tools.GroovyStarter --conf C:\dovy\tools\groovy-4.0.0\conf\groovy-starter.conf --main groovy.ui.GroovyMain --classpath .;C:\Users\Administrator\Documents\groovy_projects\proj2022\out\production\proj2022;C:\dovy\tools\groovy-4.0.0\lib\ant-1.10.12.jar;C:\dovy\tools\groovy-4.0.0\lib\ant-antlr-1.10.12.jar;C:\dovy\tools\groovy-4.0.0\lib\ant-junit-1.10.12.jar;C:\dovy\tools\groovy-4.0.0\lib\ant-launcher-1.10.12.jar;C:\dovy\tools\groovy-4.0.0\lib\commons-cli-1.5.0.jar;C:\dovy\tools\groovy-4.0.0\lib\gpars-1.2.1.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-ant-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-astbuilder-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-cli-commons-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-cli-picocli-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-console-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-contracts-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-datetime-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-dateutil-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-docgenerator-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-ginq-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-groovydoc-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-groovysh-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-jmx-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-json-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-jsr223-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-macro-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-macro-library-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-nio-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-servlet-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-sql-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-swing-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-templates-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-test-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-test-junit5-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-testng-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-toml-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-typecheckers-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-xml-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\groovy-yaml-4.0.0.jar;C:\dovy\tools\groovy-4.0.0\lib\hamcrest-core-1.3.jar;C:\dovy\tools\groovy-4.0.0\lib\ivy-2.5.0.jar;C:\dovy\tools\groovy-4.0.0\lib\jackson-annotations-2.13.1.jar;C:\dovy\tools\groovy-4.0.0\lib\jackson-core-2.13.1.jar;C:\dovy\tools\groovy-4.0.0\lib\jackson-databind-2.13.1.jar;C:\dovy\tools\groovy-4.0.0\lib\jackson-dataformat-toml-2.13.1.jar;C:\dovy\tools\groovy-4.0.0\lib\jackson-dataformat-yaml-2.13.1.jar;C:\dovy\tools\groovy-4.0.0\lib\jansi-2.4.0.jar;C:\dovy\tools\groovy-4.0.0\lib\javaparser-core-3.24.0.jar;C:\dovy\tools\groovy-4.0.0\lib\jcommander-1.78.jar;C:\dovy\tools\groovy-4.0.0\lib\jline-2.14.6.jar;C:\dovy\tools\groovy-4.0.0\lib\jquery-3.5.1.jar;C:\dovy\tools\groovy-4.0.0\lib\jsr166y-1.7.0.jar;C:\dovy\tools\groovy-4.0.0\lib\junit-4.13.2.jar;C:\dovy\tools\groovy-4.0.0\lib\junit-jupiter-api-5.8.2.jar;C:\dovy\tools\groovy-4.0.0\lib\junit-jupiter-engine-5.8.2.jar;C:\dovy\tools\groovy-4.0.0\lib\junit-platform-commons-1.8.2.jar;C:\dovy\tools\groovy-4.0.0\lib\junit-platform-engine-1.8.2.jar;C:\dovy\tools\groovy-4.0.0\lib\junit-platform-launcher-1.8.2.jar;C:\dovy\tools\groovy-4.0.0\lib\multiverse-core-0.7.0.jar;C:\dovy\tools\groovy-4.0.0\lib\mxparser-1.2.2.jar;C:\dovy\tools\groovy-4.0.0\lib\opentest4j-1.2.0.jar;C:\dovy\tools\groovy-4.0.0\lib\org.abego.treelayout.core-1.0.3.jar;C:\dovy\tools\groovy-4.0.0\lib\qdox-1.12.1.jar;C:\dovy\tools\groovy-4.0.0\lib\slf4j-api-1.7.32.jar;C:\dovy\tools\groovy-4.0.0\lib\snakeyaml-1.28.jar;C:\dovy\tools\groovy-4.0.0\lib\testng-7.5.jar;C:\dovy\tools\groovy-4.0.0\lib\xstream-1.4.18.jar --encoding=UTF-8 C:\Users\Administrator\Documents\groovy_projects\proj2022\src\sample\Auto.groovy --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.invoke=ALL-UNNAMED
Connected to the target VM, address: '127.0.0.1:51991', transport: 'socket'
helloDisconnected from the target VM, address: '127.0.0.1:51991', transport: 'socket'
Caught: Assertion failed:

assert Oho.class.groovydoc.content.contains('FFF')
                 |         |       |
                 |         ''      false
                 groovy.lang.groovydoc.Groovydoc$1@682c1e93 (toString() == "")

Assertion failed:

assert Oho.class.groovydoc.content.contains('FFF')
                 |         |       |
                 |         ''      false
                 groovy.lang.groovydoc.Groovydoc$1@682c1e93 (toString() == "")

    at Auto.run(Auto.groovy:14)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

Process finished with exit code 1

How to fix error?

Body:
Thank @tim_yates, Set VM option

-Dgroovy.attach.runtime.groovydoc=true


问:
Using other Class C++ Primer 5th Edition
i somehow have alot of Errors, when i try to implement another given class in the Book (https://github.com/jaege/Cpp-Primer-5th-Exercises/blob/master/ch1/Sales_item.h this one). Now if i try to compile my code i only get alot of Error messages.
This is my main class:

```<code>#include <iostream>
#include "Sales_item.h"

int main() {
    Sales_item item1, item2;
    std::cin >> item1 >> item2;

    if (item1.isbn() == item2.isbn()) {
        std::cout << item1 + item2 << std::endl;
        return 0;
    }
    else {
        std::cerr << "Data must refer to the same ISBN" << std::endl;
        return -1;
    }

}
</code>```

But now i dont really know how to use the other class from the Github.
My header File look like this:

```<code>#include <iostream>
#include <string>

class Sales_item {
// these declarations are explained section 7.2.1, p. 270
// and in chapter 14, pages 557, 558, 561
friend std::istream& operator>>(std::istream&, Sales_item&);
friend std::ostream& operator<<(std::ostream&, const Sales_item&);
friend bool operator<(const Sales_item&, const Sales_item&);
friend bool
operator==(const Sales_item&, const Sales_item&);
public:
    // constructors are explained in section 7.1.4, pages 262 - 265
    // default constructor needed to initialize members of built-in type
#if defined(IN_CLASS_INITS) && defined(DEFAULT_FCNS)
    Sales_item() = default;
#else
    Sales_item(): units_sold(0), revenue(0.0) { }
#endif
    Sales_item(const std::string &book):
              bookNo(book), units_sold(0), revenue(0.0) { }
    Sales_item(std::istream &is) { is >> *this; }
public:
    // operations on Sales_item objects
    // member binary operator: left-hand operand bound to implicit this pointer
    Sales_item& operator+=(const Sales_item&);

    // operations on Sales_item objects
    std::string isbn() const { return bookNo; }
    double avg_price() const;
// private members as before
private:
    std::string bookNo;      // implicitly initialized to the empty string
#ifdef IN_CLASS_INITS
    unsigned units_sold = 0; // explicitly initialized
    double revenue = 0.0;
#else
    unsigned units_sold;
    double revenue;
#endif
};

// used in chapter 10
inline
bool compareIsbn(const Sales_item &lhs, const Sales_item &rhs)
{ return lhs.isbn() == rhs.isbn(); }

// nonmember binary operator: must declare a parameter for each operand
Sales_item operator+(const Sales_item&, const Sales_item&);

inline bool
operator==(const Sales_item &lhs, const Sales_item &rhs)
{
    // must be made a friend of Sales_item
    return lhs.units_sold == rhs.units_sold &&
           lhs.revenue == rhs.revenue &&
           lhs.isbn() == rhs.isbn();
}

inline bool
operator!=(const Sales_item &lhs, const Sales_item &rhs)
{
    return !(lhs == rhs); // != defined in terms of operator==
}

// assumes that both objects refer to the same ISBN
Sales_item& Sales_item::operator+=(const Sales_item& rhs)
{
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    return *this;
}

// assumes that both objects refer to the same ISBN
Sales_item
operator+(const Sales_item& lhs, const Sales_item& rhs)
{
    Sales_item ret(lhs);  // copy (|lhs|) into a local object that we'll return
    ret += rhs;           // add in the contents of (|rhs|)
    return ret;           // return (|ret|) by value
}

std::istream&
operator>>(std::istream& in, Sales_item& s)
{
    double price;
    in >> s.bookNo >> s.units_sold >> price;
    // check that the inputs succeeded
    if (in)
        s.revenue = s.units_sold * price;
    else
        s = Sales_item();  // input failed: reset object to default state
    return in;
}

std::ostream&
operator<<(std::ostream& out, const Sales_item& s)
{
    out << s.isbn() << " " << s.units_sold << " "
        << s.revenue << " " << s.avg_price();
    return out;
}

double Sales_item::avg_price() const
{
    if (units_sold)
        return revenue/units_sold;
    else
        return 0;
}
</code>```

And the Sales_item itself is basically the same.

```<code>#include <iostream>
#include <string>

class Sales_item {
    // these declarations are explained section 7.2.1, p. 270
    // and in chapter 14, pages 557, 558, 561
    friend std::istream& operator>>(std::istream&, Sales_item&);
    friend std::ostream& operator<<(std::ostream&, const Sales_item&);
    friend bool operator<(const Sales_item&, const Sales_item&);
    friend bool
        operator==(const Sales_item&, const Sales_item&);
public:
    // constructors are explained in section 7.1.4, pages 262 - 265
    // default constructor needed to initialize members of built-in type
#if defined(IN_CLASS_INITS) && defined(DEFAULT_FCNS)
    Sales_item() = default;
#else
    Sales_item() : units_sold(0), revenue(0.0) { }
#endif
    Sales_item(const std::string& book) :
        bookNo(book), units_sold(0), revenue(0.0) { }
    Sales_item(std::istream& is) { is >> *this; }
public:
    // operations on Sales_item objects
    // member binary operator: left-hand operand bound to implicit this pointer
    Sales_item& operator+=(const Sales_item&);

    // operations on Sales_item objects
    std::string isbn() const { return bookNo; }
    double avg_price() const;
    // private members as before
private:
    std::string bookNo;      // implicitly initialized to the empty string
#ifdef IN_CLASS_INITS
    unsigned units_sold = 0; // explicitly initialized
    double revenue = 0.0;
#else
    unsigned units_sold;
    double revenue;
#endif
};

// used in chapter 10
inline
bool compareIsbn(const Sales_item& lhs, const Sales_item& rhs)
{
    return lhs.isbn() == rhs.isbn();
}

// nonmember binary operator: must declare a parameter for each operand
Sales_item operator+(const Sales_item&, const Sales_item&);

inline bool
operator==(const Sales_item& lhs, const Sales_item& rhs)
{
    // must be made a friend of Sales_item
    return lhs.units_sold == rhs.units_sold &&
        lhs.revenue == rhs.revenue &&
        lhs.isbn() == rhs.isbn();
}

inline bool
operator!=(const Sales_item& lhs, const Sales_item& rhs)
{
    return !(lhs == rhs); // != defined in terms of operator==
}

// assumes that both objects refer to the same ISBN
Sales_item& Sales_item::operator+=(const Sales_item& rhs)
{
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    return *this;
}

// assumes that both objects refer to the same ISBN
Sales_item
operator+(const Sales_item& lhs, const Sales_item& rhs)
{
    Sales_item ret(lhs);  // copy (|lhs|) into a local object that we'll return
    ret += rhs;           // add in the contents of (|rhs|)
    return ret;           // return (|ret|) by value
}

std::istream&
operator>>(std::istream& in, Sales_item& s)
{
    double price;
    in >> s.bookNo >> s.units_sold >> price;
    // check that the inputs succeeded
    if (in)
        s.revenue = s.units_sold * price;
    else
        s = Sales_item();  // input failed: reset object to default state
    return in;
}

std::ostream&
operator<<(std::ostream& out, const Sales_item& s)
{
    out << s.isbn() << " " << s.units_sold << " "
        << s.revenue << " " << s.avg_price();
    return out;
}

double Sales_item::avg_price() const
{
    if (units_sold)
        return revenue / units_sold;
    else
        return 0;
}
</code>```

This is my error output after compiling:

```<code>1>Lernencpp.cpp
1>Sales_item.obj : error LNK2005: "class std::basic_istream<char,struct std::char_traits<char> > & __cdecl operator>>(class std::basic_istream<char,struct std::char_traits<char> > &,class Sales_item &)" (??5@YAAAV?$basic_istream@DU?$char_traits@D@std@@@std@@AAV01@AAVSales_item@@@Z) already defined in Lernencpp.obj
1>Sales_item.obj : error LNK2005: "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class Sales_item const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABVSales_item@@@Z) already defined in Lernencpp.obj
1>Sales_item.obj : error LNK2005: "class Sales_item __cdecl operator+(class Sales_item const &,class Sales_item const &)" (??H@YA?AVSales_item@@ABV0@0@Z) already defined in Lernencpp.obj
1>Sales_item.obj : error LNK2005: "public: class Sales_item & __thiscall Sales_item::operator+=(class Sales_item const &)" (??YSales_item@@QAEAAV0@ABV0@@Z) already defined in Lernencpp.obj
1>Sales_item.obj : error LNK2005: "public: double __thiscall Sales_item::avg_price(void)const " (?avg_price@Sales_item@@QBENXZ) already defined in Lernencpp.obj
1>C:\Users\User\source\repos\Lernencpp\Debug\Lernencpp.exe : fatal error LNK1169: one or more multiply defined symbols found
1>Done building project "Lernencpp.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code>```

I would really appreciate any help, this book is alot of fun but i am kinda hardstuck right now.

答: I observed that Sales_item.h is included in your main function, and in the link you shared, Sales_item.h includes Version_test.h, so you need to download both header files to ensure that your main function runs correctly.

Body:
i somehow have alot of Errors, when i try to implement another given class in the Book (https://github.com/jaege/Cpp-Primer-5th-Exercises/blob/master/ch1/Sales_item.h this one). Now if i try to compile my code i only get alot of Error messages.
This is my main class:

#include <iostream>
#include "Sales_item.h"

int main() {
    Sales_item item1, item2;
    std::cin >> item1 >> item2;

    if (item1.isbn() == item2.isbn()) {
        std::cout << item1 + item2 << std::endl;
        return 0;
    }
    else {
        std::cerr << "Data must refer to the same ISBN" << std::endl;
        return -1;
    }

}

But now i dont really know how to use the other class from the Github.
My header File look like this:

#include <iostream>
#include <string>

class Sales_item {
// these declarations are explained section 7.2.1, p. 270
// and in chapter 14, pages 557, 558, 561
friend std::istream& operator>>(std::istream&, Sales_item&);
friend std::ostream& operator<<(std::ostream&, const Sales_item&);
friend bool operator<(const Sales_item&, const Sales_item&);
friend bool
operator==(const Sales_item&, const Sales_item&);
public:
    // constructors are explained in section 7.1.4, pages 262 - 265
    // default constructor needed to initialize members of built-in type
#if defined(IN_CLASS_INITS) && defined(DEFAULT_FCNS)
    Sales_item() = default;
#else
    Sales_item(): units_sold(0), revenue(0.0) { }
#endif
    Sales_item(const std::string &book):
              bookNo(book), units_sold(0), revenue(0.0) { }
    Sales_item(std::istream &is) { is >> *this; }
public:
    // operations on Sales_item objects
    // member binary operator: left-hand operand bound to implicit this pointer
    Sales_item& operator+=(const Sales_item&);

    // operations on Sales_item objects
    std::string isbn() const { return bookNo; }
    double avg_price() const;
// private members as before
private:
    std::string bookNo;      // implicitly initialized to the empty string
#ifdef IN_CLASS_INITS
    unsigned units_sold = 0; // explicitly initialized
    double revenue = 0.0;
#else
    unsigned units_sold;
    double revenue;
#endif
};

// used in chapter 10
inline
bool compareIsbn(const Sales_item &lhs, const Sales_item &rhs)
{ return lhs.isbn() == rhs.isbn(); }

// nonmember binary operator: must declare a parameter for each operand
Sales_item operator+(const Sales_item&, const Sales_item&);

inline bool
operator==(const Sales_item &lhs, const Sales_item &rhs)
{
    // must be made a friend of Sales_item
    return lhs.units_sold == rhs.units_sold &&
           lhs.revenue == rhs.revenue &&
           lhs.isbn() == rhs.isbn();
}

inline bool
operator!=(const Sales_item &lhs, const Sales_item &rhs)
{
    return !(lhs == rhs); // != defined in terms of operator==
}

// assumes that both objects refer to the same ISBN
Sales_item& Sales_item::operator+=(const Sales_item& rhs)
{
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    return *this;
}

// assumes that both objects refer to the same ISBN
Sales_item
operator+(const Sales_item& lhs, const Sales_item& rhs)
{
    Sales_item ret(lhs);  // copy (|lhs|) into a local object that we'll return
    ret += rhs;           // add in the contents of (|rhs|)
    return ret;           // return (|ret|) by value
}

std::istream&
operator>>(std::istream& in, Sales_item& s)
{
    double price;
    in >> s.bookNo >> s.units_sold >> price;
    // check that the inputs succeeded
    if (in)
        s.revenue = s.units_sold * price;
    else
        s = Sales_item();  // input failed: reset object to default state
    return in;
}

std::ostream&
operator<<(std::ostream& out, const Sales_item& s)
{
    out << s.isbn() << " " << s.units_sold << " "
        << s.revenue << " " << s.avg_price();
    return out;
}

double Sales_item::avg_price() const
{
    if (units_sold)
        return revenue/units_sold;
    else
        return 0;
}

And the Sales_item itself is basically the same.

#include <iostream>
#include <string>

class Sales_item {
    // these declarations are explained section 7.2.1, p. 270
    // and in chapter 14, pages 557, 558, 561
    friend std::istream& operator>>(std::istream&, Sales_item&);
    friend std::ostream& operator<<(std::ostream&, const Sales_item&);
    friend bool operator<(const Sales_item&, const Sales_item&);
    friend bool
        operator==(const Sales_item&, const Sales_item&);
public:
    // constructors are explained in section 7.1.4, pages 262 - 265
    // default constructor needed to initialize members of built-in type
#if defined(IN_CLASS_INITS) && defined(DEFAULT_FCNS)
    Sales_item() = default;
#else
    Sales_item() : units_sold(0), revenue(0.0) { }
#endif
    Sales_item(const std::string& book) :
        bookNo(book), units_sold(0), revenue(0.0) { }
    Sales_item(std::istream& is) { is >> *this; }
public:
    // operations on Sales_item objects
    // member binary operator: left-hand operand bound to implicit this pointer
    Sales_item& operator+=(const Sales_item&);

    // operations on Sales_item objects
    std::string isbn() const { return bookNo; }
    double avg_price() const;
    // private members as before
private:
    std::string bookNo;      // implicitly initialized to the empty string
#ifdef IN_CLASS_INITS
    unsigned units_sold = 0; // explicitly initialized
    double revenue = 0.0;
#else
    unsigned units_sold;
    double revenue;
#endif
};

// used in chapter 10
inline
bool compareIsbn(const Sales_item& lhs, const Sales_item& rhs)
{
    return lhs.isbn() == rhs.isbn();
}

// nonmember binary operator: must declare a parameter for each operand
Sales_item operator+(const Sales_item&, const Sales_item&);

inline bool
operator==(const Sales_item& lhs, const Sales_item& rhs)
{
    // must be made a friend of Sales_item
    return lhs.units_sold == rhs.units_sold &&
        lhs.revenue == rhs.revenue &&
        lhs.isbn() == rhs.isbn();
}

inline bool
operator!=(const Sales_item& lhs, const Sales_item& rhs)
{
    return !(lhs == rhs); // != defined in terms of operator==
}

// assumes that both objects refer to the same ISBN
Sales_item& Sales_item::operator+=(const Sales_item& rhs)
{
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    return *this;
}

// assumes that both objects refer to the same ISBN
Sales_item
operator+(const Sales_item& lhs, const Sales_item& rhs)
{
    Sales_item ret(lhs);  // copy (|lhs|) into a local object that we'll return
    ret += rhs;           // add in the contents of (|rhs|)
    return ret;           // return (|ret|) by value
}

std::istream&
operator>>(std::istream& in, Sales_item& s)
{
    double price;
    in >> s.bookNo >> s.units_sold >> price;
    // check that the inputs succeeded
    if (in)
        s.revenue = s.units_sold * price;
    else
        s = Sales_item();  // input failed: reset object to default state
    return in;
}

std::ostream&
operator<<(std::ostream& out, const Sales_item& s)
{
    out << s.isbn() << " " << s.units_sold << " "
        << s.revenue << " " << s.avg_price();
    return out;
}

double Sales_item::avg_price() const
{
    if (units_sold)
        return revenue / units_sold;
    else
        return 0;
}

This is my error output after compiling:

1>Lernencpp.cpp
1>Sales_item.obj : error LNK2005: "class std::basic_istream<char,struct std::char_traits<char> > & __cdecl operator>>(class std::basic_istream<char,struct std::char_traits<char> > &,class Sales_item &)" (??5@YAAAV?$basic_istream@DU?$char_traits@D@std@@@std@@AAV01@AAVSales_item@@@Z) already defined in Lernencpp.obj
1>Sales_item.obj : error LNK2005: "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class Sales_item const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABVSales_item@@@Z) already defined in Lernencpp.obj
1>Sales_item.obj : error LNK2005: "class Sales_item __cdecl operator+(class Sales_item const &,class Sales_item const &)" (??H@YA?AVSales_item@@ABV0@0@Z) already defined in Lernencpp.obj
1>Sales_item.obj : error LNK2005: "public: class Sales_item & __thiscall Sales_item::operator+=(class Sales_item const &)" (??YSales_item@@QAEAAV0@ABV0@@Z) already defined in Lernencpp.obj
1>Sales_item.obj : error LNK2005: "public: double __thiscall Sales_item::avg_price(void)const " (?avg_price@Sales_item@@QBENXZ) already defined in Lernencpp.obj
1>C:\Users\User\source\repos\Lernencpp\Debug\Lernencpp.exe : fatal error LNK1169: one or more multiply defined symbols found
1>Done building project "Lernencpp.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I would really appreciate any help, this book is alot of fun but i am kinda hardstuck right now.


问:
Fabric Modding get MinecraftServer instance without an entity
I'm creating a mod in fabric that needs to iterate through all players in the current server every x ticks, but I haven't found a way to access the MinecraftServer instance without a currently existing entity. This is the code:

```<code>private void onServerTick() {
    MinecraftServer server = null; // Placeholder
    assert server != null;
    for (ServerPlayerEntity player : PlayerLookup.all(server)) {
        // Stuff goes here
    }
}
</code>```

I have tried getting the server login network handler as it has a getServer() function, but to no avail. The code should run fully server side, so no player entities allowed.

Any bright ideas?

答:
I found a solution after tinkering with it for a bit.

So just a listener that returns the MinecraftServer instance back apparently <.<"

```<code>public class ServerTickListener implements ServerTickEvents.EndTick{
     @Override
     public void onEndTick(MinecraftServer minecraftServer){
          OverchantedMain.onServerTick(minecraftServer);
     }
}
</code>```

And initialized in Main

```<code>@Override
public void onInitialize(){
     {...}
     ServerTickEvents.END_SERVER_TICK.register(new ServerTickListener());
}
</code>```

Not sure if this is the most effective solution but hey, it works!

Body:
I'm creating a mod in fabric that needs to iterate through all players in the current server every x ticks, but I haven't found a way to access the MinecraftServer instance without a currently existing entity. This is the code:

private void onServerTick() {
    MinecraftServer server = null; // Placeholder
    assert server != null;
    for (ServerPlayerEntity player : PlayerLookup.all(server)) {
        // Stuff goes here
    }
}

I have tried getting the server login network handler as it has a getServer() function, but to no avail. The code should run fully server side, so no player entities allowed.

Any bright ideas?

Body:
I found a solution after tinkering with it for a bit.

So just a listener that returns the MinecraftServer instance back apparently <.<"

public class ServerTickListener implements ServerTickEvents.EndTick{
     @Override
     public void onEndTick(MinecraftServer minecraftServer){
          OverchantedMain.onServerTick(minecraftServer);
     }
}

And initialized in Main

@Override
public void onInitialize(){
     {...}
     ServerTickEvents.END_SERVER_TICK.register(new ServerTickListener());
}

Not sure if this is the most effective solution but hey, it works!


问:
evaluate `resin(x)` function in string with regular expression
I am trying to evaluate a function in a string like this resin(8)

so if i have this text 3*(resin(4)-sin(12))

I need to evaluate resin(1) so it will replace that while occurrence with the result which should look like 392.9

I am using this

result = result.replace(/(?<={resin\()(.*?)(?=\)})/, x => parseInt(392.9 * x))
```

but i need it to replace the resin( part and the ) closing parentheses.

is there any regexp magic I can use?

答:
Are you sure you need a positive lookbehind and a positive lookahead?

In my opinion, when using a regex replacer, as you did, the grouping is more than enough to accomplish the task:

```<code>result = result.replace(/resin\((\d+\.?\d*)\)/g, (_, x) => parseInt(392.9 * parseFloat(x)))
</code>```

Edit:
I just read in your question that you need resin(1) to be replaced with 392.9, but in your snippet you used parseInt and I kept it in my example. Just drop the parseInt in case you don't need the result to be an integer

Body:
I am trying to evaluate a function in a string like this resin(8)

so if i have this text 3*(resin(4)-sin(12))

I need to evaluate resin(1) so it will replace that while occurrence with the result which should look like 392.9

I am using this

result = result.replace(/(?<={resin\()(.*?)(?=\)})/, x => parseInt(392.9 * x))

but i need it to replace the resin( part and the ) closing parentheses.

is there any regexp magic I can use?

Body:
Are you sure you need a positive lookbehind and a positive lookahead?

In my opinion, when using a regex replacer, as you did, the grouping is more than enough to accomplish the task:

result = result.replace(/resin\((\d+\.?\d*)\)/g, (_, x) => parseInt(392.9 * parseFloat(x)))

Edit:
I just read in your question that you need resin(1) to be replaced with 392.9, but in your snippet you used parseInt and I kept it in my example. Just drop the parseInt in case you don't need the result to be an integer


问:
R function for trimming beginning of a string
Here is a sample of the dataset I am working with.

```<code>df <- data.frame( precinct = c("01-001", "01-002", "Adv 1 01-001", "Adv 1 01-002"), total = c(100, 102, 4, 6))
</code>```

I need to remove the specific string "Adv 1 " while leaving everything else intact. I considered stringr functions like str_replace() and str_remove() but but I understand it only works on single letters. Is there a function or procedure for performing the trimming?

答:
You can use gsub() to substitute the text to empty.

UPDATE 2: as pointed out by @r2evans:

If you have multiple patterns of "Adv 1 " in the string and you only wish to replace the one that is at the beginning, use "^Adv 1 " in the codes instead of "Adv 1 " (e.g. df %>% mutate(precinct = gsub("^Adv 1 ", "", precinct))).

^ is a regular expression (regex) that specify the beginning of a string.

Thanks @r2evans for the suggestion!

Tidyverse

This will not replace your df unless you assign the result back to it.

```<code>library(tidyverse)

df %>% mutate(precinct = gsub("Adv 1 ", "", precinct))
</code>```

UPDATE: in the comment, @Onyambu suggested me to include the following codes for the tidyverse solution. Thanks @Onyambu!

```<code>df %>% mutate(precinct = str_remove(precinct, 'Adv 1 '))
</code>```

And

```<code>df %>% mutate(precinct = str_replace(precinct, 'Adv 1 ', ''))
</code>```

Base R

This will immediately replace your df.

```<code>df[, 1] <- gsub("Adv 1 ", "", df[, 1])
</code>```

Body:
Here is a sample of the dataset I am working with.

df <- data.frame( precinct = c("01-001", "01-002", "Adv 1 01-001", "Adv 1 01-002"), total = c(100, 102, 4, 6))

I need to remove the specific string "Adv 1 " while leaving everything else intact. I considered stringr functions like str_replace() and str_remove() but but I understand it only works on single letters. Is there a function or procedure for performing the trimming?

Body:
You can use gsub() to substitute the text to empty.

UPDATE 2: as pointed out by @r2evans:

If you have multiple patterns of "Adv 1 " in the string and you only wish to replace the one that is at the beginning, use "^Adv 1 " in the codes instead of "Adv 1 " (e.g. df %>% mutate(precinct = gsub("^Adv 1 ", "", precinct))).

^ is a regular expression (regex) that specify the beginning of a string.

Thanks @r2evans for the suggestion!

Tidyverse

This will not replace your df unless you assign the result back to it.

library(tidyverse)

df %>% mutate(precinct = gsub("Adv 1 ", "", precinct))

UPDATE: in the comment, @Onyambu suggested me to include the following codes for the tidyverse solution. Thanks @Onyambu!

df %>% mutate(precinct = str_remove(precinct, 'Adv 1 '))

And

df %>% mutate(precinct = str_replace(precinct, 'Adv 1 ', ''))

Base R

This will immediately replace your df.

df[, 1] <- gsub("Adv 1 ", "", df[, 1])


问:
Java: avoid checking for null in nested classes (Deep Null checking)
Imagine I have a class Family. It contains a List of Person. Each (class) Person contains a (class) Address. Each (class) Address contains a (class) PostalCode.  Any "intermediate" class can be null.

So, is there a simple way to get to PostalCode without having to check for null in every step? i.e., is there a way to avoid the following daisy chaining code? I know there's not "native" Java solution, but was hoping if anyone knows of a library or something. (checked Commons & Guava and didn't see anything)

```<code>if(family != null) {
    if(family.getPeople() != null) {
        if(family.people.get(0) != null) {
            if(people.get(0).getAddress() != null) {
                if(people.get(0).getAddress().getPostalCode() != null) {
                    //FINALLY MADE IT TO DO SOMETHING!!!
                }
            }
        }
    }
}
</code>```

No, can't change the structure. It's from a service I don't have control over.

No, I can't use Groovy and it's handy "Elvis" operator.

No, I'd prefer not to wait for Java 8 :D

I can't believe I'm the first dev ever to get sick 'n tired of writing code like this, but I haven't been able to find a solution.

答:
I personally prefer something similar to:

```<code>nullSafeLogic(() -> family.people.get(0).getAddress().getPostalCode(), x -> doSomethingWithX(x))

public static <T, U> void nullSafeLogic(Supplier<T> supplier, Function<T,U> function) {
    try {
        function.apply(supplier.get());
    } catch (NullPointerException n) {
        return null;
    }
}
</code>```

or something like

```<code>nullSafeGetter(() -> family.people.get(0).getAddress().getPostalCode())

public static <T> T nullSafeGetter(Supplier<T> supplier) {
    try {
        return supplier.get();
    } catch (NullPointerException n) {
        return null;
    }
}
</code>```

Best part is the static methods are reusable with any function :)

Body:
Imagine I have a class Family. It contains a List of Person. Each (class) Person contains a (class) Address. Each (class) Address contains a (class) PostalCode.  Any "intermediate" class can be null.

So, is there a simple way to get to PostalCode without having to check for null in every step? i.e., is there a way to avoid the following daisy chaining code? I know there's not "native" Java solution, but was hoping if anyone knows of a library or something. (checked Commons & Guava and didn't see anything)

if(family != null) {
    if(family.getPeople() != null) {
        if(family.people.get(0) != null) {
            if(people.get(0).getAddress() != null) {
                if(people.get(0).getAddress().getPostalCode() != null) {
                    //FINALLY MADE IT TO DO SOMETHING!!!
                }
            }
        }
    }
}

No, can't change the structure. It's from a service I don't have control over.

No, I can't use Groovy and it's handy "Elvis" operator.

No, I'd prefer not to wait for Java 8 :D

I can't believe I'm the first dev ever to get sick 'n tired of writing code like this, but I haven't been able to find a solution.

Body:
I personally prefer something similar to:

nullSafeLogic(() -> family.people.get(0).getAddress().getPostalCode(), x -> doSomethingWithX(x))

public static <T, U> void nullSafeLogic(Supplier<T> supplier, Function<T,U> function) {
    try {
        function.apply(supplier.get());
    } catch (NullPointerException n) {
        return null;
    }
}

or something like

nullSafeGetter(() -> family.people.get(0).getAddress().getPostalCode())

public static <T> T nullSafeGetter(Supplier<T> supplier) {
    try {
        return supplier.get();
    } catch (NullPointerException n) {
        return null;
    }
}

Best part is the static methods are reusable with any function :)