问:
Transaction is not rolling back in spring batch item writer
Transaction is not rolling back in spring batch. I am throwing exception intentionally to test transaction roll back. Database transaction is committing even with exception thrown from the item writer.Below is the method in writer which is saving into DB. compEvent object is jpa repository injected into this class

```

    private void writeCEs(Map> agentMap) throws FailedCompensationException, Exception {

        for (Entry> agent : agentMap.entrySet()) {
            agent.getValue().stream().forEach((ce) -> {
                compEvent.save(ce);
            });
            updateRecordFileStatus(agent.getKey());
            //postToAccounting(agent.getKey(), agent.getValue());
        }
        throw new Exception("Testing XA roolback.... ");
     }

```

I tried marking transaction for the above method with
@Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
Still it is committing the transaction. I am sure I am missing something. any help would be appreciated.

Below is my batch configuration

```

       @EnableBatchProcessing
        @EnableTransactionManagement @Configuration @ComponentScan({ "com.pm.*" })

    public class TrueBatchConfig extends DefaultBatchConfigurer {

    @Autowired
    private JobBuilderFactory jobs;

    @Autowired
    private StepBuilderFactory steps;

    @Autowired
    EventReader reader;

    @Autowired
    private EventProcessor processor;

    @Autowired
    private EventWriter writer;

    @Bean
    protected Step step1(ThreadPoolTaskExecutor executor) {
        DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
        attribute.setPropagationBehavior(Propagation.REQUIRED.value());
        attribute.setIsolationLevel(Isolation.DEFAULT.value());
        attribute.setTimeout(30);

        return steps.get("step1")., Map>>chunk(10).reader(reader)
                .processor(processor).writer(writer).transactionAttribute(attribute).build();
    }

    @Bean(name = "firstBatchJob")
    public Job job(@Qualifier("step1") Step step1) {
        return jobs.get("firstBatchJob").start(step1).build();
    }
    }

```

答:
According to your configuration, Spring Batch is not configured to use your JpaTransactionManager, you need to override getTransactionManager, see example here. In your case it should be something like:

```<code>public class TrueBatchConfig extends DefaultBatchConfigurer {

   // ..

    @Override
    public PlatformTransactionManager getTransactionManager() {
        return new JpaTransactionManager(); // TODO set entity manager factory
    }

}
</code>```

Body:
Transaction is not rolling back in spring batch. I am throwing exception intentionally to test transaction roll back. Database transaction is committing even with exception thrown from the item writer.Below is the method in writer which is saving into DB. compEvent object is jpa repository injected into this class

    private void writeCEs(Map> agentMap) throws FailedCompensationException, Exception {

        for (Entry> agent : agentMap.entrySet()) {
            agent.getValue().stream().forEach((ce) -> {
                compEvent.save(ce);
            });
            updateRecordFileStatus(agent.getKey());
            //postToAccounting(agent.getKey(), agent.getValue());
        }
        throw new Exception("Testing XA roolback.... ");
     }

I tried marking transaction for the above method with
@Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
Still it is committing the transaction. I am sure I am missing something. any help would be appreciated.

Below is my batch configuration

       @EnableBatchProcessing
        @EnableTransactionManagement @Configuration @ComponentScan({ "com.pm.*" })

    public class TrueBatchConfig extends DefaultBatchConfigurer {

    @Autowired
    private JobBuilderFactory jobs;

    @Autowired
    private StepBuilderFactory steps;

    @Autowired
    EventReader reader;

    @Autowired
    private EventProcessor processor;

    @Autowired
    private EventWriter writer;

    @Bean
    protected Step step1(ThreadPoolTaskExecutor executor) {
        DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
        attribute.setPropagationBehavior(Propagation.REQUIRED.value());
        attribute.setIsolationLevel(Isolation.DEFAULT.value());
        attribute.setTimeout(30);

        return steps.get("step1")., Map>>chunk(10).reader(reader)
                .processor(processor).writer(writer).transactionAttribute(attribute).build();
    }

    @Bean(name = "firstBatchJob")
    public Job job(@Qualifier("step1") Step step1) {
        return jobs.get("firstBatchJob").start(step1).build();
    }
    }

Body:
According to your configuration, Spring Batch is not configured to use your JpaTransactionManager, you need to override getTransactionManager, see example here. In your case it should be something like:

public class TrueBatchConfig extends DefaultBatchConfigurer {

   // ..

    @Override
    public PlatformTransactionManager getTransactionManager() {
        return new JpaTransactionManager(); // TODO set entity manager factory
    }

}


来源: stackexchange

问:
casts datetime format in Laravel
As the Laravel document, we can cast the value to DateTime.

https://laravel.com/docs/5.8/eloquent-serialization#date-serialization

```<code>protected $casts = [
    'birthday' => 'date:Y-m-d',
    'joined_at' => 'datetime:Y-m-d H:00',
];

</code>```

There result is :

"2020-05-29 00:00:00"
but i want to result like that:

"2020-10-29T00:00"

I can use Carbon with format "Y-m-d\TH:i");

if possible to format like "2020-10-29T00:00" if I don't use the Carbon?

any ideas will be appreciated.

答:
As the Carbon documentation (https://carbon.nesbot.com/docs/#api-formatting) states. You can use format() function.

$dt->format("Y-m-d\TH:i")
```

ContentLicense: CC BY-SA 4.0

Title: casts datetime format in Laravel

Body:
As the Laravel document, we can cast the value to DateTime.

https://laravel.com/docs/5.8/eloquent-serialization#date-serialization

protected $casts = [
    'birthday' => 'date:Y-m-d',
    'joined_at' => 'datetime:Y-m-d H:00',
];

There result is :

"2020-05-29 00:00:00"
but i want to result like that:

"2020-10-29T00:00"

I can use Carbon with format "Y-m-d\TH:i");

if possible to format like "2020-10-29T00:00" if I don't use the Carbon?

any ideas will be appreciated.


问:
Django problem with foreginKey in templates
I am started learning Django and I have question. I have code like this:

```<code>from django.db import models
from django.utils import timezone

class Worker(models.Model):
    firstname = models.CharField(max_length = 32, blank=False, null=False)
    lastname = models.CharField(max_length = 32, blank=False, null=False)

class Computer(models.Model):
    TYPE = {
        (0, 'PC'),
        (1, 'Laptop'),
    }
    workerId = models.ForeignKey(Worker, on_delete=models.SET_NULL, blank=True, null=True)
    prod = models.CharField(max_length = 32, blank=False, null=False)
    type = models.PositiveSmallIntegerField(default=0, choices=TYPE)
</code>```

What I should do in views and templates if I want to do list with workers and theirs computers? One computer can be for one user or for no one but one worker can have a few computers.

My template for this look like:

```<code>{% block site %}
    {% for work in worker %}
        <p>{{ work.id }} {{ work.fullname }}
            {{ work.lastname }}</p><br>
            {% if comp.workerId == work.id%}
                {{ comp }}
            {% else %}
                <p>Empty</p>
            {% endif %}
    {% endfor %}
    {% for c in comp %}
        <p>{{ c }}</p>
    {% endfor %}
{% endblock %}
</code>```

But I always have "Empty". Thanks for help

答:
You can try like this with for-empty in template:

```<code>{% for work in worker %}
    <p>{{ work.id }} {{ work.fullname }}
        {{ work.lastname }}</p><br>
        {% for comp in work.computer_set.all %}
            {{ comp }}
        {% empty %}
            <p>Empty</p>
        {% endfor %}
 {% endfor %}
</code>```

Body:
I am started learning Django and I have question. I have code like this:

from django.db import models
from django.utils import timezone

class Worker(models.Model):
    firstname = models.CharField(max_length = 32, blank=False, null=False)
    lastname = models.CharField(max_length = 32, blank=False, null=False)

class Computer(models.Model):
    TYPE = {
        (0, 'PC'),
        (1, 'Laptop'),
    }
    workerId = models.ForeignKey(Worker, on_delete=models.SET_NULL, blank=True, null=True)
    prod = models.CharField(max_length = 32, blank=False, null=False)
    type = models.PositiveSmallIntegerField(default=0, choices=TYPE)

What I should do in views and templates if I want to do list with workers and theirs computers? One computer can be for one user or for no one but one worker can have a few computers.

My template for this look like:

{% block site %}
    {% for work in worker %}

{{ work.id }} {{ work.fullname }}
            {{ work.lastname }}

            {% if comp.workerId == work.id%}
                {{ comp }}
            {% else %}

Empty

            {% endif %}
    {% endfor %}
    {% for c in comp %}

{{ c }}

    {% endfor %}
{% endblock %}

But I always have "Empty". Thanks for help

Body:
You can try like this with for-empty in template:

{% for work in worker %}
    <p>{{ work.id }} {{ work.fullname }}
        {{ work.lastname }}</p><br>
        {% for comp in work.computer_set.all %}
            {{ comp }}
        {% empty %}
            <p>Empty</p>
        {% endfor %}
 {% endfor %}


问:
How to split a string on multiple delimiters stored in a list?
I have a list of delimiters like

```<code>List<String> delimiters= Arrays.asList(",",".");
</code>```

If I have a string like "a.b,c".

How to split on all the delimiters?

答:
Here is code:</p>

```<code>import java.util.Arrays;
import java.util.List;

public class StringSplitMultipleDelimeter {

    public static void main(String[] args) {
        List<String> delimiters= Arrays.asList(",",".","!","?","$","&","^","%","@");
        String givenString = "Test,String.with?Multiple@delimeters!example";
        //Create Regex to split sting
        StringBuilder regex = new StringBuilder();
        regex.append("[");
        delimiters.forEach(delimeter -> regex.append(delimeter));
        regex.append("]");
        String[] tokens = givenString.split(regex.toString());
        System.out.println("Number of tokens = " + tokens.length);
        for(int i =0; i<tokens.length; i++) {
            System.out.println(tokens[i]);
        }
    }
}
</code>```

Body:
I have a list of delimiters like

List<String> delimiters= Arrays.asList(",",".");

If I have a string like "a.b,c".

How to split on all the delimiters?

Body:
Here is code:

import java.util.Arrays;
import java.util.List;

public class StringSplitMultipleDelimeter {

    public static void main(String[] args) {
        List<String> delimiters= Arrays.asList(",",".","!","?","$","&","^","%","@");
        String givenString = "Test,String.with?Multiple@delimeters!example";
        //Create Regex to split sting
        StringBuilder regex = new StringBuilder();
        regex.append("[");
        delimiters.forEach(delimeter -> regex.append(delimeter));
        regex.append("]");
        String[] tokens = givenString.split(regex.toString());
        System.out.println("Number of tokens = " + tokens.length);
        for(int i =0; i<tokens.length; i++) {
            System.out.println(tokens[i]);
        }
    }
}


问:
Highchart spline Cut Off when reach to maximum scale value. How can it fixed?. I have attached may sample code on body
I'm making use if the highcharts plugin to make a chart. But I'm running into some problems.
My Highchart spline is cut off when reach to maximum scale value. How is this possible and how can it be fixed?

I have created a sample demo for this chart and also attached the screenshot to point of the cutoff spline.
Here is my demo code:

let chartdata = [];
let A = [95, 95, 95];
let B = [50, 100, 100];

var colorBand = [{
    color: "red",
    to: 0,
    from: 20
  },
  {
    color: "green",
    to: 21,
    from: 40
  },
  {
    color: "blue",
    to: 41,
    from: 60
  },
  {
    color: "orange",
    to: 61,
    from: 90
  },
  {
    color: "yellow",
    to: 91,
    from: 100
  },
];

chartdata.push({
  name: 'A',
  type: 'column',
  date: 'A',
  data: A,
  color: 'red',
});

chartdata.push({
  name: 'B',
  type: 'spline',
  date: 'B',
  data: B,
  color: 'blue'
});

Highcharts.chart('container', {
  chart: {
    height: 205,
    width: 200,
    background: '#F2F2F2'
  },
  title: {
    text: ''
  },
  credits: {
    enabled: false
  },
  legend: {
    align: "center",
    layout: "horizontal",
    verticalAlign: "bottom",
    symbolHeight: 10,
    symbolWidth: 10,
    symbolRadius: 0,
    itemStyle: {
      fontSize: "13px",
      fontWeight: 'bold',
      fontFamily: '"Arial", sans-serif'
    }
  },
  xAxis: {
    labels: {
      style: {
        fontSize: "11px",
        fontFamily: '"Arial", sans-serif',
        color: "#000"
      }
    },
    gridLineColor: "transparent",
    gridLineWidth: 0,
    minorGridLineWidth: 0,
    lineColor: "#9A9A9A",
    zIndex: 9999999,
    minorTickLength: 0,
    tickLength: 0,
    style: {
      fontSize: "11px",
      fontWeight: "bold",
      fontFamily: '"Arial", sans-serif',
      color: "#000"
    }
  },

  yAxis: [{
      gridLineWidth: 0,
      labels: {
        style: {
          fontSize: "12px",
          color: "#000",
          fontFamily: '"Arial", sans-serif'
        }
      },
      title: {
        text: ''
      },
      min: 0,
      plotBands: colorBand,
      width: 20,
      max: 100,
      tickInterval: 20
    },
    {
      linkedTo: 0,
      gridLineWidth: 0,
      lineColor: "transparent",
      title: {
        text: ""
      },
      labels: {
        enabled: false
      }
    }
  ],
  plotOptions: {
    series: {
      states: {
        hover: {
          enabled: false,
        },
        inactive: {
          opacity: 1
        }
      },
      pointPadding: 0.1,
      groupPadding: 0,
      lineWidth: 5,
      pointWidth: 25,
      enableMouseTracking: false,
      borderWidth: 1,
      borderColor: '#FFFFFF',
      threshold: 0, // let zero values have some height
      marker: {
        enabled: false,
        states: {
          hover: {
            //radius: 1
          }
        }
      },
      minPointLength: 10,
      events: {
        legendItemClick: function() {
          return false;
        }
      }
    }
  },
  series: chartdata
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container"></div></code>```

Here I pointed out the cutline

enter image description here

答:
I think the cut line comes from the fact that you have a 5px lineWidth in your config. So in order to have the line not cut, you need to put it a 3px below where it is now, so that it has 2 pixels on top available (2pixels top + 2 pixels bottom + its pixel position = 5 pixels).

let B = [97,97,97];

jsfiddle: https://jsfiddle.net/8w5roqpt/

Note that you could also increase the max size of your graph (yAxis.max): https://jsfiddle.net/sk4n9gp0/

Body:
I'm making use if the highcharts plugin to make a chart. But I'm running into some problems.
My Highchart spline is cut off when reach to maximum scale value. How is this possible and how can it be fixed?

I have created a sample demo for this chart and also attached the screenshot to point of the cutoff spline.
Here is my demo code:

let chartdata = [];
let A = [95, 95, 95];
let B = [50, 100, 100];

var colorBand = [{
    color: "red",
    to: 0,
    from: 20
  },
  {
    color: "green",
    to: 21,
    from: 40
  },
  {
    color: "blue",
    to: 41,
    from: 60
  },
  {
    color: "orange",
    to: 61,
    from: 90
  },
  {
    color: "yellow",
    to: 91,
    from: 100
  },
];

chartdata.push({
  name: 'A',
  type: 'column',
  date: 'A',
  data: A,
  color: 'red',
});

chartdata.push({
  name: 'B',
  type: 'spline',
  date: 'B',
  data: B,
  color: 'blue'
});

Highcharts.chart('container', {
  chart: {
    height: 205,
    width: 200,
    background: '#F2F2F2'
  },
  title: {
    text: ''
  },
  credits: {
    enabled: false
  },
  legend: {
    align: "center",
    layout: "horizontal",
    verticalAlign: "bottom",
    symbolHeight: 10,
    symbolWidth: 10,
    symbolRadius: 0,
    itemStyle: {
      fontSize: "13px",
      fontWeight: 'bold',
      fontFamily: '"Arial", sans-serif'
    }
  },
  xAxis: {
    labels: {
      style: {
        fontSize: "11px",
        fontFamily: '"Arial", sans-serif',
        color: "#000"
      }
    },
    gridLineColor: "transparent",
    gridLineWidth: 0,
    minorGridLineWidth: 0,
    lineColor: "#9A9A9A",
    zIndex: 9999999,
    minorTickLength: 0,
    tickLength: 0,
    style: {
      fontSize: "11px",
      fontWeight: "bold",
      fontFamily: '"Arial", sans-serif',
      color: "#000"
    }
  },

  yAxis: [{
      gridLineWidth: 0,
      labels: {
        style: {
          fontSize: "12px",
          color: "#000",
          fontFamily: '"Arial", sans-serif'
        }
      },
      title: {
        text: ''
      },
      min: 0,
      plotBands: colorBand,
      width: 20,
      max: 100,
      tickInterval: 20
    },
    {
      linkedTo: 0,
      gridLineWidth: 0,
      lineColor: "transparent",
      title: {
        text: ""
      },
      labels: {
        enabled: false
      }
    }
  ],
  plotOptions: {
    series: {
      states: {
        hover: {
          enabled: false,
        },
        inactive: {
          opacity: 1
        }
      },
      pointPadding: 0.1,
      groupPadding: 0,
      lineWidth: 5,
      pointWidth: 25,
      enableMouseTracking: false,
      borderWidth: 1,
      borderColor: '#FFFFFF',
      threshold: 0, // let zero values have some height
      marker: {
        enabled: false,
        states: {
          hover: {
            //radius: 1
          }
        }
      },
      minPointLength: 10,
      events: {
        legendItemClick: function() {
          return false;
        }
      }
    }
  },
  series: chartdata
});

Here I pointed out the cutline

enter image description here


问:
jq how to merge array objects into single object
in jq its possible to add objects using the + operator

if you have an array

```<code> [
      {
        "a": "value"
      },
      {
        "b": "value"
      },
      {
        "c": "value"
      }
 ]
</code>```

I want to convert it into a single object { a:"value", b:"value", c:"value" }
I can use the following filter .[0] + .[1] + .[2], but i want to do it for the whole array without specifying all the indexes.

答:
You can use reduce:

```<code>reduce .[] as $o ({}; . + $o)
</code>```

returns:

```<code>{
  "a": "value",
  "b": "value",
  "c": "value"
}
</code>```

Body:
in jq its possible to add objects using the + operator

if you have an array

 [
      {
        "a": "value"
      },
      {
        "b": "value"
      },
      {
        "c": "value"
      }
 ]

I want to convert it into a single object { a:"value", b:"value", c:"value" }
I can use the following filter .[0] + .[1] + .[2], but i want to do it for the whole array without specifying all the indexes.

Body:
You can use reduce:

reduce .[] as $o ({}; . + $o)

returns:

{
  "a": "value",
  "b": "value",
  "c": "value"
}


问:
create hierarchy of folders, and set permissions
mkdir has options:

-p that creates all parent directories if missing

-m which changes user rights.

Problem for me is, that -m 755 is applied only to the leaf directory.

mkdir -m 755 -p a/b/c -> c has mode 755 but a and a/b have modes 700. (I want a and a/b to be also 755)

Is there easy solution? (or just iterate over parents and chmod each?)

答:
That is a bit unexpected behaviour from mkdir, I would also assume the -m flag would have effect on all created directories, not just the leaf node.

I see two easy ways to do this:

$ (umask 022; mkdir -p a/b/c)

$ install -d -m 755 a/b/c

The umask controls all file creation done by the shell and is a mask of the permission bits set (this makes the values a bit hard to use).  Putting the two commands in parenthesis means it will only have effect for that sub shell.

Using the install tool is another option.  With the -d option, it behaves the same way as mkdir -p, but the -m flag will be used for all directories, not just the leaf node.  install is part of the coreutils package, and will most likely be available on any system.


问:
How to get sum of time values in SQLite DATETIME field
How can get sum of time values stored as hh:mm format in a datetime field in SQLite? I have tried solution given at sqlite: how to add total time hh:mm:ss where column datatype is DATETIME? and it gives me same result as I get in Excel. But if I count manually one by one, the answer is 44 hours and 49 minutes. But both, excel and the query derived from the solution given at above URL give the answer as 20 hours and 49 minutes. I am including the query which I use.

Query:

```<code>select time(sum(strftime('%s',appUsageTime)-strftime('%s','00:00')),'unixepoch')
from offlineAppsUsageHistory
WHERE appId=3;
</code>```

Unable to add Excel screenshot but the time values in the appUsageTime field are as follows:

```<code>01:27
01:10
01:21
00:54
01:28
01:53
01:29
03:30
02:11
03:38
02:40
02:07
03:04
02:42
02:24
02:16
02:05
01:46
02:41
01:13
02:07
00:43
</code>```

答:
Because your sum exceeds 24 hours, time just returns the part that is not a whole day. Thus you get a result of 20:49 instead of 44:49 as 20:49 is 44:49 - 24:00. One way to display the total hours and minutes would be to use printf on the sum instead:

```<code>SELECT printf('%d:%02d', totsec / 3600, (totsec % 3600) / 60) AS total
FROM (
  SELECT sum(strftime('%s',appUsageTime)-strftime('%s','00:00')) AS totsec
  FROM offlineAppsUsageHistory
  WHERE appId=3
) h
</code>```

Output:

```<code>total
44:49
</code>```

Demo on dbfiddle

Body:
How can get sum of time values stored as hh:mm format in a datetime field in SQLite? I have tried solution given at sqlite: how to add total time hh:mm:ss where column datatype is DATETIME? and it gives me same result as I get in Excel. But if I count manually one by one, the answer is 44 hours and 49 minutes. But both, excel and the query derived from the solution given at above URL give the answer as 20 hours and 49 minutes. I am including the query which I use.

Query:

select time(sum(strftime('%s',appUsageTime)-strftime('%s','00:00')),'unixepoch')
from offlineAppsUsageHistory
WHERE appId=3;

Unable to add Excel screenshot but the time values in the appUsageTime field are as follows:

01:27
01:10
01:21
00:54
01:28
01:53
01:29
03:30
02:11
03:38
02:40
02:07
03:04
02:42
02:24
02:16
02:05
01:46
02:41
01:13
02:07
00:43

Body:
Because your sum exceeds 24 hours, time just returns the part that is not a whole day. Thus you get a result of 20:49 instead of 44:49 as 20:49 is 44:49 - 24:00. One way to display the total hours and minutes would be to use printf on the sum instead:

SELECT printf('%d:%02d', totsec / 3600, (totsec % 3600) / 60) AS total
FROM (
  SELECT sum(strftime('%s',appUsageTime)-strftime('%s','00:00')) AS totsec
  FROM offlineAppsUsageHistory
  WHERE appId=3
) h

Output:

total
44:49

Demo on dbfiddle


问:
jquery $.each() for objects
```<code><script>
    $(document).ready(function() {
        var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };
        $.each(data.programs[0], function(key,val) {
            alert(key+val);
        });
    });
</script>
</code>```

This code retrieves the first data. name:zonealarm and price:500.

How can I retrieve all the data in the object?

I tried $.each(data.programs, function(key,val) but it didn't work.

Should I put it in a loop?

答:
Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.

You have programs: [ {...}, {...} ]
so programs[0] is { "name":"zonealarm", "price":"500" }
So your loop is just going over that.

You could do an outer loop over the array

```<code>$.each(data.programs, function(index) {

    // then loop over the object elements
    $.each(data.programs[index], function(key, value) {
        console.log(key + ": " + value);
    }

}
</code>```

Title: jquery $.each() for objects

Body:
Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.

You have programs: [ {...}, {...} ]
so programs[0] is { "name":"zonealarm", "price":"500" }
So your loop is just going over that.

You could do an outer loop over the array

$.each(data.programs, function(index) {

    // then loop over the object elements
    $.each(data.programs[index], function(key, value) {
        console.log(key + ": " + value);
    }

}

ContentLicense: CC BY-SA 3.0


问:
Deno - How to fetch data from distant API or URL?
I'm wondering how I can get data from other servers and API with deno ? Everything in the documentation teach me about making http servers and read files from local source. But I can't find anything useful about reading something on the network.

How can read JSON data from the Stripe API ? Or if I want to read a HTML file with text inside ?

Thank you for your time!

答:
I am just giving you an example of the GET request for fetching repositories of Github.

You can change the URL and Request Configuration as per your need.

In the code given below, I am calling another API of Github. By using the fetch() method you can do that.

fetch() method first takes the URL as the first parameter and the next parameter is RequestInit which takes the request method type, headers, body, etc and at the end returning JSON response of that API call.

```<code>const githubResponse = async (): Promise<any> => {
    const response = await fetch("https://api.github.com/search/repositories?q=android", {
        method: "GET",
        headers: {
            "Content-Type": "application/json",
        },
    });
    return response.json(); // For JSON Response
    //   return response.text(); // For HTML or Text Response
}

console.log(await githubResponse());
</code>```

I have written the above code in a ts file named Testing.ts . So, you can run the above code by the command given below:

```<code>deno run --allow-net Testing.ts
</code>```

Next, I am giving you a sample POST request code:

```<code>const githubResponse = async (): Promise<any> => {
    const body: URLSearchParams = new URLSearchParams({
        q: "AvijitKarmakar",
    });

    const response = await fetch("https://api.github.com/search/repositories", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: body
    });
    return response.json();
    //   return response.text(); // For HTML or Text Response
}

console.log(await githubResponse());
</code>```

You can see that I have created a body object and passed it in the RequestInit through the body parameter and also changed the request method type to POST.

Body:
I am just giving you an example of the GET request for fetching repositories of Github.

You can change the URL and Request Configuration as per your need.

In the code given below, I am calling another API of Github. By using the fetch() method you can do that.

fetch() method first takes the URL as the first parameter and the next parameter is RequestInit which takes the request method type, headers, body, etc and at the end returning JSON response of that API call.

const githubResponse = async (): Promise<any> => {
    const response = await fetch("https://api.github.com/search/repositories?q=android", {
        method: "GET",
        headers: {
            "Content-Type": "application/json",
        },
    });
    return response.json(); // For JSON Response
    //   return response.text(); // For HTML or Text Response
}

console.log(await githubResponse());

I have written the above code in a ts file named Testing.ts . So, you can run the above code by the command given below:

deno run --allow-net Testing.ts

Next, I am giving you a sample POST request code:

const githubResponse = async (): Promise<any> => {
    const body: URLSearchParams = new URLSearchParams({
        q: "AvijitKarmakar",
    });

    const response = await fetch("https://api.github.com/search/repositories", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: body
    });
    return response.json();
    //   return response.text(); // For HTML or Text Response
}

console.log(await githubResponse());

You can see that I have created a body object and passed it in the RequestInit through the body parameter and also changed the request method type to POST.


问:
Use of Take() LINQ Method in Entity Framework Core v3.1.4
I'm trying to add a limit GET query parameter in my API request (i.e. ?limit=10) and the value of this limit will then be used by the Take() LINQ method to get only the number of results I want. What I want to do is to include the LINQ Take() method as part of the LINQ-TO-T-SQL query and perform the limit as part of the SQL query. I tried the following codes below. I also captured the error stack trace.

Code 1: For this code, I'm trying to use the Take() on my top level resource in the query. Then afterwards (in the declaration of q), I'm performing sub-queries related to the top level resource.

```<code>baseQuery = baseQuery.Take(2);

var q = from doctor in baseQuery

        let sp = (from ds in db.DoctorSpecialty
                  join s in db.Specialty on ds.SpecialtyID equals s.SpecialtyID
                  where ds.DoctorID == doctor.DoctorID
                  select new
                  {
                      s.SpecialtyID,
                      s.Specialty1
                  }).ToList()

        let clinics = (from c in db.Clinic
                  where c.DoctorID == doctor.DoctorID && c.Active == true

                  let schedule = (from sc in db.Schedule
                                  where sc.ClinicID == c.ClinicID
                                    && sc.DoctorID == doctor.DoctorID
                                    && DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
                                  select sc).ToList()

                  select new
                  {
                      c.ClinicID,
                      c.Street,
                      c.ClinicName,
                      c.ContactNumber,
                      c.City,
                      c.Province,
                      c.HomeNumber,
                      c.MobileNumber,
                      c.WorkNumber,
                      c.Email,
                      Schedules = schedule,
                  }).ToList()
        select new
        {
            Doctor = doctor,
            Specialties = sp,
            Clinics = clinics

        };

var rs = q.ToList();
</code>```

Error stack trace for code 1:

```<code>fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
      Failed executing DbCommand (5ms) [Parameters=[@__p_0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
      SELECT [t].[DoctorID], [t].[Address], [t].[AvailableInvites], [t].[Birthdate], [t].[City], [t].[CityID], [t].[ContactNumber], [t].[Country], [t].[DateRegistered], [t].[Description], [t].[DoctorUrl], [t].[Email], [t].[EmailActivated], [t].[EmailUID], [t].[EmailVerifiedFirstTime], [t].[Facebook], [t].[FirstName], [t].[Gender], [t].[GooglePlus], [t].[HomeNumber], [t].[Image], [t].[LastName], [t].[LinkedIn], [t].[MainSpecialty], [t].[ManuallyVerified], [t].[MedicalSchool], [t].[MedicalSchoolYear], [t].[MiddleName], [t].[MobileNumber], [t].[Nationality], [t].[OriginalIssueDate], [t].[PRCNumber], [t].[PageOkay], [t].[PatientNumber], [t].[PhicNumber], [t].[PractisingSince], [t].[Province], [t].[PtrNumber], [t].[Residency], [t].[ResidencyYear], [t].[S2Number], [t].[ShowPublicProfile], [t].[Status], [t].[Street], [t].[Suffix], [t].[Title], [t].[Twitter], [t].[UserID], [t].[Website], [t].[WorkNumber], [t].[Zipcode], [t0].[SpecialtyID], [t0].[Specialty], [t0].[Id], [t2].[ClinicID], [t2].[Street], [t2].[ClinicName], [t2].[ContactNumber], [t2].[City], [t2].[Province], [t2].[HomeNumber], [t2].[MobileNumber], [t2].[WorkNumber], [t2].[Email], [t2].[ScheduleID], [t2].[Active], [t2].[ClinicID0], [t2].[DateModified], [t2].[DayOfWeek], [t2].[DoctorID], [t2].[Notes], [t2].[StartFrom], [t2].[TimeEnd], [t2].[TimeStart], [t2].[Until]
      FROM (
          SELECT TOP(@__p_0) [d].[DoctorID], [d].[Address], [d].[AvailableInvites], [d].[Birthdate], [d].[City], [d].[CityID], [d].[ContactNumber], [d].[Country], [d].[DateRegistered], [d].[Description], [d].[DoctorUrl], [d].[Email], [d].[EmailActivated], [d].[EmailUID], [d].[EmailVerifiedFirstTime], [d].[Facebook], [d].[FirstName], [d].[Gender], [d].[GooglePlus], [d].[HomeNumber], [d].[Image], [d].[LastName], [d].[LinkedIn], [d].[MainSpecialty], [d].[ManuallyVerified], [d].[MedicalSchool], [d].[MedicalSchoolYear], [d].[MiddleName], [d].[MobileNumber], [d].[Nationality], [d].[OriginalIssueDate], [d].[PRCNumber], [d].[PageOkay], [d].[PatientNumber], [d].[PhicNumber], [d].[PractisingSince], [d].[Province], [d].[PtrNumber], [d].[Residency], [d].[ResidencyYear], [d].[S2Number], [d].[ShowPublicProfile], [d].[Status], [d].[Street], [d].[Suffix], [d].[Title], [d].[Twitter], [d].[UserID], [d].[Website], [d].[WorkNumber], [d].[Zipcode]
          FROM [Doctor] AS [d]
          WHERE [d].[Status] = 'good'
      ) AS [t]
      LEFT JOIN (
          SELECT [s].[SpecialtyID], [s].[Specialty], [d0].[Id], [d0].[DoctorID]
          FROM [DoctorSpecialty] AS [d0]
          INNER JOIN [Specialty] AS [s] ON [d0].[SpecialtyID] = [s].[SpecialtyID]
      ) AS [t0] ON [t].[DoctorID] = [t0].[DoctorID]
      LEFT JOIN (
          SELECT [c].[ClinicID], [c].[Street], [c].[ClinicName], [c].[ContactNumber], [c].[City], [c].[Province], [c].[HomeNumber], [c].[MobileNumber], [c].[WorkNumber], [c].[Email], [t1].[ScheduleID], [t1].[Active], [t1].[ClinicID] AS [ClinicID0], [t1].[DateModified], [t1].[DayOfWeek], [t1].[DoctorID], [t1].[Notes], [t1].[StartFrom], [t1].[TimeEnd], [t1].[TimeStart], [t1].[Until], [c].[DoctorID] AS [DoctorID0]
          FROM [Clinic] AS [c]
          LEFT JOIN (
              SELECT [s0].[ScheduleID], [s0].[Active], [s0].[ClinicID], [s0].[DateModified], [s0].[DayOfWeek], [s0].[DoctorID], [s0].[Notes], [s0].[StartFrom], [s0].[TimeEnd], [s0].[TimeStart], [s0].[Until]
              FROM [Schedule] AS [s0]
              WHERE ([s0].[DoctorID] = [d].[DoctorID]) AND [s0].[Notes] IN (N'Walk-In', N'By Appointment')
          ) AS [t1] ON [c].[ClinicID] = [t1].[ClinicID]
          WHERE [c].[Active] = CAST(1 AS bit)
      ) AS [t2] ON [t].[DoctorID] = [t2].[DoctorID0]
      ORDER BY [t].[DoctorID], [t0].[Id], [t0].[SpecialtyID], [t2].[ClinicID], [t2].[ScheduleID]
fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'SeriousMDCommonsCore.Models.Database.SeriousmdEntitiesContext'.
      Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
         at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
         at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
         at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
         at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
         at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
         at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
         at System.Data.Common.DbCommand.ExecuteReader()
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
      ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
      Error Number:4104,State:1,Class:16
Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
   at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
Error Number:4104,State:1,Class:16
fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HM03JVLBFS8O", Request id "0HM03JVLBFS8O:00000001": An unhandled exception was thrown by the application.
Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
   at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
Error Number:4104,State:1,Class:16
</code>```

Code 2: Here, instead of performing the Take() in the baseQuery, I'm performing the Take() in the final query expression q. I also added a doctor.DoctorID as some sort of id that I think is required to be fed to the Take() LINQ method

```<code>var q = from doctor in baseQuery

        let sp = (from ds in db.DoctorSpecialty
                  join s in db.Specialty on ds.SpecialtyID equals s.SpecialtyID
                  where ds.DoctorID == doctor.DoctorID
                  select new
                  {
                      s.SpecialtyID,
                      s.Specialty1
                  }).ToList()

        let clinics = (from c in db.Clinic
                  where c.DoctorID == doctor.DoctorID && c.Active == true

                  let schedule = (from sc in db.Schedule
                                  where sc.ClinicID == c.ClinicID
                                    && sc.DoctorID == doctor.DoctorID
                                    && DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
                                  select sc).ToList()

                  select new
                  {
                      c.ClinicID,
                      c.Street,
                      c.ClinicName,
                      c.ContactNumber,
                      c.City,
                      c.Province,
                      c.HomeNumber,
                      c.MobileNumber,
                      c.WorkNumber,
                      c.Email,
                      Schedules = schedule,
                  }).ToList()
        select new
        {
            doctor.DoctorID,
            Doctor = doctor,
            Specialties = sp,
            Clinics = clinics

        };

q = q.Take(2);

var rs = q.ToList();
</code>```

Error stack trace for code 2: Here, the error changed from that of code 2 and it seems that the added index is being used by the Take() LINQ method but still throws an error.

```<code>fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HM03K296O68T", Request id "0HM03K296O68T:00000001": An unhandled exception was thrown by the application.
System.InvalidOperationException: Processing of the LINQ expression '(ProjectionBindingExpression: 0)' by 'RelationalProjectionBindingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitExtension(Expression extensionExpression)
   at System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitNew(NewExpression newExpression)
   at System.Linq.Expressions.NewExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Translate(SelectExpression selectExpression, Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateSelect(ShapedQueryExpression source, LambdaExpression selector)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
</code>```

Back to my question, how can I integrate the Take() LINQ method as part of my LINQ-TO-T-SQL query so that all of my queries will go through EF Core and all query operations will be performed in database?

答:
Code 3: This version of my code successfully returns the number of results I wanted via the Take() LINQ method. However, the Take() is being performed on data / collection that is already loaded in the client side or in memory. So this Take() performs a LINQ-TO-Collections query instead of LINQ-TO-T-SQL and doesn't go through EF Core.

```<code>var q = from doctor in baseQuery

        let sp = (from ds in db.DoctorSpecialty
                  join s in db.Specialty on ds.SpecialtyID equals s.SpecialtyID
                  where ds.DoctorID == doctor.DoctorID
                  select new
                  {
                      s.SpecialtyID,
                      s.Specialty1
                  }).ToList()

        let clinics = (from c in db.Clinic
                  where c.DoctorID == doctor.DoctorID && c.Active == true

                  let schedule = (from sc in db.Schedule
                                  where sc.ClinicID == c.ClinicID
                                    && sc.DoctorID == doctor.DoctorID
                                    && DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
                                  select sc).ToList()

                  select new
                  {
                      c.ClinicID,
                      c.Street,
                      c.ClinicName,
                      c.ContactNumber,
                      c.City,
                      c.Province,
                      c.HomeNumber,
                      c.MobileNumber,
                      c.WorkNumber,
                      c.Email,
                      Schedules = schedule,
                  }).ToList()
        select new
        {
            Doctor = doctor,
            Specialties = sp,
            Clinics = clinics

        };

var rs = q.ToList();

rs = rs.AsEnumerable().Take(2).ToList();
</code>```

Body:
I'm trying to add a limit GET query parameter in my API request (i.e. ?limit=10) and the value of this limit will then be used by the Take() LINQ method to get only the number of results I want. What I want to do is to include the LINQ Take() method as part of the LINQ-TO-T-SQL query and perform the limit as part of the SQL query. I tried the following codes below. I also captured the error stack trace.

Code 1: For this code, I'm trying to use the Take() on my top level resource in the query. Then afterwards (in the declaration of q), I'm performing sub-queries related to the top level resource.

baseQuery = baseQuery.Take(2);

var q = from doctor in baseQuery

        let sp = (from ds in db.DoctorSpecialty
                  join s in db.Specialty on ds.SpecialtyID equals s.SpecialtyID
                  where ds.DoctorID == doctor.DoctorID
                  select new
                  {
                      s.SpecialtyID,
                      s.Specialty1
                  }).ToList()

        let clinics = (from c in db.Clinic
                  where c.DoctorID == doctor.DoctorID && c.Active == true

                  let schedule = (from sc in db.Schedule
                                  where sc.ClinicID == c.ClinicID
                                    && sc.DoctorID == doctor.DoctorID
                                    && DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
                                  select sc).ToList()

                  select new
                  {
                      c.ClinicID,
                      c.Street,
                      c.ClinicName,
                      c.ContactNumber,
                      c.City,
                      c.Province,
                      c.HomeNumber,
                      c.MobileNumber,
                      c.WorkNumber,
                      c.Email,
                      Schedules = schedule,
                  }).ToList()
        select new
        {
            Doctor = doctor,
            Specialties = sp,
            Clinics = clinics

        };

var rs = q.ToList();

Error stack trace for code 1:

fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
      Failed executing DbCommand (5ms) [Parameters=[@__p_0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
      SELECT [t].[DoctorID], [t].[Address], [t].[AvailableInvites], [t].[Birthdate], [t].[City], [t].[CityID], [t].[ContactNumber], [t].[Country], [t].[DateRegistered], [t].[Description], [t].[DoctorUrl], [t].[Email], [t].[EmailActivated], [t].[EmailUID], [t].[EmailVerifiedFirstTime], [t].[Facebook], [t].[FirstName], [t].[Gender], [t].[GooglePlus], [t].[HomeNumber], [t].[Image], [t].[LastName], [t].[LinkedIn], [t].[MainSpecialty], [t].[ManuallyVerified], [t].[MedicalSchool], [t].[MedicalSchoolYear], [t].[MiddleName], [t].[MobileNumber], [t].[Nationality], [t].[OriginalIssueDate], [t].[PRCNumber], [t].[PageOkay], [t].[PatientNumber], [t].[PhicNumber], [t].[PractisingSince], [t].[Province], [t].[PtrNumber], [t].[Residency], [t].[ResidencyYear], [t].[S2Number], [t].[ShowPublicProfile], [t].[Status], [t].[Street], [t].[Suffix], [t].[Title], [t].[Twitter], [t].[UserID], [t].[Website], [t].[WorkNumber], [t].[Zipcode], [t0].[SpecialtyID], [t0].[Specialty], [t0].[Id], [t2].[ClinicID], [t2].[Street], [t2].[ClinicName], [t2].[ContactNumber], [t2].[City], [t2].[Province], [t2].[HomeNumber], [t2].[MobileNumber], [t2].[WorkNumber], [t2].[Email], [t2].[ScheduleID], [t2].[Active], [t2].[ClinicID0], [t2].[DateModified], [t2].[DayOfWeek], [t2].[DoctorID], [t2].[Notes], [t2].[StartFrom], [t2].[TimeEnd], [t2].[TimeStart], [t2].[Until]
      FROM (
          SELECT TOP(@__p_0) [d].[DoctorID], [d].[Address], [d].[AvailableInvites], [d].[Birthdate], [d].[City], [d].[CityID], [d].[ContactNumber], [d].[Country], [d].[DateRegistered], [d].[Description], [d].[DoctorUrl], [d].[Email], [d].[EmailActivated], [d].[EmailUID], [d].[EmailVerifiedFirstTime], [d].[Facebook], [d].[FirstName], [d].[Gender], [d].[GooglePlus], [d].[HomeNumber], [d].[Image], [d].[LastName], [d].[LinkedIn], [d].[MainSpecialty], [d].[ManuallyVerified], [d].[MedicalSchool], [d].[MedicalSchoolYear], [d].[MiddleName], [d].[MobileNumber], [d].[Nationality], [d].[OriginalIssueDate], [d].[PRCNumber], [d].[PageOkay], [d].[PatientNumber], [d].[PhicNumber], [d].[PractisingSince], [d].[Province], [d].[PtrNumber], [d].[Residency], [d].[ResidencyYear], [d].[S2Number], [d].[ShowPublicProfile], [d].[Status], [d].[Street], [d].[Suffix], [d].[Title], [d].[Twitter], [d].[UserID], [d].[Website], [d].[WorkNumber], [d].[Zipcode]
          FROM [Doctor] AS [d]
          WHERE [d].[Status] = 'good'
      ) AS [t]
      LEFT JOIN (
          SELECT [s].[SpecialtyID], [s].[Specialty], [d0].[Id], [d0].[DoctorID]
          FROM [DoctorSpecialty] AS [d0]
          INNER JOIN [Specialty] AS [s] ON [d0].[SpecialtyID] = [s].[SpecialtyID]
      ) AS [t0] ON [t].[DoctorID] = [t0].[DoctorID]
      LEFT JOIN (
          SELECT [c].[ClinicID], [c].[Street], [c].[ClinicName], [c].[ContactNumber], [c].[City], [c].[Province], [c].[HomeNumber], [c].[MobileNumber], [c].[WorkNumber], [c].[Email], [t1].[ScheduleID], [t1].[Active], [t1].[ClinicID] AS [ClinicID0], [t1].[DateModified], [t1].[DayOfWeek], [t1].[DoctorID], [t1].[Notes], [t1].[StartFrom], [t1].[TimeEnd], [t1].[TimeStart], [t1].[Until], [c].[DoctorID] AS [DoctorID0]
          FROM [Clinic] AS [c]
          LEFT JOIN (
              SELECT [s0].[ScheduleID], [s0].[Active], [s0].[ClinicID], [s0].[DateModified], [s0].[DayOfWeek], [s0].[DoctorID], [s0].[Notes], [s0].[StartFrom], [s0].[TimeEnd], [s0].[TimeStart], [s0].[Until]
              FROM [Schedule] AS [s0]
              WHERE ([s0].[DoctorID] = [d].[DoctorID]) AND [s0].[Notes] IN (N'Walk-In', N'By Appointment')
          ) AS [t1] ON [c].[ClinicID] = [t1].[ClinicID]
          WHERE [c].[Active] = CAST(1 AS bit)
      ) AS [t2] ON [t].[DoctorID] = [t2].[DoctorID0]
      ORDER BY [t].[DoctorID], [t0].[Id], [t0].[SpecialtyID], [t2].[ClinicID], [t2].[ScheduleID]
fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'SeriousMDCommonsCore.Models.Database.SeriousmdEntitiesContext'.
      Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
         at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
         at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
         at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
         at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
         at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
         at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
         at System.Data.Common.DbCommand.ExecuteReader()
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
      ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
      Error Number:4104,State:1,Class:16
Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
   at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
Error Number:4104,State:1,Class:16
fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HM03JVLBFS8O", Request id "0HM03JVLBFS8O:00000001": An unhandled exception was thrown by the application.
Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
   at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
Error Number:4104,State:1,Class:16

Code 2: Here, instead of performing the Take() in the baseQuery, I'm performing the Take() in the final query expression q. I also added a doctor.DoctorID as some sort of id that I think is required to be fed to the Take() LINQ method

var q = from doctor in baseQuery

        let sp = (from ds in db.DoctorSpecialty
                  join s in db.Specialty on ds.SpecialtyID equals s.SpecialtyID
                  where ds.DoctorID == doctor.DoctorID
                  select new
                  {
                      s.SpecialtyID,
                      s.Specialty1
                  }).ToList()

        let clinics = (from c in db.Clinic
                  where c.DoctorID == doctor.DoctorID && c.Active == true

                  let schedule = (from sc in db.Schedule
                                  where sc.ClinicID == c.ClinicID
                                    && sc.DoctorID == doctor.DoctorID
                                    && DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
                                  select sc).ToList()

                  select new
                  {
                      c.ClinicID,
                      c.Street,
                      c.ClinicName,
                      c.ContactNumber,
                      c.City,
                      c.Province,
                      c.HomeNumber,
                      c.MobileNumber,
                      c.WorkNumber,
                      c.Email,
                      Schedules = schedule,
                  }).ToList()
        select new
        {
            doctor.DoctorID,
            Doctor = doctor,
            Specialties = sp,
            Clinics = clinics

        };

q = q.Take(2);

var rs = q.ToList();

Error stack trace for code 2: Here, the error changed from that of code 2 and it seems that the added index is being used by the Take() LINQ method but still throws an error.

fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HM03K296O68T", Request id "0HM03K296O68T:00000001": An unhandled exception was thrown by the application.
System.InvalidOperationException: Processing of the LINQ expression '(ProjectionBindingExpression: 0)' by 'RelationalProjectionBindingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitExtension(Expression extensionExpression)
   at System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitNew(NewExpression newExpression)
   at System.Linq.Expressions.NewExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Translate(SelectExpression selectExpression, Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateSelect(ShapedQueryExpression source, LambdaExpression selector)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)

Back to my question, how can I integrate the Take() LINQ method as part of my LINQ-TO-T-SQL query so that all of my queries will go through EF Core and all query operations will be performed in database?

Body:
Code 3: This version of my code successfully returns the number of results I wanted via the Take() LINQ method. However, the Take() is being performed on data / collection that is already loaded in the client side or in memory. So this Take() performs a LINQ-TO-Collections query instead of LINQ-TO-T-SQL and doesn't go through EF Core.

var q = from doctor in baseQuery

        let sp = (from ds in db.DoctorSpecialty
                  join s in db.Specialty on ds.SpecialtyID equals s.SpecialtyID
                  where ds.DoctorID == doctor.DoctorID
                  select new
                  {
                      s.SpecialtyID,
                      s.Specialty1
                  }).ToList()

        let clinics = (from c in db.Clinic
                  where c.DoctorID == doctor.DoctorID && c.Active == true

                  let schedule = (from sc in db.Schedule
                                  where sc.ClinicID == c.ClinicID
                                    && sc.DoctorID == doctor.DoctorID
                                    && DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
                                  select sc).ToList()

                  select new
                  {
                      c.ClinicID,
                      c.Street,
                      c.ClinicName,
                      c.ContactNumber,
                      c.City,
                      c.Province,
                      c.HomeNumber,
                      c.MobileNumber,
                      c.WorkNumber,
                      c.Email,
                      Schedules = schedule,
                  }).ToList()
        select new
        {
            Doctor = doctor,
            Specialties = sp,
            Clinics = clinics

        };

var rs = q.ToList();

rs = rs.AsEnumerable().Take(2).ToList();


问:
Compiling C++ program on Windows XP
I have a problem running a simple Hello-world program in C++ on my Windows XP. I have written a post here:

Using the g++ C++ compiler from cygwin

where I stated the problem and I received many helpful replies, which solved some things. However, I still cannot run my hello-world program. Please, have a look at the post, I have included the program there. A friend of mine is able to run this program on his machine without problems. So, the problem should be in my system or libraries or something else, but I cannot figure what. In the "Edited" section of my post, I have included what error messages exactly I get.

Here is what I receive when I try to compile the program like this:

g++ hello.cpp

From the cygwin shell:

When I try g++ hello.cpp, I get:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
</code>```

And here is what I get when I try to compile the program (again with g++ hello.cpp) from the DOS command prompt:

When I try g++ hello.cpp, I get:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
</code>```

答: You have an illegal character in your code; it may be caused by a bad character encoding or something like that. Try to check that.</p>

ContentLicense: CC BY-SA 2.5

Title: Compiling C++ program on Windows XP

Body:
I have a problem running a simple Hello-world program in C++ on my Windows XP. I have written a post here:

Using the g++ C++ compiler from cygwin

where I stated the problem and I received many helpful replies, which solved some things. However, I still cannot run my hello-world program. Please, have a look at the post, I have included the program there. A friend of mine is able to run this program on his machine without problems. So, the problem should be in my system or libraries or something else, but I cannot figure what. In the "Edited" section of my post, I have included what error messages exactly I get.

Here is what I receive when I try to compile the program like this:

g++ hello.cpp

From the cygwin shell:

When I try g++ hello.cpp, I get:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files

And here is what I get when I try to compile the program (again with g++ hello.cpp) from the DOS command prompt:

When I try g++ hello.cpp, I get:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)

LastEditorDisplayName: Rich B

OwnerDisplayName: jpalecek


问:
PostgreSQL tsvector configuration: how to allow special characters?
I've set up a new text search configuration in PostgreSQL. This configuration uses an empty stop word file, DictFile and AffFile.

A simple test...

```<code>SELECT *
  FROM ts_debug('public.myconfig', 'C++ and C# and PHP');
</code>```

...works (nearly) fine except the fact that the lexemes for 'C++' and 'C#' are both 'C'. Basically, all I would like to do is to make sure that the lexeme for 'C++' is 'C++' and that the lexeme for 'C#' is 'C#', hence enabling the user to query for 'C++'.

答:
The problem is two-fold.

The first issue is with indexing. The default config uses stemming to index the data and hence you get the lexeme 'C' for 'C++' and 'C#'. You can use the 'simple' config to index the data but then you will end up with unwanted words in the index. What I did was convert 'C++' to 'Cplusplus' and index that. Since 'Cplusplus' has no lexeme, it will be inxexed as is. You can do the same for 'C#' by making it 'CSharp' in the index data.

The second issue is with searching. Now that the indexed data is okay, we need to make sure that we convert the search terms for the special words. If the user types in 'C++", you need to convert it to 'Cplusplus' before performing the search.

I created a function on the DB that took in a string and converted all occurences of the special terms.

I have not used TSearch in a while, so I am not sure if TSearch allows you to setup and exception list the same way it allows for stopwords.

Body:
I've set up a new text search configuration in PostgreSQL. This configuration uses an empty stop word file, DictFile and AffFile.

A simple test...

SELECT *
  FROM ts_debug('public.myconfig', 'C++ and C# and PHP');

...works (nearly) fine except the fact that the lexemes for 'C++' and 'C#' are both 'C'. Basically, all I would like to do is to make sure that the lexeme for 'C++' is 'C++' and that the lexeme for 'C#' is 'C#', hence enabling the user to query for 'C++'.


问:
Attempted to load class "Mpdf" from namespace "Mpdf"
I'm using PHPSpreadsheet to create Excel.
I want t generate the Excel file, then convert the Excel file in a PDF one.
 So I've done the following :

```<code>use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use PhpOffice\PhpSpreadsheet\Reader\Exception;

class DevisGenerator
{
public function runDevis()
    {
       $spreadsheet = $this->loadexcelTemplate();
       $uuid = $this->uniqidReal();
       $filename = $this->writeName($spreadsheet, $uuid);
       $this->convertPdf($spreadsheet, $filename);

    }

    public function writeName($spreadsheet, $uuid)
    {
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->getCell('B2')->setValue('Toto');

        try {
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $filename = $uuid;
            $writer->save($filename.'.xlsx');
        }catch (Exception $e)
        {
            //TODO gestion erreur
        }
        return $filename;

    }

public function convertPdf($spreadsheet, $filename)
    {
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
        $writer->save($filename.'.pdf');

    }

</code>```

But whan I run the code the following error appear :

Attempted to load class "Mpdf" from namespace "Mpdf".
  Did you forget a "use" statement for "PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf"?

I did not understand this error, I have correctly insert the use statement in my code.
Any idea ?

答:
Since you use the fully qualified namespace when creating the instance, the use statement is not taken into account (thus the error message).

It seems like you have added a supplementary slash at the beginning of the namespace when creating your Mpdf instance, removing it will solve your issue.

$writer = new PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
```

<p>But since you have added a <code>use</code> statement, you do not need to use the fully qualified namespace again, you can do</p>

<pre class="lang-php prettyprint-override"><code>$writer = new Mpdf($spreadsheet);
</code>```

Body:
I'm using PHPSpreadsheet to create Excel.
I want t generate the Excel file, then convert the Excel file in a PDF one.
 So I've done the following :

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use PhpOffice\PhpSpreadsheet\Reader\Exception;

class DevisGenerator
{
public function runDevis()
    {
       $spreadsheet = $this->loadexcelTemplate();
       $uuid = $this->uniqidReal();
       $filename = $this->writeName($spreadsheet, $uuid);
       $this->convertPdf($spreadsheet, $filename);

    }

    public function writeName($spreadsheet, $uuid)
    {
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->getCell('B2')->setValue('Toto');

        try {
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $filename = $uuid;
            $writer->save($filename.'.xlsx');
        }catch (Exception $e)
        {
            //TODO gestion erreur
        }
        return $filename;

    }

public function convertPdf($spreadsheet, $filename)
    {
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
        $writer->save($filename.'.pdf');

    }

But whan I run the code the following error appear :

Attempted to load class "Mpdf" from namespace "Mpdf".
  Did you forget a "use" statement for "PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf"?

I did not understand this error, I have correctly insert the use statement in my code.
Any idea ?

Body:
Since you use the fully qualified namespace when creating the instance, the use statement is not taken into account (thus the error message).

It seems like you have added a supplementary slash at the beginning of the namespace when creating your Mpdf instance, removing it will solve your issue.

$writer = new PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);

But since you have added a use statement, you do not need to use the fully qualified namespace again, you can do

$writer = new Mpdf($spreadsheet);


问:
How to create a continuous v-slide-group with Vuetify?
Has anyone managed to create a continuous v-slide-group with Vuetify? I've created this v-slide-group with custom arrows and all, but now i have to make it continuous - when the last item is reached (by clicking the green arrow, or swiping) it has to start over. I've saw that this functionality is implemented in the v-carousel component (along with the cycle prop), but is there a way to make it with v-slide-group?

答:
I have a "working solution" right now, i'll be grateful if someone can expand on it, improve it or provide better one: I've v-model-ed the entire slide-group to a 0, and then when the user clicks the next arrow, it increments, previous arrow decrements. It takes 4 clicks to reach the end of the slide-group, so when this.slideGroup == 4, the next click sets it to 0 and restarts it.

```<code>slideGroup: 0,
nextSlide() {
  this.slideGroup++;
  this.slideGroup == 4 ? (this.slideGroup = 0) : "";
},
previousSlide() {
  this.slideGroup--;
}
</code>```

Body:
I have a "working solution" right now, i'll be grateful if someone can expand on it, improve it or provide better one: I've v-model-ed the entire slide-group to a 0, and then when the user clicks the next arrow, it increments, previous arrow decrements. It takes 4 clicks to reach the end of the slide-group, so when this.slideGroup == 4, the next click sets it to 0 and restarts it.

slideGroup: 0,
nextSlide() {
  this.slideGroup++;
  this.slideGroup == 4 ? (this.slideGroup = 0) : "";
},
previousSlide() {
  this.slideGroup--;
}


问:
is JSONDeserializationSchema() deprecated in Flink?
I am new to Flink and doing something very similar to the below link.

Cannot see message while sinking kafka stream and cannot see print message in flink 1.2

I am also trying to add JSONDeserializationSchema() as a deserializer for my Kafka input JSON message which is without a key.

But I found JSONDeserializationSchema() is not present.

Please let me know if I am doing anything wrong.

答:
To solve the problem of reading non-key JSON messages from Kafka I used case class and JSON parser.

The following code makes a case class and parses the JSON field using play API.

```<code>import play.api.libs.json.JsValue

object CustomerModel {

  def readElement(jsonElement: JsValue): Customer = {
    val id = (jsonElement \ "id").get.toString().toInt
    val name = (jsonElement \ "name").get.toString()
    Customer(id,name)
  }
case class Customer(id: Int, name: String)
}

def main(args: Array[String]): Unit = {
val env = StreamExecutionEnvironment.getExecutionEnvironment
val properties = new Properties()
properties.setProperty("bootstrap.servers", "xxx.xxx.0.114:9092")
properties.setProperty("group.id", "test-grp")

val consumer = new FlinkKafkaConsumer[String]("customer", new SimpleStringSchema(), properties)
val stream1 = env.addSource(consumer).rebalance

val stream2:DataStream[Customer]= stream1.map( str =>{Try(CustomerModel.readElement(Json.parse(str))).getOrElse(Customer(0,Try(CustomerModel.readElement(Json.parse(str))).toString))
    })

stream2.print("stream2")
env.execute("This is Kafka+Flink")

}
</code>```

The Try method lets you overcome the exception thrown while parsing the data
and returns the exception in one of the fields (if we want) or else it can just return the case class object with any given or default fields.

The sample output of the Code is:

```<code>stream2:1> Customer(1,"Thanh")
stream2:1> Customer(5,"Huy")
stream2:3> Customer(0,Failure(com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
 at [Source: ; line: 1, column: 0]))
</code>```

I am not sure if it is the best approach but it is working for me as of now.

Body:
To solve the problem of reading non-key JSON messages from Kafka I used case class and JSON parser.

The following code makes a case class and parses the JSON field using play API.

import play.api.libs.json.JsValue

object CustomerModel {

  def readElement(jsonElement: JsValue): Customer = {
    val id = (jsonElement \ "id").get.toString().toInt
    val name = (jsonElement \ "name").get.toString()
    Customer(id,name)
  }
case class Customer(id: Int, name: String)
}

def main(args: Array[String]): Unit = {
val env = StreamExecutionEnvironment.getExecutionEnvironment
val properties = new Properties()
properties.setProperty("bootstrap.servers", "xxx.xxx.0.114:9092")
properties.setProperty("group.id", "test-grp")

val consumer = new FlinkKafkaConsumer[String]("customer", new SimpleStringSchema(), properties)
val stream1 = env.addSource(consumer).rebalance

val stream2:DataStream[Customer]= stream1.map( str =>{Try(CustomerModel.readElement(Json.parse(str))).getOrElse(Customer(0,Try(CustomerModel.readElement(Json.parse(str))).toString))
    })

stream2.print("stream2")
env.execute("This is Kafka+Flink")

}

The Try method lets you overcome the exception thrown while parsing the data
and returns the exception in one of the fields (if we want) or else it can just return the case class object with any given or default fields.

The sample output of the Code is:

stream2:1> Customer(1,"Thanh")
stream2:1> Customer(5,"Huy")
stream2:3> Customer(0,Failure(com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
 at [Source: ; line: 1, column: 0]))

I am not sure if it is the best approach but it is working for me as of now.


问:
Adding more commits to a Branch in Git
Apologies in advance. I'm sure this is a very simple question with a very simple answer but I'm a beginner at Git and I'm a bit lost. I have a master branch. I made some changes yesterday and performed git add ., git commit, made a new branch by doing git branch part-one, then I pushed the commits to that new branch by doing git push origin part-one. I see that my commits got pushed into that branch on github. Now, I did some more work on the same files. I added and staged the changes just as before. Now when I go to push the commits by doing git push origin part-one it says Everything up-to-date. I don't see the most recent commits in my history on github.

Why is it not pushing the most recent commit to my part-one branch?

Possible cause: If I wanted to push these commits to my branch. Was I supposed to be do git checkout part-one, then do git add and git commit? I did those commands while I was on the master.

答:
You where on a branch, say master for simplicity. The name doesn't matter.

You added all files to the tracked files list (git add .), then created a commit on branch master (git commit).

You tried pushing this commit to a remote branch, on a different branch that is, not on remote master.

You are not really allowed to do so, for a number of reasons. Say the commit you created was child of commit X. Commit X exists on both local and remote master branch. Commit X does not exists on remote part-one, so there is no easy way to explain how to apply the edits starting from last commit of part-one, which is commit Y, say.

In the end, you want to move commits to a new branch, or perform a merge of master onto part-one, or git commit --amend to destroy last commit you made on master, then git switch part-one and git commit -a there.

Title: Adding more commits to a Branch in Git