问:
Mongoose: Missing expected field "$search"
I am trying to execute a query which performs a full text search with mongoose. The filter object looks as follows and works using mongosh:

{
  authorUid: 'X',
  '$text': { '$search': 'searchStr' }
}
```
<p>But, whenever trying to execute this with mongoose, I'm getting the following error:</p>
```MongoServerError: Missing expected field "$search"
```
<p>The mongoose code is as follows:</p>
<pre class="lang-js prettyprint-override"><code>let query = Collection.find(
    filterObj,
    {
        _id: 1,
        title: 1,
        src: 1,
    },
    { sort: { createdAt: -1 } },
);
</code>```

I am quite certain the text search index in the collection is created without error. It is visible in MongoDB Compass and I don't think the query should have worked in mongosh if this wasn't the case.

To be complete, here is the command ran via mongosh:

db.collection.find(
  {
    authorUid: 'X',
    '$text': { '$search': 'searchStr' }
  },
  {
    _id: 1,
    title: 1,
    src: 1
  },
  {sort: {createdAt: -1}}
)
```
<p>Is this one not equivalent with the one written for Mongoose? How can I perform this query using Mongoose?</p>
<p><strong>-- EDIT --</strong><br />
Just to ensure the cause is not the <code>filterObj</code>, I tried doing the exact same thing with it hard coded. Using Mongoose, it looks as follows:</p>
<pre class="lang-js prettyprint-override"><code>let query = Collection.find(
  {
     $text: {
        $search: "math",
      },
  },
);
</code>```

I'm still getting the same error. It is however still working via mongosh.

-- EDIT 2 --

I did get this to work using aggregates instead of .find. The following code returns the same as in the mongosh environment:

const res = await Collection.aggregate([
    {
        $match: {
           $text: {
                $search: "math",
            },
        },
    },
]);
```

This is most definitely usable, but I'm still clueless as to why the initial query did not work.

Body:
I am trying to execute a query which performs a full text search with mongoose. The filter object looks as follows and works using mongosh:

{
  authorUid: 'X',
  '$text': { '$search': 'searchStr' }
}

But, whenever trying to execute this with mongoose, I'm getting the following error:

MongoServerError: Missing expected field "$search"

The mongoose code is as follows:

let query = Collection.find(
    filterObj,
    {
        _id: 1,
        title: 1,
        src: 1,
    },
    { sort: { createdAt: -1 } },
);

I am quite certain the text search index in the collection is created without error. It is visible in MongoDB Compass and I don't think the query should have worked in mongosh if this wasn't the case.

To be complete, here is the command ran via mongosh:

db.collection.find(
  {
    authorUid: 'X',
    '$text': { '$search': 'searchStr' }
  },
  {
    _id: 1,
    title: 1,
    src: 1
  },
  {sort: {createdAt: -1}}
)

Is this one not equivalent with the one written for Mongoose? How can I perform this query using Mongoose?

-- EDIT --

Just to ensure the cause is not the filterObj, I tried doing the exact same thing with it hard coded. Using Mongoose, it looks as follows:

let query = Collection.find(
  {
     $text: {
        $search: "math",
      },
  },
);

I'm still getting the same error. It is however still working via mongosh.

-- EDIT 2 --

I did get this to work using aggregates instead of .find. The following code returns the same as in the mongosh environment:

const res = await Collection.aggregate([
    {
        $match: {
           $text: {
                $search: "math",
            },
        },
    },
]);

This is most definitely usable, but I'm still clueless as to why the initial query did not work.


来源: stackexchange

问:
Creating a new empty directory folder with the record id number on the desktop for each record added with the form in Django
First of all, my english is not very good, sorry for that.

I only have one field in my model. I want to create an empty directory folder on the desktop while creating a record using the form. Since I am new to Django, I would be grateful if you could write the complete codes. Thank you very much in advance.

MODELS.PY

```<code>class DosyaBilgileri(models.Model):
sahisAdi = models.CharField(max_length=50, verbose_name='Şahıs Adı')

def __str__(self):
    return self.sahisAdi

def delilIndex(request):
</code>```

VIEWS.PY

```<code>def delilIndex(request):

dosyaEkleFormu = DosyaBilgileriModelForm(request.POST or None, files=request.FILES or None)
if dosyaEkleFormu.is_valid():
    dosyaEkleFormuD = dosyaEkleFormu.save(commit=False)
    dosyaEkleFormuD.save()
    messages.add_message(request, messages.INFO, 'Dosya ekleme işlemi başarıyla tamamlandı.')
    return redirect('delilIndex')

return render(request, 'delil/index.html', {'dosyaEkleFormu':dosyaEkleFormu })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
First of all, my english is not very good, sorry for that.

I only have one field in my model. I want to create an empty directory folder on the desktop while creating a record using the form. Since I am new to Django, I would be grateful if you could write the complete codes. Thank you very much in advance.

MODELS.PY

class DosyaBilgileri(models.Model):
sahisAdi = models.CharField(max_length=50, verbose_name='Şahıs Adı')

def __str__(self):
    return self.sahisAdi

def delilIndex(request):

VIEWS.PY

def delilIndex(request):

dosyaEkleFormu = DosyaBilgileriModelForm(request.POST or None, files=request.FILES or None)
if dosyaEkleFormu.is_valid():
    dosyaEkleFormuD = dosyaEkleFormu.save(commit=False)
    dosyaEkleFormuD.save()
    messages.add_message(request, messages.INFO, 'Dosya ekleme işlemi başarıyla tamamlandı.')
    return redirect('delilIndex')

return render(request, 'delil/index.html', {'dosyaEkleFormu':dosyaEkleFormu })


问:
Forward RTSP feeds from private cameras through one public ip
I'm trying to provide access to RTSP feeds from multiple cameras on a private network through a single server, that will serve each feed via a unique port.

For example,

Camera A (Local IP: 10.0.0.1) can be accessed via Public IP: rtsp://50.12.1.2:800

Camera B (Local IP: 10.0.0.2) can be accessed via Public IP: rtsp://50.12.1.2:801

Camera C (Local IP: 10.0.0.3) can be accessed via Public IP: rtsp://50.12.1.2:802

and so on.

My current plan is to use a single ubuntu server to do the feed forwarding. Would like to know whats the best way to do this.


问:
Can I use a prevent default at a form that uses GET as a method in the Django HTML template?
I’m looking to create a section about searching for some movies in my database, however, this section is at the bottom of my page. However, when I search and find the movie that I was looking for, the page refreshed. Also, I do not know if “GET” is the ideal method for secure sections, but I read that POST is necessary just for database changes. In this case, I just want to bring the movie corresponding to what was searched at a search bar.

This is my view and I am getting the search like this, in the context, to make it easier to render. It is working ok.

class MoviesPage(TemplateView):

    template_name = "tailwind/movies-page.html"

    def get_context_data(self, **kwargs):

        context = super(MoviesPage, self).get_context_data(**kwargs)

        # Top Movies' section
        movies = Movies.objects.filter(
            name__in=[
                'Oldboy',
                'Parasite',
                'Lady Vengeance',
                ]
            )

        context['movies'] = movies

        # Movie search's section
        query = self.request.GET.get('q', default='oldboy')
        results = Movies/.objects.filter(Q(name__icontains=query))
        context['results'] = results
```
<p>This is my form in my HTML template:</p>
<pre class="lang-html prettyprint-override"><code><form
  action=""
  method="GET"
  id="search-package-form"
>
  <input
    type="search"
    name="q"
    placeholder="oldboy"
  />
  <div>
    <button
      type="submit"
    >
      <span>Search</span>
    </button>
  </div>

</form>

{% if results %}

  <div>
    {% for movie in results %}
            <ul>
                <li>{{ movie.name }}</li>
            </ul>
    {% endfor %}
  </div>

{% else %}

    <div>
      <h3>We did not found this movie</h3>
    </div>

{% endif %}

<script>
  document.getElementById('search-package-form').addEventListener('submit', function(e) {
  // prevent the default action of the submit event
  e.preventDefault();

  // submit the form using the submit() method
  this.submit();
});

</script>
</code>```

However, my page still refreshes when I submit something because I get something like:

/movies/?q=oldboy.

Body:
I’m looking to create a section about searching for some movies in my database, however, this section is at the bottom of my page. However, when I search and find the movie that I was looking for, the page refreshed. Also, I do not know if “GET” is the ideal method for secure sections, but I read that POST is necessary just for database changes. In this case, I just want to bring the movie corresponding to what was searched at a search bar.

This is my view and I am getting the search like this, in the context, to make it easier to render. It is working ok.

class MoviesPage(TemplateView):

    template_name = "tailwind/movies-page.html"

    def get_context_data(self, **kwargs):

        context = super(MoviesPage, self).get_context_data(**kwargs)

        # Top Movies' section
        movies = Movies.objects.filter(
            name__in=[
                'Oldboy',
                'Parasite',
                'Lady Vengeance',
                ]
            )

        context['movies'] = movies

        # Movie search's section
        query = self.request.GET.get('q', default='oldboy')
        results = Movies/.objects.filter(Q(name__icontains=query))
        context['results'] = results

This is my form in my HTML template:

<form
  action=""
  method="GET"
  id="search-package-form"
>
  <input
    type="search"
    name="q"
    placeholder="oldboy"
  />

    <button
      type="submit"
    >
      Search
    </button>

</form>

{% if results %}

    {% for movie in results %}

{{ movie.name }}

    {% endfor %}

{% else %}

We did not found this movie

{% endif %}

However, my page still refreshes when I submit something because I get something like:

/movies/?q=oldboy.


问:
GitLab CICD - Run stages only during merge_requests
I want to enable a stage to be run during only merge_requests. But if I add only - merge_requests then the stages above such as build and test stage doesn't show up during the merge request build.

As you can see in this screenshot, the build and test stage are missing during merge_requests and only the stage deploy review is showing.

Any idea why Build and Test stage doesn't show during merge?

Here is the full cicd pipeline:

```<code>image: node

stages:
  - build
  - test
  - deploy review
  - deploy staging
  - deploy production
  - production tests

build website:
  stage: build
  script:
    - sed -i "s/%%VERSION%%/$CI_COMMIT_SHORT_SHA/g" ./public/index.html
  artifacts:
    paths:
      - ./public

test website:
  stage: test
  script:
    - curl "http://localhost:9000" | tac | tac | grep -q "Gatsby"

deploy review:
  stage: deploy review
  only:
    - merge_requests    # The build and test stage should still be visible but it isn't
  environment:
    name: review/$CI_COMMIT_REF_NAME
    url: http://test.surge.sh
    on_stop: stop review
  script:
    - npm install -g surge
    - surge --project ./public --domain test.surge.sh
</code>```

Body:
I want to enable a stage to be run during only merge_requests. But if I add only - merge_requests then the stages above such as build and test stage doesn't show up during the merge request build.

As you can see in this screenshot, the build and test stage are missing during merge_requests and only the stage deploy review is showing.

Any idea why Build and Test stage doesn't show during merge?

Here is the full cicd pipeline:

image: node

stages:
  - build
  - test
  - deploy review
  - deploy staging
  - deploy production
  - production tests

build website:
  stage: build
  script:
    - sed -i "s/%%VERSION%%/$CI_COMMIT_SHORT_SHA/g" ./public/index.html
  artifacts:
    paths:
      - ./public

test website:
  stage: test
  script:
    - curl "http://localhost:9000" | tac | tac | grep -q "Gatsby"

deploy review:
  stage: deploy review
  only:
    - merge_requests    # The build and test stage should still be visible but it isn't
  environment:
    name: review/$CI_COMMIT_REF_NAME
    url: http://test.surge.sh
    on_stop: stop review
  script:
    - npm install -g surge
    - surge --project ./public --domain test.surge.sh


问:
JavaScript function triggered by <select> which takes the value X (range: 1 to 5) and rewrites DOM to show X number of divs
For class project I'm making a 'fee calculator' for a private school.

Default is to show one div for the user to enter data about one kid.

If the user selects 3 kids from the dropdown, they should see 3 divs inside of which are some questions and html form elements, identical to the first div for the first kid. In my script below, I attempted this with .cloneNode() and then .appendChild() without success.

If the user then changes from 3 to select 2 kids, the surplus div should be removed. In my script below, I attempted this by using a .querySelectorAll() to return a list of elements, and then iterate .remove() over the list, to get to zero divs before then appendChilding the saved clone X number of times... but this did not work.

```<code>// duplicate the oneKid element per number of kids selected
function numerateKids(num) {
const kidModule = document.getElementById("seedKid");
const kidClone = kidModule.cloneNode(true);
const kidsCurrent = document.querySelectorAll('.oneKid');
kidsCurrent.forEach(kid => {
  kid.remove();
});
num ++;
for (var i = 0; i < num; i++) {
    document.getElementById("calcBody").appendChild(kidClone);
}}
</code>```
```<code><html>
  <head>
  </head>
  <body>
    <div id="calcContainer">
      <div id="calcHead">
        Fee Calculator
      </div>
      <div id="calcBody">
        How many kids?
        <select onchange="numerateKids(this.value);" name="kidsNum" id="kidNumerator">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
        </select>
        <div class="oneKid" id="seedKid">
          <div>
            Kid's name?
          </div>
          <div>
            Starting year?
          </div>
          <div>
            Starting grade?
          </div>
        </div>
      </div>
      <div class="calcFoot">
        <div class="calcButton">
          Next
        </div>
      </div>
    </div>
  </body>
</html>
</code>```

Body:
For class project I'm making a 'fee calculator' for a private school.

Default is to show one div for the user to enter data about one kid.

If the user selects 3 kids from the dropdown, they should see 3 divs inside of which are some questions and html form elements, identical to the first div for the first kid. In my script below, I attempted this with .cloneNode() and then .appendChild() without success.

If the user then changes from 3 to select 2 kids, the surplus div should be removed. In my script below, I attempted this by using a .querySelectorAll() to return a list of elements, and then iterate .remove() over the list, to get to zero divs before then appendChilding the saved clone X number of times... but this did not work.

// duplicate the oneKid element per number of kids selected
function numerateKids(num) {
const kidModule = document.getElementById("seedKid");
const kidClone = kidModule.cloneNode(true);
const kidsCurrent = document.querySelectorAll('.oneKid');
kidsCurrent.forEach(kid => {
  kid.remove();
});
num ++;
for (var i = 0; i < num; i++) {
    document.getElementById("calcBody").appendChild(kidClone);
}}

        Fee Calculator

        How many kids?
        <select onchange="numerateKids(this.value);" name="kidsNum" id="kidNumerator">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
        </select>

            Kid's name?

            Starting year?

            Starting grade?

          Next


问:
Opentelemetry, collector and Grafana Tempo
I start my spring boot app like:

```<code>ExecStart=/bin/java -javaagent:./opentelemetry-javaagent.jar -jar /myapp/app.jar -Xmx4gi -Dotel.traces.exporter=otlp -Dotel.javaagent.debug=true -Dotel.metrics.exporter=logging -Dotel.exporter.otlp.endpoint=http://GRAFANA_TEMPO_IP:4317 -Dotel.exporter.otlp.traces.endpoint=GRAFANA_TEMPO_IP:4317 -Dotel.resource.attributes=service.name=app
</code>```

Why it still sends traffic to: The request could not be executed. Full error message: Failed to connect to localhost/127.0.0.1:4317? Why it send to localhost if variables are defined when starting java app?

Do I need in this case collector from Opentelemetry, or can I use only an agent?

Body:
I start my spring boot app like:

ExecStart=/bin/java -javaagent:./opentelemetry-javaagent.jar -jar /myapp/app.jar -Xmx4gi -Dotel.traces.exporter=otlp -Dotel.javaagent.debug=true -Dotel.metrics.exporter=logging -Dotel.exporter.otlp.endpoint=http://GRAFANA_TEMPO_IP:4317 -Dotel.exporter.otlp.traces.endpoint=GRAFANA_TEMPO_IP:4317 -Dotel.resource.attributes=service.name=app

Why it still sends traffic to: The request could not be executed. Full error message: Failed to connect to localhost/127.0.0.1:4317? Why it send to localhost if variables are defined when starting java app?

Do I need in this case collector from Opentelemetry, or can I use only an agent?


问:
How can I stop API returning URL escape code of the characters from URL I am sending through Python code?
I am trying to query GitLab's API to fetch users.

URL I have passed to the API:
https://gitlab.com/api/scim/v2/groups/cimpress-technology/Users/waad|5cmnhgd@NVJ4bHFYnhfv_mvbj4KGjguJGka_:

The response I get back:
ERROR: Http Error: 401 Client Error: Unauthorized for url:https://gitlab.com/api/scim/v2/groups/XXXXXXX/Users/waad%7C5cmnhgd@NVJ4bHFYnhfv_mvbj4KGjguJGka_:_-c9ef6jS API response we have received: «Response [401]>

I have noticed the | character gets replaced with its URL escape code '%7C' (Refer URL escape code of |)

I have tried multiple ways of URL parsing/encoding like.

```<code>import urllib.parse
safe_string = urllib.parse.quote_plus(...)
</code>```

I am expecting that it should read the '|' character as it is and not use the 7%C url escape code instead.

Is there a way I can avoid this?

Thank you

Body:
I am trying to query GitLab's API to fetch users.

URL I have passed to the API:
https://gitlab.com/api/scim/v2/groups/cimpress-technology/Users/waad|5cmnhgd@NVJ4bHFYnhfv_mvbj4KGjguJGka_:

The response I get back:
ERROR: Http Error: 401 Client Error: Unauthorized for url:https://gitlab.com/api/scim/v2/groups/XXXXXXX/Users/waad%7C5cmnhgd@NVJ4bHFYnhfv_mvbj4KGjguJGka_:_-c9ef6jS API response we have received: «Response [401]>

I have noticed the | character gets replaced with its URL escape code '%7C' (Refer URL escape code of |)

I have tried multiple ways of URL parsing/encoding like.

import urllib.parse
safe_string = urllib.parse.quote_plus(...)

I am expecting that it should read the '|' character as it is and not use the 7%C url escape code instead.

Is there a way I can avoid this?

Thank you


问:
Space simulation in the world gives rotation error which is not in the local, the main part that i need to use the world space
Local space simulation

World Space simulation


问:
Generate a new uniformly distributed array from the elements of the previous array
It is basically a constraint optimisation problem where I need to find similar colors given a particular color, from a color database.

Consider an array (signifying the distance between the inputColor and the allColorsInDB): [0, 5, 6, 1, 0.56, 4350, 64, 345, 20, 14, 2.045, 54, 56]

Construct a new array of limit N (user input) with the elements of the previous array such that:

K is the middle element of the new array. (K is user input and is already present in the original array)

Each interval between i th and (i+1)th element in the new array is same or closest possible.

Constraints:

N <= originalArray.length

K is always present in the original Array

This is what I'm trying...

const convert = require('@csstools/convert-colors');

export type Lab = [number, number, number];

const calculateEuclideanDistance = (color1: Lab, color2: Lab) => {
  const [l1, a1, b1] = color1;
  const [l2, a2, b2] = color2;
  return Math.sqrt((l2 - l1) ** 2 + (a2 - a1) ** 2 + (b2 - b1) ** 2);
};

const getSimilarColors = (brand: keyof typeof colors.brands, color: string, threshold?: number, limit?: number) => {
  const brandColors = colors.brands[brand].colors;
  const colorLab = convert.hex2lab(color);
  let allColors = Object.keys(brandColors)
    .map((curr) => {
      // @ts-ignore
      const currLab = brandColors[curr as keyof typeof brandColors].lab as Lab;
      return {
        ...brandColors[curr as keyof typeof brandColors],
        hex: curr,
        distance: calculateEuclideanDistance(colorLab, currLab),
      };
    })
    // Sorting colors from dark to light
    .sort((a, b) => a.lab[0]! - b.lab[0]!);

  if (threshold) {
    allColors = allColors.filter((c) => c.distance <= threshold);
  }

  if (!limit || limit >= allColors.length) {
    return allColors;
  }

  // TODO: Improve this logic, right now we're assuming limit is always 5, hence computing it statically
  const filteredColors = new Array(5);
  const midIndex = allColors.findIndex((c) => c.hex === color)!;

  // eslint-disable-next-line prefer-destructuring
  filteredColors[0] = allColors[0];
  filteredColors[2] = allColors[midIndex];
  filteredColors[4] = allColors[allColors.length - 1];

  filteredColors[1] = allColors[Math.floor(midIndex / 2)];
  filteredColors[3] = allColors[Math.floor((allColors.length - 1 + midIndex) / 2)];

  return filteredColors;
};
```

Result that I'm expecting:
Sorted Colors Based on LAB
Sorted Colors Based on LAB

The thing that I'm getting from the API for now is correct, however the I'm doing it statically.

Input

Output

Formatted Output

Body:
It is basically a constraint optimisation problem where I need to find similar colors given a particular color, from a color database.

Consider an array (signifying the distance between the inputColor and the allColorsInDB): [0, 5, 6, 1, 0.56, 4350, 64, 345, 20, 14, 2.045, 54, 56]

Construct a new array of limit N (user input) with the elements of the previous array such that:

K is the middle element of the new array. (K is user input and is already present in the original array)

Each interval between i th and (i+1)th element in the new array is same or closest possible.

Constraints:

N <= originalArray.length

K is always present in the original Array

This is what I'm trying...

const convert = require('@csstools/convert-colors');

export type Lab = [number, number, number];

const calculateEuclideanDistance = (color1: Lab, color2: Lab) => {
  const [l1, a1, b1] = color1;
  const [l2, a2, b2] = color2;
  return Math.sqrt((l2 - l1) ** 2 + (a2 - a1) ** 2 + (b2 - b1) ** 2);
};

const getSimilarColors = (brand: keyof typeof colors.brands, color: string, threshold?: number, limit?: number) => {
  const brandColors = colors.brands[brand].colors;
  const colorLab = convert.hex2lab(color);
  let allColors = Object.keys(brandColors)
    .map((curr) => {
      // @ts-ignore
      const currLab = brandColors[curr as keyof typeof brandColors].lab as Lab;
      return {
        ...brandColors[curr as keyof typeof brandColors],
        hex: curr,
        distance: calculateEuclideanDistance(colorLab, currLab),
      };
    })
    // Sorting colors from dark to light
    .sort((a, b) => a.lab[0]! - b.lab[0]!);

  if (threshold) {
    allColors = allColors.filter((c) => c.distance <= threshold);
  }

  if (!limit || limit >= allColors.length) {
    return allColors;
  }

  // TODO: Improve this logic, right now we're assuming limit is always 5, hence computing it statically
  const filteredColors = new Array(5);
  const midIndex = allColors.findIndex((c) => c.hex === color)!;

  // eslint-disable-next-line prefer-destructuring
  filteredColors[0] = allColors[0];
  filteredColors[2] = allColors[midIndex];
  filteredColors[4] = allColors[allColors.length - 1];

  filteredColors[1] = allColors[Math.floor(midIndex / 2)];
  filteredColors[3] = allColors[Math.floor((allColors.length - 1 + midIndex) / 2)];

  return filteredColors;
};

Result that I'm expecting:
Sorted Colors Based on LAB
Sorted Colors Based on LAB

The thing that I'm getting from the API for now is correct, however the I'm doing it statically.

Input

Output

Formatted Output


问:
Swift performance with Accelerate when evaluating random binary trees
I am trying to move a program I currently have implemented in Python to Swift. Performance is critical as it is about a randomness-based search algorithm. What I need to do is to evaluate a large amount of random binary trees where each non-leaf node represents a basic arithmetic or logical operation and each leaf-node represents a (large) vector of numbers.

I managed to get Accelerate's BNNS functions to do the calculations but still they are slower than my (much simpler, Pandas-based) Python approach, which takes less than half the time on average and with similar circumstances to perform evaluate_signal on each of the trees.

It would be great if someone could review my code and tell me whether there is any further potential for optimisation and/or any better approach. In below code I only cover the add (addition) operations but the others are very similar in structure. I also left out the part which generates the trees (and ensures they are "legit" in terms of consecutive operations) as I don't think that is particularly relevant here - happy to also add it however in case you think that is of help.

import Accelerate

enum NodeValue {
    case add // Addition
    case sub // Substraction
    case mul // Multiplication
    case div // Division
    case sml // Smaller
    case lrg // Larger
    case met(columnIndex: Int) // This is a index of return_data and used for the leafs of the hierarchy tree
}

final class Node {
    var value: NodeValue
    var lhs: Node?
    var rhs: Node?

    init(value: NodeValue, lhs: Node?, rhs: Node?) {
        self.value = value
        self.lhs = lhs
        self.rhs = rhs
    }

    func evaluate_signal(return_data: [Int: [Float16]]) -> [Any] {
        // Determine output
        switch self.value {
        case .add:
            let eval_left = lhs!.evaluate_signal(return_data: return_data) as! [Float16]
            let eval_right = rhs!.evaluate_signal(return_data: return_data) as! [Float16]
            let leftDescriptor = BNNSNDArrayDescriptor.allocate(
                initializingFrom: eval_left,
                shape: .vector(eval_left.count))
            let rightDescriptor = BNNSNDArrayDescriptor.allocate(
                initializingFrom: eval_right,
                shape: .vector(eval_left.count))
            let resultDescriptor = BNNSNDArrayDescriptor.allocateUninitialized(
                scalarType: Float16.self,
                shape: .vector(eval_left.count))
            let layer = BNNS.BinaryArithmeticLayer(
                inputA: leftDescriptor,
                inputADescriptorType: BNNS.DescriptorType.sample,
                inputB: rightDescriptor,
                inputBDescriptorType: BNNS.DescriptorType.sample,
                output: resultDescriptor,
                outputDescriptorType: BNNS.DescriptorType.sample,
                function: BNNS.ArithmeticBinaryFunction.add)
            try! layer!.apply(
                batchSize: 1,
                inputA: leftDescriptor,
                inputB: rightDescriptor,
                output: resultDescriptor)
            let resultVector: [Float16] = resultDescriptor.makeArray(of: Float16.self)!
            leftDescriptor.deallocate()
            rightDescriptor.deallocate()
            resultDescriptor.deallocate()
            return resultVector
        case .sub:
            // Similar code for substraction
        case .mul:
            // Similar code for multiplication
        case .div:
            // Similar code for division
        case .sml:
            // Similar code for comparison if smaller
        case .lrg:
            // Similar code for comparison if larger
        case .met(let columnIndex):
            return return_data[columnIndex]!
        }
    }
}

```


问:
How to get a retrofit response which changes according to my request?
I want to make a list of coins in my request and send it to server and according to my request my response will changes, for an example :

I want to send a request using retrofit to my server to check the price of bitcoin and cardano vs usd so i will add bitcoin and cardano to my request and the rquest will be like this:

request

and response will be a json string like this:

{
"bitcoin": {
"usd": 17155.19
},
"cardano": {
"usd": 0.312429
}
}

my question is how can I make a model in retrofit for such a case which has no key and changes frequently?

for example if I just add dogecoin to my request and compare it with etherium the result will change like this ?

request

and respons will be :

{
"bitcoin": {
"usd": 17147.44,
"eth": 13.476023
},
"cardano": {
"usd": 0.312662,
"eth": 0.00024572
},
"dogecoin": {
"usd": 0.096497,
"eth": 0.00007584
}
}

I tried to get the data as a json object but I could not achieve a good result


问:
How to detect if there is no more post to fetch in CollectionView?
I am making new app with Xcode using Swift and i am fetching posts from my WordPress website , all works fine but there is one problem, when i scroll down to the very last post of category then the indicator is just running and nothing happens, i want when there is no more post then Progress bar should stop running and i want to toast a message that there is no more post , how is that possible ? this is my code to fetch posts

```<code> func fetchPostData(completionHandler: @escaping ([Postimage]) -> Void ) {

    let url = URL(string: "https://www.sikhnama.com/wp-json/wp/v2/posts/?categories=4&page=\(page)\(sortBy)")!
    print(url)
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

        guard let data = data else {return}

        do {

            let postsData = try JSONDecoder().decode([Postimage].self, from: data)

            completionHandler(postsData)
            DispatchQueue.main.async {
                if(self.newsData.isEmpty == false){
                    print("collection view empty")
                    self.collectionView.reloadData()
                    SVProgressHUD.dismiss()

                }
                else{
                  if(self.collectionView == nil){
                      print("collection view nill")
                      self.fetchPostData { (posts) in
                          self.newsData = posts }
                      }
                   }

            }
        }

        catch {

            let error = error
            print(String(describing: error))
        }

    }
  task.resume()

}
</code>```

can you please help ?

Body:
I am making new app with Xcode using Swift and i am fetching posts from my WordPress website , all works fine but there is one problem, when i scroll down to the very last post of category then the indicator is just running and nothing happens, i want when there is no more post then Progress bar should stop running and i want to toast a message that there is no more post , how is that possible ? this is my code to fetch posts

 func fetchPostData(completionHandler: @escaping ([Postimage]) -> Void ) {

    let url = URL(string: "https://www.sikhnama.com/wp-json/wp/v2/posts/?categories=4&page=\(page)\(sortBy)")!
    print(url)
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

        guard let data = data else {return}

        do {

            let postsData = try JSONDecoder().decode([Postimage].self, from: data)

            completionHandler(postsData)
            DispatchQueue.main.async {
                if(self.newsData.isEmpty == false){
                    print("collection view empty")
                    self.collectionView.reloadData()
                    SVProgressHUD.dismiss()

                }
                else{
                  if(self.collectionView == nil){
                      print("collection view nill")
                      self.fetchPostData { (posts) in
                          self.newsData = posts }
                      }
                   }

            }
        }

        catch {

            let error = error
            print(String(describing: error))
        }

    }
  task.resume()

}

can you please help ?


问:
How to create custome layouts in jetpack compose
I wonder if there is a way to create this Layout in jetpack compose?

I tried using Draw Arc but it didn't look the same as the view.

Can someone help me with a link or a piece tip that can allow me to create m,y own Layouts to get the exact same view in the image?


问:
Typescript: Is it possible to use a property of a type as a type?
I would like to infer types from the current object and on its implementation. The following FruitPicker has a property of fruitKey, which will determine the return value of the Function. Is it possible to connect those.

type Lookup = {
  banana: Banana;
  apple: Apple;
  peach: Peach;
};

type FruitPicker = {
  (
    deliveredFruits // TypeBasedOn FruitPicker.availableFruits
  ) => Lookup[this.fruitKey] // type based on FruitPicker.fruitKey
  fruitKey: keyof Lookup;
  availableFruits: (keyof Lookup)[];
}

// implementation of FruitPicker:
const fruitPicker: FruitPicker = (
  deliveredFruits // should be dependant on the type of available Fruits
) => {
  // working with the fruits
  // has to return type Banana because its fruitKey is 'banana'
}
fruitPicker.fruitKey = 'banana'
fruitPicker.availableFruits = ['apple', 'peach'];
```
<p>i was successful connecting them like this:</p>
<pre class="lang-js prettyprint-override"><code>type FruitPicker<Key extends keyof Lookup, AvailableFruits extends keyof Lookup> = {
  (availableFruits: Pick<Lookup, AvailableFruits>) => Lookup[Key];
  fruitKey: Key,
  availableFruits: AvailableFruits[];
}
</code>```

But i always have to pass the generic arguments, even if it could be read from the implementation.

Body:
I would like to infer types from the current object and on its implementation. The following FruitPicker has a property of fruitKey, which will determine the return value of the Function. Is it possible to connect those.

type Lookup = {
  banana: Banana;
  apple: Apple;
  peach: Peach;
};

type FruitPicker = {
  (
    deliveredFruits // TypeBasedOn FruitPicker.availableFruits
  ) => Lookup[this.fruitKey] // type based on FruitPicker.fruitKey
  fruitKey: keyof Lookup;
  availableFruits: (keyof Lookup)[];
}

// implementation of FruitPicker:
const fruitPicker: FruitPicker = (
  deliveredFruits // should be dependant on the type of available Fruits
) => {
  // working with the fruits
  // has to return type Banana because its fruitKey is 'banana'
}
fruitPicker.fruitKey = 'banana'
fruitPicker.availableFruits = ['apple', 'peach'];

i was successful connecting them like this:

type FruitPicker<Key extends keyof Lookup, AvailableFruits extends keyof Lookup> = {
  (availableFruits: Pick<Lookup, AvailableFruits>) => Lookup[Key];
  fruitKey: Key,
  availableFruits: AvailableFruits[];
}

But i always have to pass the generic arguments, even if it could be read from the implementation.


问:
what does this mean in command systemctl status
When I use command systemctl status to list all service in linux, I got this:
enter image description here
why is there underline under docker.service and containers.service?
why is there three dots behind docker.service and containerd.service?

I am looking for why eBPF uprobe cannot work when I attach an uprobe to daemon /usr/bin/dockerd and /usr/bin/containerd, while it works well on other daemons.
Everytime I try to attach an uprobe to this two daemon by bpftrace, it tells me "ERROR: uprobe target file '/usr/bin/dockerd' does not exist or is not executable".


问:
Postgres - super slow query - wierd behaviour
Im struggling with super slow query which contains hundreds of AND .. OR conditions / text parameters - no joins etc (this is part of closed system co query cannot be easily changed)

Query slowed down recently, after some maintenance we did on DB (before it was executed few seconds, now ~30 mins)
I tried to analyse it - it does basically Bitmap Heap Scan than hundreds  Bitmap Index Scan's for each AND condition

As this is closed (vendor) system I cant do much, but I wonder why it slowed down so much from day to day...

I tried:

Reindex Table - still slow

Full Vacuum Table - slow

vacuum full Database - slow

Restore DB from SQL Dump - slow

Copy data to table B - FAST AGAIN!

Truncate data and copy back from table A - FAST!

Query plan was exactly the same in all cases..

Can someone explain me what is happening here?

Table size: ~6'000'000 rows
PostgreSQL 12.


问:
MySql update statement in stored procedure. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column
I want to use a stored procedure to update price for an arbitrary product
in products table. Input data is id for product and the new price.
id is primary key in products table:

CREATE DEFINER=root@localhost PROCEDURE update_price(
IN id int,
IN val decimal(10,2))
BEGIN
UPDATE products
SET Price = val
WHERE Id = id;
END

When I run the stored procedure I get error "Error Code: 1175. You are using safe update mode and you tried to  update a table without a WHERE that uses a KEY column." When I disable safe mode the stored procedure runs without error, but the price is updated to same value for all rows,
i.e. the WHERE-clause does not work.


问:
Skipping incompatible when searching for... - SDL2
I wanted to try out SDL2 but I can't seem to succeed in the installation.

Here's what I get:

cmd.exe /C "cd . && C:\PROGRA~1\JETBRA~1\CLION2~1.3\bin\mingw\bin\gcc.exe -g  CMakeFiles/SDL.dir/main.c.obj -o SDL.exe -Wl,--out-implib,libSDL.dll.a -Wl,--major-image-version,0,--minor-image-version,0 -LC:/libs/SDL/lib/x86 -lSDL2main  -lSDL2  -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 && cd ."
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2main.lib when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib\libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib\libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2main.lib when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86\SDL2main.lib when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: cannot find -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2main.lib when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2.lib when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2.dll when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2.dll.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib\libSDL2.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2.dll.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib\libSDL2.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2.lib when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2.dll when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86\SDL2.lib when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2.dll.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2.dll.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: cannot find -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2.lib when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2.dll when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2.dll.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2.dll.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2.a when searching for -lSDL2
collect2.exe: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
```
<p>Can someone help?</p>
<p>Here's my CMakeList file:</p>
```cmake_minimum_required(VERSION 3.23)
project(SDL C)

set(CMAKE_C_STANDARD 99)

set(SDL2_INCLUDE_DIR C:/libs/SDL/include)
set(SDL2_LIB_DIR C:/libs/SDL/lib/x86)

include_directories(${SDL2_INCLUDE_DIR})
link_directories(${SDL2_LIB_DIR})

add_executable(SDL main.c)

target_link_libraries(${PROJECT_NAME} SDL2main SDL2)
```

Body:
I wanted to try out SDL2 but I can't seem to succeed in the installation.

Here's what I get:

cmd.exe /C "cd . && C:\PROGRA~1\JETBRA~1\CLION2~1.3\bin\mingw\bin\gcc.exe -g  CMakeFiles/SDL.dir/main.c.obj -o SDL.exe -Wl,--out-implib,libSDL.dll.a -Wl,--major-image-version,0,--minor-image-version,0 -LC:/libs/SDL/lib/x86 -lSDL2main  -lSDL2  -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 && cd ."
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2main.lib when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib\libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib\libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2main.lib when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86\SDL2main.lib when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: cannot find -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2main.lib when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2main.a when searching for -lSDL2main
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2.lib when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2.dll when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2.dll.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib\libSDL2.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2.dll.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib\libSDL2.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2.lib when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2.dll when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86\SDL2.lib when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2.dll.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2.dll.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: cannot find -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2.lib when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible C:/libs/SDL/lib/x86/SDL2.dll when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2.dll.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/../lib/libSDL2.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2.dll.a when searching for -lSDL2
C:\Program Files\JetBrains\CLion 2022.2.3\bin\mingw\bin/ld.exe: skipping incompatible /mingw/lib/libSDL2.a when searching for -lSDL2
collect2.exe: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.

Can someone help?

Here's my CMakeList file:

cmake_minimum_required(VERSION 3.23)
project(SDL C)

set(CMAKE_C_STANDARD 99)

set(SDL2_INCLUDE_DIR C:/libs/SDL/include)
set(SDL2_LIB_DIR C:/libs/SDL/lib/x86)

include_directories(${SDL2_INCLUDE_DIR})
link_directories(${SDL2_LIB_DIR})

add_executable(SDL main.c)

target_link_libraries(${PROJECT_NAME} SDL2main SDL2)


问:
The value of the firestore field sums
I have a firestore file and I want to add the value of the field "quantity" in all files (all together and displayed in label), is there a way to do this?

For example, the value of "quantity" in the first file field is "100", the value of "quantity" in the second file field is "50", and the value of "quantity" in the third file field is "1000"
100+50+1000=
Displayed in label:1150

Here is my current code:

```<code>func getDatas2(){
        self.db.collection("Users").document(UID!).collection("AiBuyPost").getDocuments { snapshot, error in
        if error != nil {
            print(error?.localizedDescription ?? "Error while getting data from server!" )
        }else{
            if snapshot?.isEmpty != true && snapshot != nil {
                self.postArray.removeAll(keepingCapacity: false)
                for document in snapshot!.documents{
                    if let quantity = document.data()["quantity"] as? Int{
                        self.totalVotes += quantity
                        self.new.text = String(self.totalVotes)
                    }
                }
            }
        }
    }
}
</code>```

Title: The value of the firestore field sums

Body:
I have a firestore file and I want to add the value of the field "quantity" in all files (all together and displayed in label), is there a way to do this?

For example, the value of "quantity" in the first file field is "100", the value of "quantity" in the second file field is "50", and the value of "quantity" in the third file field is "1000"
100+50+1000=
Displayed in label:1150

Here is my current code:

func getDatas2(){
        self.db.collection("Users").document(UID!).collection("AiBuyPost").getDocuments { snapshot, error in
        if error != nil {
            print(error?.localizedDescription ?? "Error while getting data from server!" )
        }else{
            if snapshot?.isEmpty != true && snapshot != nil {
                self.postArray.removeAll(keepingCapacity: false)
                for document in snapshot!.documents{
                    if let quantity = document.data()["quantity"] as? Int{
                        self.totalVotes += quantity
                        self.new.text = String(self.totalVotes)
                    }
                }
            }
        }
    }
}


问:
How to create vm instance from machine image with the different boot disk size in GCP
I want to create a virtual machine instance from a machine image. The machine image size has a boot disc of 20GB, but I want to create a VM with a boot disc of 30GB. I tried the command below, but it didn't work for me. Could someone please assist me with this?

gcloud beta compute instances create test-vm --project=test-2511 --zone us-east1-b --network=demo-vpc --subnet=demo-subnet --machine-type=n2-standard-2 --boot-disk-size=30GB --source-machine-image projects/test-2511/global/machineImages/demo --service-account 1266-compute@developer.gserviceaccount.com```


问:
"ALSA lib pcm_dmix.c error when running Rust project: Cannot connect to server socket"
I am encountering an error when trying to run the ggez snake game example in Rust., The error message is:

```<code>ALSA lib pcm_dmix.c:999:(snd_pcm_dmix_open) unable to open slave
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
ALSA lib pcm_oss.c:397:(_snd_pcm_oss_open) Cannot open device /dev/dsp
ALSA lib pcm_oss.c:397:(_snd_pcm_oss_open) Cannot open device /dev/dsp
Failed to initialize graphics, trying secondary backends.. Please mention this if you encounter any bugs!
Error: RequestDeviceError(RequestDeviceError)
</code>```

Here is the example code i'm using from ggez repo:

//! A small snake game done after watching
//! <https://www.youtube.com/watch?v=HCwMb0KslX8>
//! to showcase ggez and how it relates/differs from piston.
//!
//! Note that this example is meant to highlight the general
//! structure of a ggez game. Some of the details may need to
//! be changed to scale the game. For example, if we needed to
//! draw hundreds or thousands of shapes, a SpriteBatch is going
//! to offer far better performance than the direct draw calls
//! that this example uses.
//!
//! Author: @termhn
//! Original repo: <https://github.com/termhn/ggez_snake>

// First we'll import the crates we need for our game;
// in this case that is just `ggez` and `oorandom` (and `getrandom`
// to seed the RNG.)
use oorandom::Rand32;

// Next we need to actually `use` the pieces of ggez that we are going
// to need frequently.
use ggez::{
    event, graphics,
    input::keyboard::{KeyCode, KeyInput},
    Context, GameResult,
};

// We'll bring in some things from `std` to help us in the future.
use std::collections::LinkedList;

// The first thing we want to do is set up some constants that will help us out later.

// Here we define the size of our game board in terms of how many grid
// cells it will take up. We choose to make a 30 x 20 game board.
const GRID_SIZE: (i16, i16) = (30, 20);
// Now we define the pixel size of each tile, which we make 32x32 pixels.
const GRID_CELL_SIZE: (i16, i16) = (32, 32);

// Next we define how large we want our actual window to be by multiplying
// the components of our grid size by its corresponding pixel size.
const SCREEN_SIZE: (f32, f32) = (
    GRID_SIZE.0 as f32 * GRID_CELL_SIZE.0 as f32,
    GRID_SIZE.1 as f32 * GRID_CELL_SIZE.1 as f32,
);

// Here we're defining how often we want our game to update. This will be
// important later so that we don't have our snake fly across the screen because
// it's moving a full tile every frame.
const DESIRED_FPS: u32 = 8;

/// Now we define a struct that will hold an entity's position on our game board
/// or grid which we defined above. We'll use signed integers because we only want
/// to store whole numbers, and we need them to be signed so that they work properly
/// with our modulus arithmetic later.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct GridPosition {
    x: i16,
    y: i16,
}

impl GridPosition {
    /// We make a standard helper function so that we can create a new `GridPosition`
    /// more easily.
    pub fn new(x: i16, y: i16) -> Self {
        GridPosition { x, y }
    }

    /// As well as a helper function that will give us a random `GridPosition` from
    /// `(0, 0)` to `(max_x, max_y)`
    pub fn random(rng: &mut Rand32, max_x: i16, max_y: i16) -> Self {
        // We can use `.into()` to convert from `(i16, i16)` to a `GridPosition` since
        // we implement `From<(i16, i16)>` for `GridPosition` below.
        (
            rng.rand_range(0..(max_x as u32)) as i16,
            rng.rand_range(0..(max_y as u32)) as i16,
        )
            .into()
    }

    /// We'll make another helper function that takes one grid position and returns a new one after
    /// making one move in the direction of `dir`.
    /// We use the [rem_euclid()](https://doc.rust-lang.org/std/primitive.i16.html#method.rem_euclid)
    /// API when crossing the top/left limits, as the standard remainder function (`%`) returns a
    /// negative value when the left operand is negative.
    /// Only the Up/Left cases require rem_euclid(); for consistency, it's used for all of them.
    pub fn new_from_move(pos: GridPosition, dir: Direction) -> Self {
        match dir {
            Direction::Up => GridPosition::new(pos.x, (pos.y - 1).rem_euclid(GRID_SIZE.1)),
            Direction::Down => GridPosition::new(pos.x, (pos.y + 1).rem_euclid(GRID_SIZE.1)),
            Direction::Left => GridPosition::new((pos.x - 1).rem_euclid(GRID_SIZE.0), pos.y),
            Direction::Right => GridPosition::new((pos.x + 1).rem_euclid(GRID_SIZE.0), pos.y),
        }
    }
}

/// We implement the `From` trait, which in this case allows us to convert easily between
/// a GridPosition and a ggez `graphics::Rect` which fills that grid cell.
/// Now we can just call `.into()` on a `GridPosition` where we want a
/// `Rect` that represents that grid cell.
impl From<GridPosition> for graphics::Rect {
    fn from(pos: GridPosition) -> Self {
        graphics::Rect::new_i32(
            pos.x as i32 * GRID_CELL_SIZE.0 as i32,
            pos.y as i32 * GRID_CELL_SIZE.1 as i32,
            GRID_CELL_SIZE.0 as i32,
            GRID_CELL_SIZE.1 as i32,
        )
    }
}

/// And here we implement `From` again to allow us to easily convert between
/// `(i16, i16)` and a `GridPosition`.
impl From<(i16, i16)> for GridPosition {
    fn from(pos: (i16, i16)) -> Self {
        GridPosition { x: pos.0, y: pos.1 }
    }
}

/// Next we create an enum that will represent all the possible
/// directions that our snake could move.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Direction {
    Up,
    Down,
    Left,
    Right,
}

impl Direction {
    /// We create a helper function that will allow us to easily get the inverse
    /// of a `Direction` which we can use later to check if the player should be
    /// able to move the snake in a certain direction.
    pub fn inverse(&self) -> Self {
        match *self {
            Direction::Up => Direction::Down,
            Direction::Down => Direction::Up,
            Direction::Left => Direction::Right,
            Direction::Right => Direction::Left,
        }
    }

    /// We also create a helper function that will let us convert between a
    /// `ggez` `Keycode` and the `Direction` that it represents. Of course,
    /// not every keycode represents a direction, so we return `None` if this
    /// is the case.
    pub fn from_keycode(key: KeyCode) -> Option<Direction> {
        match key {
            KeyCode::Up => Some(Direction::Up),
            KeyCode::Down => Some(Direction::Down),
            KeyCode::Left => Some(Direction::Left),
            KeyCode::Right => Some(Direction::Right),
            _ => None,
        }
    }
}

/// This is mostly just a semantic abstraction over a `GridPosition` to represent
/// a segment of the snake. It could be useful to, say, have each segment contain its
/// own color or something similar. This is an exercise left up to the reader ;)
#[derive(Clone, Copy, Debug)]
struct Segment {
    pos: GridPosition,
}

impl Segment {
    pub fn new(pos: GridPosition) -> Self {
        Segment { pos }
    }
}

/// This is again an abstraction over a `GridPosition` that represents
/// a piece of food the snake can eat. It can draw itself.
struct Food {
    pos: GridPosition,
}

impl Food {
    pub fn new(pos: GridPosition) -> Self {
        Food { pos }
    }

    /// Here is the first time we see what drawing looks like with ggez.
    /// We have a function that takes in a `&mut ggez::graphics::Canvas` which we use
    /// to do drawing.
    ///
    /// Note: this method of drawing does not scale. If you need to render
    /// a large number of shapes, use an InstanceArray. This approach is fine for
    /// this example since there are a fairly limited number of calls.
    fn draw(&self, canvas: &mut graphics::Canvas) {
        // First we set the color to draw with, in this case all food will be
        // colored blue.
        let color = [0.0, 0.0, 1.0, 1.0];
        // Then we draw a rectangle with the Fill draw mode, and we convert the
        // Food's position into a `ggez::Rect` using `.into()` which we can do
        // since we implemented `From<GridPosition>` for `Rect` earlier.
        canvas.draw(
            &graphics::Quad,
            graphics::DrawParam::new()
                .dest_rect(self.pos.into())
                .color(color),
        );
    }
}

/// Here we define an enum of the possible things that the snake could have "eaten"
/// during an update of the game. It could have either eaten a piece of `Food`, or
/// it could have eaten `Itself` if the head ran into its body.
#[derive(Clone, Copy, Debug)]
enum Ate {
    Itself,
    Food,
}

/// Now we make a struct that contains all the information needed to describe the
/// state of the Snake itself.
struct Snake {
    /// First we have the head of the snake, which is a single `Segment`.
    head: Segment,
    /// Then we have the current direction the snake is moving. This is
    /// the direction it will move when `update` is called on it.
    dir: Direction,
    /// Next we have the body, which we choose to represent as a `LinkedList`
    /// of `Segment`s.
    body: LinkedList<Segment>,
    /// Now we have a property that represents the result of the last update
    /// that was performed. The snake could have eaten nothing (None), Food (Some(Ate::Food)),
    /// or Itself (Some(Ate::Itself))
    ate: Option<Ate>,
    /// Finally we store the direction that the snake was traveling the last
    /// time that `update` was called, which we will use to determine valid
    /// directions that it could move the next time update is called.
    last_update_dir: Direction,
    /// Store the direction that will be used in the `update` after the next `update`
    /// This is needed so a user can press two directions (eg. left then up)
    /// before one `update` has happened. It sort of queues up key press input
    next_dir: Option<Direction>,
}

impl Snake {
    pub fn new(pos: GridPosition) -> Self {
        let mut body = LinkedList::new();
        // Our snake will initially have a head and one body segment,
        // and will be moving to the right.
        body.push_back(Segment::new((pos.x - 1, pos.y).into()));
        Snake {
            head: Segment::new(pos),
            dir: Direction::Right,
            last_update_dir: Direction::Right,
            body,
            ate: None,
            next_dir: None,
        }
    }

    /// A helper function that determines whether
    /// the snake eats a given piece of Food based
    /// on its current position
    fn eats(&self, food: &Food) -> bool {
        self.head.pos == food.pos
    }

    /// A helper function that determines whether
    /// the snake eats itself based on its current position
    fn eats_self(&self) -> bool {
        for seg in self.body.iter() {
            if self.head.pos == seg.pos {
                return true;
            }
        }
        false
    }

    /// The main update function for our snake which gets called every time
    /// we want to update the game state.
    fn update(&mut self, food: &Food) {
        // If `last_update_dir` has already been updated to be the same as `dir`
        // and we have a `next_dir`, then set `dir` to `next_dir` and unset `next_dir`
        if self.last_update_dir == self.dir && self.next_dir.is_some() {
            self.dir = self.next_dir.unwrap();
            self.next_dir = None;
        }
        // First we get a new head position by using our `new_from_move` helper
        // function from earlier. We move our head in the direction we are currently
        // heading.
        let new_head_pos = GridPosition::new_from_move(self.head.pos, self.dir);
        // Next we create a new segment will be our new head segment using the
        // new position we just made.
        let new_head = Segment::new(new_head_pos);
        // Then we push our current head Segment onto the front of our body
        self.body.push_front(self.head);
        // And finally make our actual head the new Segment we created. This has
        // effectively moved the snake in the current direction.
        self.head = new_head;
        // Next we check whether the snake eats itself or some food, and if so,
        // we set our `ate` member to reflect that state.
        if self.eats_self() {
            self.ate = Some(Ate::Itself);
        } else if self.eats(food) {
            self.ate = Some(Ate::Food);
        } else {
            self.ate = None
        }
        // If we didn't eat anything this turn, we remove the last segment from our body,
        // which gives the illusion that the snake is moving. In reality, all the segments stay
        // stationary, we just add a segment to the front and remove one from the back. If we eat
        // a piece of food, then we leave the last segment so that we extend our body by one.
        if self.ate.is_none() {
            self.body.pop_back();
        }
        // And set our last_update_dir to the direction we just moved.
        self.last_update_dir = self.dir;
    }

    /// Here we have the Snake draw itself. This is very similar to how we saw the Food
    /// draw itself earlier.
    ///
    /// Again, note that this approach to drawing is fine for the limited scope of this
    /// example, but larger scale games will likely need a more optimized render path
    /// using InstanceArray or something similar that batches draw calls.
    fn draw(&self, canvas: &mut graphics::Canvas) {
        // We first iterate through the body segments and draw them.
        for seg in self.body.iter() {
            // Again we set the color (in this case an orangey color)
            // and then draw the Rect that we convert that Segment's position into
            canvas.draw(
                &graphics::Quad,
                graphics::DrawParam::new()
                    .dest_rect(seg.pos.into())
                    .color([0.3, 0.3, 0.0, 1.0]),
            );
        }
        // And then we do the same for the head, instead making it fully red to distinguish it.
        canvas.draw(
            &graphics::Quad,
            graphics::DrawParam::new()
                .dest_rect(self.head.pos.into())
                .color([1.0, 0.5, 0.0, 1.0]),
        );
    }
}

/// Now we have the heart of our game, the GameState. This struct
/// will implement ggez's `EventHandler` trait and will therefore drive
/// everything else that happens in our game.
struct GameState {
    /// First we need a Snake
    snake: Snake,
    /// A piece of food
    food: Food,
    /// Whether the game is over or not
    gameover: bool,
    /// Our RNG state
    rng: Rand32,
}

impl GameState {
    /// Our new function will set up the initial state of our game.
    pub fn new() -> Self {
        // First we put our snake a quarter of the way across our grid in the x axis
        // and half way down the y axis. This works well since we start out moving to the right.
        let snake_pos = (GRID_SIZE.0 / 4, GRID_SIZE.1 / 2).into();
        // And we seed our RNG with the system RNG.
        let mut seed: [u8; 8] = [0; 8];
        getrandom::getrandom(&mut seed[..]).expect("Could not create RNG seed");
        let mut rng = Rand32::new(u64::from_ne_bytes(seed));
        // Then we choose a random place to put our piece of food using the helper we made
        // earlier.
        let food_pos = GridPosition::random(&mut rng, GRID_SIZE.0, GRID_SIZE.1);

        GameState {
            snake: Snake::new(snake_pos),
            food: Food::new(food_pos),
            gameover: false,
            rng,
        }
    }
}

/// Now we implement EventHandler for GameState. This provides an interface
/// that ggez will call automatically when different events happen.
impl event::EventHandler<ggez::GameError> for GameState {
    /// Update will happen on every frame before it is drawn. This is where we update
    /// our game state to react to whatever is happening in the game world.
    fn update(&mut self, ctx: &mut Context) -> GameResult {
        // Rely on ggez's built-in timer for deciding when to update the game, and how many times.
        // If the update is early, there will be no cycles, otherwises, the logic will run once for each
        // frame fitting in the time since the last update.
        while ctx.time.check_update_time(DESIRED_FPS) {
            // We check to see if the game is over. If not, we'll update. If so, we'll just do nothing.
            if !self.gameover {
                // Here we do the actual updating of our game world. First we tell the snake to update itself,
                // passing in a reference to our piece of food.
                self.snake.update(&self.food);
                // Next we check if the snake ate anything as it updated.
                if let Some(ate) = self.snake.ate {
                    // If it did, we want to know what it ate.
                    match ate {
                        // If it ate a piece of food, we randomly select a new position for our piece of food
                        // and move it to this new position.
                        Ate::Food => {
                            let new_food_pos =
                                GridPosition::random(&mut self.rng, GRID_SIZE.0, GRID_SIZE.1);
                            self.food.pos = new_food_pos;
                        }
                        // If it ate itself, we set our gameover state to true.
                        Ate::Itself => {
                            self.gameover = true;
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// draw is where we should actually render the game's current state.
    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        // First we create a canvas that renders to the frame, and clear it to a (sort of) green color
        let mut canvas =
            graphics::Canvas::from_frame(ctx, graphics::Color::from([0.0, 1.0, 0.0, 1.0]));

        // Then we tell the snake and the food to draw themselves
        self.snake.draw(&mut canvas);
        self.food.draw(&mut canvas);

        // Finally, we "flush" the draw commands.
        // Since we rendered to the frame, we don't need to tell ggez to present anything else,
        // as ggez will automatically present the frame image unless told otherwise.
        canvas.finish(ctx)?;

        // We yield the current thread until the next update
        ggez::timer::yield_now();
        // And return success.
        Ok(())
    }

    /// key_down_event gets fired when a key gets pressed.
    fn key_down_event(&mut self, _ctx: &mut Context, input: KeyInput, _repeat: bool) -> GameResult {
        // Here we attempt to convert the Keycode into a Direction using the helper
        // we defined earlier.
        if let Some(dir) = input.keycode.and_then(Direction::from_keycode) {
            // If it succeeds, we check if a new direction has already been set
            // and make sure the new direction is different then `snake.dir`
            if self.snake.dir != self.snake.last_update_dir && dir.inverse() != self.snake.dir {
                self.snake.next_dir = Some(dir);
            } else if dir.inverse() != self.snake.last_update_dir {
                // If no new direction has been set and the direction is not the inverse
                // of the `last_update_dir`, then set the snake's new direction to be the
                // direction the user pressed.
                self.snake.dir = dir;
            }
        }
        Ok(())
    }
}

fn main() -> GameResult {
    // Here we use a ContextBuilder to setup metadata about our game. First the title and author
    let (ctx, events_loop) = ggez::ContextBuilder::new("snake", "Gray Olson")
        // Next we set up the window. This title will be displayed in the title bar of the window.
        .window_setup(ggez::conf::WindowSetup::default().title("Snake!"))
        // Now we get to set the size of the window, which we use our SCREEN_SIZE constant from earlier to help with
        .window_mode(ggez::conf::WindowMode::default().dimensions(SCREEN_SIZE.0, SCREEN_SIZE.1))
        // And finally we attempt to build the context and create the window. If it fails, we panic with the message
        // "Failed to build ggez context"
        .build()?;

    // Next we create a new instance of our GameState struct, which implements EventHandler
    let state = GameState::new();
    // And finally we actually run our game, passing in our context and state.
    event::run(ctx, events_loop, state)
}
```

It appears that the issue may be related to the ALSA library and a problem connecting to the server socket. I don't know how to fix this issue and I'm new to the rust lang, I would appreciate any help.

Body:
I am encountering an error when trying to run the ggez snake game example in Rust., The error message is:

ALSA lib pcm_dmix.c:999:(snd_pcm_dmix_open) unable to open slave
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
ALSA lib pcm_oss.c:397:(_snd_pcm_oss_open) Cannot open device /dev/dsp
ALSA lib pcm_oss.c:397:(_snd_pcm_oss_open) Cannot open device /dev/dsp
Failed to initialize graphics, trying secondary backends.. Please mention this if you encounter any bugs!
Error: RequestDeviceError(RequestDeviceError)

Here is the example code i'm using from ggez repo:

//! A small snake game done after watching
//! <https://www.youtube.com/watch?v=HCwMb0KslX8>
//! to showcase ggez and how it relates/differs from piston.
//!
//! Note that this example is meant to highlight the general
//! structure of a ggez game. Some of the details may need to
//! be changed to scale the game. For example, if we needed to
//! draw hundreds or thousands of shapes, a SpriteBatch is going
//! to offer far better performance than the direct draw calls
//! that this example uses.
//!
//! Author: @termhn
//! Original repo: <https://github.com/termhn/ggez_snake>

// First we'll import the crates we need for our game;
// in this case that is just `ggez` and `oorandom` (and `getrandom`
// to seed the RNG.)
use oorandom::Rand32;

// Next we need to actually `use` the pieces of ggez that we are going
// to need frequently.
use ggez::{
    event, graphics,
    input::keyboard::{KeyCode, KeyInput},
    Context, GameResult,
};

// We'll bring in some things from `std` to help us in the future.
use std::collections::LinkedList;

// The first thing we want to do is set up some constants that will help us out later.

// Here we define the size of our game board in terms of how many grid
// cells it will take up. We choose to make a 30 x 20 game board.
const GRID_SIZE: (i16, i16) = (30, 20);
// Now we define the pixel size of each tile, which we make 32x32 pixels.
const GRID_CELL_SIZE: (i16, i16) = (32, 32);

// Next we define how large we want our actual window to be by multiplying
// the components of our grid size by its corresponding pixel size.
const SCREEN_SIZE: (f32, f32) = (
    GRID_SIZE.0 as f32 * GRID_CELL_SIZE.0 as f32,
    GRID_SIZE.1 as f32 * GRID_CELL_SIZE.1 as f32,
);

// Here we're defining how often we want our game to update. This will be
// important later so that we don't have our snake fly across the screen because
// it's moving a full tile every frame.
const DESIRED_FPS: u32 = 8;

/// Now we define a struct that will hold an entity's position on our game board
/// or grid which we defined above. We'll use signed integers because we only want
/// to store whole numbers, and we need them to be signed so that they work properly
/// with our modulus arithmetic later.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct GridPosition {
    x: i16,
    y: i16,
}

impl GridPosition {
    /// We make a standard helper function so that we can create a new `GridPosition`
    /// more easily.
    pub fn new(x: i16, y: i16) -> Self {
        GridPosition { x, y }
    }

    /// As well as a helper function that will give us a random `GridPosition` from
    /// `(0, 0)` to `(max_x, max_y)`
    pub fn random(rng: &mut Rand32, max_x: i16, max_y: i16) -> Self {
        // We can use `.into()` to convert from `(i16, i16)` to a `GridPosition` since
        // we implement `From<(i16, i16)>` for `GridPosition` below.
        (
            rng.rand_range(0..(max_x as u32)) as i16,
            rng.rand_range(0..(max_y as u32)) as i16,
        )
            .into()
    }

    /// We'll make another helper function that takes one grid position and returns a new one after
    /// making one move in the direction of `dir`.
    /// We use the [rem_euclid()](https://doc.rust-lang.org/std/primitive.i16.html#method.rem_euclid)
    /// API when crossing the top/left limits, as the standard remainder function (`%`) returns a
    /// negative value when the left operand is negative.
    /// Only the Up/Left cases require rem_euclid(); for consistency, it's used for all of them.
    pub fn new_from_move(pos: GridPosition, dir: Direction) -> Self {
        match dir {
            Direction::Up => GridPosition::new(pos.x, (pos.y - 1).rem_euclid(GRID_SIZE.1)),
            Direction::Down => GridPosition::new(pos.x, (pos.y + 1).rem_euclid(GRID_SIZE.1)),
            Direction::Left => GridPosition::new((pos.x - 1).rem_euclid(GRID_SIZE.0), pos.y),
            Direction::Right => GridPosition::new((pos.x + 1).rem_euclid(GRID_SIZE.0), pos.y),
        }
    }
}

/// We implement the `From` trait, which in this case allows us to convert easily between
/// a GridPosition and a ggez `graphics::Rect` which fills that grid cell.
/// Now we can just call `.into()` on a `GridPosition` where we want a
/// `Rect` that represents that grid cell.
impl From<GridPosition> for graphics::Rect {
    fn from(pos: GridPosition) -> Self {
        graphics::Rect::new_i32(
            pos.x as i32 * GRID_CELL_SIZE.0 as i32,
            pos.y as i32 * GRID_CELL_SIZE.1 as i32,
            GRID_CELL_SIZE.0 as i32,
            GRID_CELL_SIZE.1 as i32,
        )
    }
}

/// And here we implement `From` again to allow us to easily convert between
/// `(i16, i16)` and a `GridPosition`.
impl From<(i16, i16)> for GridPosition {
    fn from(pos: (i16, i16)) -> Self {
        GridPosition { x: pos.0, y: pos.1 }
    }
}

/// Next we create an enum that will represent all the possible
/// directions that our snake could move.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Direction {
    Up,
    Down,
    Left,
    Right,
}

impl Direction {
    /// We create a helper function that will allow us to easily get the inverse
    /// of a `Direction` which we can use later to check if the player should be
    /// able to move the snake in a certain direction.
    pub fn inverse(&self) -> Self {
        match *self {
            Direction::Up => Direction::Down,
            Direction::Down => Direction::Up,
            Direction::Left => Direction::Right,
            Direction::Right => Direction::Left,
        }
    }

    /// We also create a helper function that will let us convert between a
    /// `ggez` `Keycode` and the `Direction` that it represents. Of course,
    /// not every keycode represents a direction, so we return `None` if this
    /// is the case.
    pub fn from_keycode(key: KeyCode) -> Option<Direction> {
        match key {
            KeyCode::Up => Some(Direction::Up),
            KeyCode::Down => Some(Direction::Down),
            KeyCode::Left => Some(Direction::Left),
            KeyCode::Right => Some(Direction::Right),
            _ => None,
        }
    }
}

/// This is mostly just a semantic abstraction over a `GridPosition` to represent
/// a segment of the snake. It could be useful to, say, have each segment contain its
/// own color or something similar. This is an exercise left up to the reader ;)
#[derive(Clone, Copy, Debug)]
struct Segment {
    pos: GridPosition,
}

impl Segment {
    pub fn new(pos: GridPosition) -> Self {
        Segment { pos }
    }
}

/// This is again an abstraction over a `GridPosition` that represents
/// a piece of food the snake can eat. It can draw itself.
struct Food {
    pos: GridPosition,
}

impl Food {
    pub fn new(pos: GridPosition) -> Self {
        Food { pos }
    }

    /// Here is the first time we see what drawing looks like with ggez.
    /// We have a function that takes in a `&mut ggez::graphics::Canvas` which we use
    /// to do drawing.
    ///
    /// Note: this method of drawing does not scale. If you need to render
    /// a large number of shapes, use an InstanceArray. This approach is fine for
    /// this example since there are a fairly limited number of calls.
    fn draw(&self, canvas: &mut graphics::Canvas) {
        // First we set the color to draw with, in this case all food will be
        // colored blue.
        let color = [0.0, 0.0, 1.0, 1.0];
        // Then we draw a rectangle with the Fill draw mode, and we convert the
        // Food's position into a `ggez::Rect` using `.into()` which we can do
        // since we implemented `From<GridPosition>` for `Rect` earlier.
        canvas.draw(
            &graphics::Quad,
            graphics::DrawParam::new()
                .dest_rect(self.pos.into())
                .color(color),
        );
    }
}

/// Here we define an enum of the possible things that the snake could have "eaten"
/// during an update of the game. It could have either eaten a piece of `Food`, or
/// it could have eaten `Itself` if the head ran into its body.
#[derive(Clone, Copy, Debug)]
enum Ate {
    Itself,
    Food,
}

/// Now we make a struct that contains all the information needed to describe the
/// state of the Snake itself.
struct Snake {
    /// First we have the head of the snake, which is a single `Segment`.
    head: Segment,
    /// Then we have the current direction the snake is moving. This is
    /// the direction it will move when `update` is called on it.
    dir: Direction,
    /// Next we have the body, which we choose to represent as a `LinkedList`
    /// of `Segment`s.
    body: LinkedList<Segment>,
    /// Now we have a property that represents the result of the last update
    /// that was performed. The snake could have eaten nothing (None), Food (Some(Ate::Food)),
    /// or Itself (Some(Ate::Itself))
    ate: Option<Ate>,
    /// Finally we store the direction that the snake was traveling the last
    /// time that `update` was called, which we will use to determine valid
    /// directions that it could move the next time update is called.
    last_update_dir: Direction,
    /// Store the direction that will be used in the `update` after the next `update`
    /// This is needed so a user can press two directions (eg. left then up)
    /// before one `update` has happened. It sort of queues up key press input
    next_dir: Option<Direction>,
}

impl Snake {
    pub fn new(pos: GridPosition) -> Self {
        let mut body = LinkedList::new();
        // Our snake will initially have a head and one body segment,
        // and will be moving to the right.
        body.push_back(Segment::new((pos.x - 1, pos.y).into()));
        Snake {
            head: Segment::new(pos),
            dir: Direction::Right,
            last_update_dir: Direction::Right,
            body,
            ate: None,
            next_dir: None,
        }
    }

    /// A helper function that determines whether
    /// the snake eats a given piece of Food based
    /// on its current position
    fn eats(&self, food: &Food) -> bool {
        self.head.pos == food.pos
    }

    /// A helper function that determines whether
    /// the snake eats itself based on its current position
    fn eats_self(&self) -> bool {
        for seg in self.body.iter() {
            if self.head.pos == seg.pos {
                return true;
            }
        }
        false
    }

    /// The main update function for our snake which gets called every time
    /// we want to update the game state.
    fn update(&mut self, food: &Food) {
        // If `last_update_dir` has already been updated to be the same as `dir`
        // and we have a `next_dir`, then set `dir` to `next_dir` and unset `next_dir`
        if self.last_update_dir == self.dir && self.next_dir.is_some() {
            self.dir = self.next_dir.unwrap();
            self.next_dir = None;
        }
        // First we get a new head position by using our `new_from_move` helper
        // function from earlier. We move our head in the direction we are currently
        // heading.
        let new_head_pos = GridPosition::new_from_move(self.head.pos, self.dir);
        // Next we create a new segment will be our new head segment using the
        // new position we just made.
        let new_head = Segment::new(new_head_pos);
        // Then we push our current head Segment onto the front of our body
        self.body.push_front(self.head);
        // And finally make our actual head the new Segment we created. This has
        // effectively moved the snake in the current direction.
        self.head = new_head;
        // Next we check whether the snake eats itself or some food, and if so,
        // we set our `ate` member to reflect that state.
        if self.eats_self() {
            self.ate = Some(Ate::Itself);
        } else if self.eats(food) {
            self.ate = Some(Ate::Food);
        } else {
            self.ate = None
        }
        // If we didn't eat anything this turn, we remove the last segment from our body,
        // which gives the illusion that the snake is moving. In reality, all the segments stay
        // stationary, we just add a segment to the front and remove one from the back. If we eat
        // a piece of food, then we leave the last segment so that we extend our body by one.
        if self.ate.is_none() {
            self.body.pop_back();
        }
        // And set our last_update_dir to the direction we just moved.
        self.last_update_dir = self.dir;
    }

    /// Here we have the Snake draw itself. This is very similar to how we saw the Food
    /// draw itself earlier.
    ///
    /// Again, note that this approach to drawing is fine for the limited scope of this
    /// example, but larger scale games will likely need a more optimized render path
    /// using InstanceArray or something similar that batches draw calls.
    fn draw(&self, canvas: &mut graphics::Canvas) {
        // We first iterate through the body segments and draw them.
        for seg in self.body.iter() {
            // Again we set the color (in this case an orangey color)
            // and then draw the Rect that we convert that Segment's position into
            canvas.draw(
                &graphics::Quad,
                graphics::DrawParam::new()
                    .dest_rect(seg.pos.into())
                    .color([0.3, 0.3, 0.0, 1.0]),
            );
        }
        // And then we do the same for the head, instead making it fully red to distinguish it.
        canvas.draw(
            &graphics::Quad,
            graphics::DrawParam::new()
                .dest_rect(self.head.pos.into())
                .color([1.0, 0.5, 0.0, 1.0]),
        );
    }
}

/// Now we have the heart of our game, the GameState. This struct
/// will implement ggez's `EventHandler` trait and will therefore drive
/// everything else that happens in our game.
struct GameState {
    /// First we need a Snake
    snake: Snake,
    /// A piece of food
    food: Food,
    /// Whether the game is over or not
    gameover: bool,
    /// Our RNG state
    rng: Rand32,
}

impl GameState {
    /// Our new function will set up the initial state of our game.
    pub fn new() -> Self {
        // First we put our snake a quarter of the way across our grid in the x axis
        // and half way down the y axis. This works well since we start out moving to the right.
        let snake_pos = (GRID_SIZE.0 / 4, GRID_SIZE.1 / 2).into();
        // And we seed our RNG with the system RNG.
        let mut seed: [u8; 8] = [0; 8];
        getrandom::getrandom(&mut seed[..]).expect("Could not create RNG seed");
        let mut rng = Rand32::new(u64::from_ne_bytes(seed));
        // Then we choose a random place to put our piece of food using the helper we made
        // earlier.
        let food_pos = GridPosition::random(&mut rng, GRID_SIZE.0, GRID_SIZE.1);

        GameState {
            snake: Snake::new(snake_pos),
            food: Food::new(food_pos),
            gameover: false,
            rng,
        }
    }
}

/// Now we implement EventHandler for GameState. This provides an interface
/// that ggez will call automatically when different events happen.
impl event::EventHandler<ggez::GameError> for GameState {
    /// Update will happen on every frame before it is drawn. This is where we update
    /// our game state to react to whatever is happening in the game world.
    fn update(&mut self, ctx: &mut Context) -> GameResult {
        // Rely on ggez's built-in timer for deciding when to update the game, and how many times.
        // If the update is early, there will be no cycles, otherwises, the logic will run once for each
        // frame fitting in the time since the last update.
        while ctx.time.check_update_time(DESIRED_FPS) {
            // We check to see if the game is over. If not, we'll update. If so, we'll just do nothing.
            if !self.gameover {
                // Here we do the actual updating of our game world. First we tell the snake to update itself,
                // passing in a reference to our piece of food.
                self.snake.update(&self.food);
                // Next we check if the snake ate anything as it updated.
                if let Some(ate) = self.snake.ate {
                    // If it did, we want to know what it ate.
                    match ate {
                        // If it ate a piece of food, we randomly select a new position for our piece of food
                        // and move it to this new position.
                        Ate::Food => {
                            let new_food_pos =
                                GridPosition::random(&mut self.rng, GRID_SIZE.0, GRID_SIZE.1);
                            self.food.pos = new_food_pos;
                        }
                        // If it ate itself, we set our gameover state to true.
                        Ate::Itself => {
                            self.gameover = true;
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// draw is where we should actually render the game's current state.
    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        // First we create a canvas that renders to the frame, and clear it to a (sort of) green color
        let mut canvas =
            graphics::Canvas::from_frame(ctx, graphics::Color::from([0.0, 1.0, 0.0, 1.0]));

        // Then we tell the snake and the food to draw themselves
        self.snake.draw(&mut canvas);
        self.food.draw(&mut canvas);

        // Finally, we "flush" the draw commands.
        // Since we rendered to the frame, we don't need to tell ggez to present anything else,
        // as ggez will automatically present the frame image unless told otherwise.
        canvas.finish(ctx)?;

        // We yield the current thread until the next update
        ggez::timer::yield_now();
        // And return success.
        Ok(())
    }

    /// key_down_event gets fired when a key gets pressed.
    fn key_down_event(&mut self, _ctx: &mut Context, input: KeyInput, _repeat: bool) -> GameResult {
        // Here we attempt to convert the Keycode into a Direction using the helper
        // we defined earlier.
        if let Some(dir) = input.keycode.and_then(Direction::from_keycode) {
            // If it succeeds, we check if a new direction has already been set
            // and make sure the new direction is different then `snake.dir`
            if self.snake.dir != self.snake.last_update_dir && dir.inverse() != self.snake.dir {
                self.snake.next_dir = Some(dir);
            } else if dir.inverse() != self.snake.last_update_dir {
                // If no new direction has been set and the direction is not the inverse
                // of the `last_update_dir`, then set the snake's new direction to be the
                // direction the user pressed.
                self.snake.dir = dir;
            }
        }
        Ok(())
    }
}

fn main() -> GameResult {
    // Here we use a ContextBuilder to setup metadata about our game. First the title and author
    let (ctx, events_loop) = ggez::ContextBuilder::new("snake", "Gray Olson")
        // Next we set up the window. This title will be displayed in the title bar of the window.
        .window_setup(ggez::conf::WindowSetup::default().title("Snake!"))
        // Now we get to set the size of the window, which we use our SCREEN_SIZE constant from earlier to help with
        .window_mode(ggez::conf::WindowMode::default().dimensions(SCREEN_SIZE.0, SCREEN_SIZE.1))
        // And finally we attempt to build the context and create the window. If it fails, we panic with the message
        // "Failed to build ggez context"
        .build()?;

    // Next we create a new instance of our GameState struct, which implements EventHandler
    let state = GameState::new();
    // And finally we actually run our game, passing in our context and state.
    event::run(ctx, events_loop, state)
}

It appears that the issue may be related to the ALSA library and a problem connecting to the server socket. I don't know how to fix this issue and I'm new to the rust lang, I would appreciate any help.


问:
Converting every n rows of the table to single row with n columns by Kusto Query Language
I have the following output for my query:

```<code>LogEntry
'@timestamp': '2022-12-11T12:36:59.258Z',
msName: 'frontend',
level: 'ERROR',
message: 'Get categories failed with the error: Error: Request failed with status code 503'
userId: ''
req: 'http://ssm.att.com/'
'@timestamp': '2022-12-11T12:38:507.258Z',
msName: 'frontend',
level: 'INFO',
message: 'clearSession failed with the error: SyntaxError: Exponent part is missing a number in JSON at position 2'
userId: ''
req: 'http://ssm.att.com/'
</code>```

and so on i.e., this pattern repeats every 6 rows.

I would like to perform some manipulation by Kusto Query Language to get one row with 6 columns for every 6 rows i.e.

```<code>timestamp                  msName    level  message          userId  req
2022-12-11T12:36:59.258Z   frontend  ERROR  Get categor...           http://ssm.att.com
2022-12-11T12:38:507.258Z  fromtend  INFO   clearSession ...         http://ssm.att.com
</code>```

etc.

Please advise

I just tried to see which function can be used but did not find something useful

```<code>a,b,c
1,2,3
4,5,6
</code>```

a
b
c

1
2
3

4
5
6

https://ozh.github.io/ascii-tables/

LogEntry
'@timestamp': '2022-12-11T12:36:59.258Z',
msName: 'frontend',
level: 'ERROR',
message: 'Get categories failed with the error: Error: Request failed with status code 503'
userId: ''
req: 'http://ssm.att.com/'
'@timestamp': '2022-12-11T12:38:507.258Z',
msName: 'frontend',
level: 'INFO',
message: 'clearSession failed with the error: SyntaxError: Exponent part is missing a number in JSON at position 2'
userId: ''
req: 'http://ssm.att.com/'

There is no additional column

Body:
I have the following output for my query:

LogEntry
'@timestamp': '2022-12-11T12:36:59.258Z',
msName: 'frontend',
level: 'ERROR',
message: 'Get categories failed with the error: Error: Request failed with status code 503'
userId: ''
req: 'http://ssm.att.com/'
'@timestamp': '2022-12-11T12:38:507.258Z',
msName: 'frontend',
level: 'INFO',
message: 'clearSession failed with the error: SyntaxError: Exponent part is missing a number in JSON at position 2'
userId: ''
req: 'http://ssm.att.com/'

and so on i.e., this pattern repeats every 6 rows.

I would like to perform some manipulation by Kusto Query Language to get one row with 6 columns for every 6 rows i.e.

timestamp                  msName    level  message          userId  req
2022-12-11T12:36:59.258Z   frontend  ERROR  Get categor...           http://ssm.att.com
2022-12-11T12:38:507.258Z  fromtend  INFO   clearSession ...         http://ssm.att.com

etc.

Please advise

I just tried to see which function can be used but did not find something useful

a,b,c
1,2,3
4,5,6

a
b
c

1
2
3

4
5
6

https://ozh.github.io/ascii-tables/

LogEntry
'@timestamp': '2022-12-11T12:36:59.258Z',
msName: 'frontend',
level: 'ERROR',
message: 'Get categories failed with the error: Error: Request failed with status code 503'
userId: ''
req: 'http://ssm.att.com/'
'@timestamp': '2022-12-11T12:38:507.258Z',
msName: 'frontend',
level: 'INFO',
message: 'clearSession failed with the error: SyntaxError: Exponent part is missing a number in JSON at position 2'
userId: ''
req: 'http://ssm.att.com/'

There is no additional column


问:
vscode how to stop debuger automatically run
When I run the script in the picture below, the debugger also runs. but I never set it up  like that, it just automatically runs without my permission, How can I stop this behavior ?

As you can see in the console, it says debugger attached, I never ask vs code to attach the debugger.