问:
Closing figures from previous sessions
I am running a python code that produces some figures with Matplotlib and Pandas. After a few runs of the code, I am getting to following error:

RuntimeWarning: More than 20 figures have been opened. Figures created
through the pyplot interface (matplotlib.pyplot.figure) are retained
until explicitly closed and may consume too much memory. (To control
this warning, see the rcParam figure.max_open_warning)

I think this is because I forgot to close the figures after each run of the code. I have tried

```<code>plt.close('all')
</code>```

but it does not close the figures from previous sessions. Restarting the terminal (conda) did not help either.

答:
You have a really similar issue with really good and detailed answers in this thread.

I can tell you that you are probably creating figures in a loop or over and over with more than one execution, so you need to use the methods .clf and .cla to close the figures you are creating. But, you have all the detailed info in the above thread.

Title: Closing figures from previous sessions

Body:
I am running a python code that produces some figures with Matplotlib and Pandas. After a few runs of the code, I am getting to following error:

RuntimeWarning: More than 20 figures have been opened. Figures created
through the pyplot interface (matplotlib.pyplot.figure) are retained
until explicitly closed and may consume too much memory. (To control
this warning, see the rcParam figure.max_open_warning)

I think this is because I forgot to close the figures after each run of the code. I have tried

plt.close('all')

but it does not close the figures from previous sessions. Restarting the terminal (conda) did not help either.


来源: stackexchange

问:
Django how to set a class based view queryset with function return
im trying to make endless pagination with filtered data and im geting the data with get request.

views.py:

```<code>class ProductsView(ListView):

    paginate_by = 20
    context_object_name = 'products'
    template_name = "urunler.html"
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        renkler = Renk.objects.all()
        beden = Varyasyon.objects.all()
        katagori = Grub.objects.all()
        order = self.request.GET.get('order')
        filtered = Stok.objects.all().order_by('-urun_id__kayit_tarihi','foto').distinct('urun_id__kayit_tarihi','foto')
        checked_var = self.request.GET.getlist('varyasyon_id__in')
        checked_renk = self.request.GET.getlist('renk_id__in')
        checked_kat = self.request.GET.getlist('grub_id__in')
        if self.request.GET.getlist("varyasyon_id__in"):
            filtered = filtered.filter(
                Q(varyasyon_id__in = self.request.GET.getlist("varyasyon_id__in"))
            )
        if self.request.GET.getlist("renk_id__in"):
            filtered = filtered.filter(
                Q(renk_id__in = self.request.GET.getlist("renk_id__in"))
            )
        if self.request.GET.getlist("grub_id__in"):
            filtered = filtered.filter(
                Q(grub_id__in = self.request.GET.getlist("grub_id__in"))
            )

        if order == "date":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
        )
        elif order == "sale":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(indirim = True)
        )
        elif order == "tesettur":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(urun_id__tesettur = True)
        )
        else:
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
        )

        context = {"renkler":renkler,"bedenler":beden,"katagoriler":katagori,'filtered':filters,'checkedvar':checked_var,'checkedrenk':checked_renk,'checkedkat':checked_kat}
        self.queryset = context
        return context
    queryset = get_context_data()
</code>```

i want to set the queryset from get_context_data's return but it asks for self argument.

error

```<code>TypeError: ProductsView.get_context_data() missing 1 required positional argument: 'self'
</code>```

when i define queryset on the top it says that get_context_data is not defined.

答:
Maybe you should override get_queryset method. A queryset is not a context dict:

```<code>class ProductsView(ListView):

    paginate_by = 20
    context_object_name = 'products'
    template_name = "urunler.html"

    def get_queryset(self):
        queryset = super().get_queryset()

        # do stuff here to change queryset dynamically
        ...

        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # do stuff here to update your context dict
        ...

        return context
</code>```

ContentLicense: CC BY-SA 4.0

Body:
im trying to make endless pagination with filtered data and im geting the data with get request.

views.py:

class ProductsView(ListView):

    paginate_by = 20
    context_object_name = 'products'
    template_name = "urunler.html"
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        renkler = Renk.objects.all()
        beden = Varyasyon.objects.all()
        katagori = Grub.objects.all()
        order = self.request.GET.get('order')
        filtered = Stok.objects.all().order_by('-urun_id__kayit_tarihi','foto').distinct('urun_id__kayit_tarihi','foto')
        checked_var = self.request.GET.getlist('varyasyon_id__in')
        checked_renk = self.request.GET.getlist('renk_id__in')
        checked_kat = self.request.GET.getlist('grub_id__in')
        if self.request.GET.getlist("varyasyon_id__in"):
            filtered = filtered.filter(
                Q(varyasyon_id__in = self.request.GET.getlist("varyasyon_id__in"))
            )
        if self.request.GET.getlist("renk_id__in"):
            filtered = filtered.filter(
                Q(renk_id__in = self.request.GET.getlist("renk_id__in"))
            )
        if self.request.GET.getlist("grub_id__in"):
            filtered = filtered.filter(
                Q(grub_id__in = self.request.GET.getlist("grub_id__in"))
            )

        if order == "date":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
        )
        elif order == "sale":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(indirim = True)
        )
        elif order == "tesettur":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(urun_id__tesettur = True)
        )
        else:
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
        )

        context = {"renkler":renkler,"bedenler":beden,"katagoriler":katagori,'filtered':filters,'checkedvar':checked_var,'checkedrenk':checked_renk,'checkedkat':checked_kat}
        self.queryset = context
        return context
    queryset = get_context_data()

i want to set the queryset from get_context_data's return but it asks for self argument.

error

TypeError: ProductsView.get_context_data() missing 1 required positional argument: 'self'

when i define queryset on the top it says that get_context_data is not defined.

Body:
Maybe you should override get_queryset method. A queryset is not a context dict:

class ProductsView(ListView):

    paginate_by = 20
    context_object_name = 'products'
    template_name = "urunler.html"

    def get_queryset(self):
        queryset = super().get_queryset()

        # do stuff here to change queryset dynamically
        ...

        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # do stuff here to update your context dict
        ...

        return context


问:
react-hooks/exhaustive-deps not showing in VS code
I have a .eslintrc file with the following rules:

```<code>"rules": {
    "prettier/prettier": "error",
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "error",
    "no-console": "warn"
},
</code>```

I've installed: eslint-plugin-prettier, eslint-config-prettier and eslint-plugin-react-hooks

I've enabled "eslint.validate": [ "javascript", "javascriptreact", "html", "typescriptreact" ], in settings.json in vscode

but when I remove dependencies that are needed in a useEffect, it's not showing an error that I hoped it would

what else do I need to do?

答:
This worked for me only when I updated react-scripts to 4.x.x

It also helps to restart the ESLint server in VScode after doing this

hgb123 answer also is useful if you haven't already done that

Body:
I have a .eslintrc file with the following rules:

"rules": {
    "prettier/prettier": "error",
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "error",
    "no-console": "warn"
},

I've installed: eslint-plugin-prettier, eslint-config-prettier and eslint-plugin-react-hooks

I've enabled "eslint.validate": [ "javascript", "javascriptreact", "html", "typescriptreact" ], in settings.json in vscode

but when I remove dependencies that are needed in a useEffect, it's not showing an error that I hoped it would

what else do I need to do?


问:
Can I store data on an Android device to persist between installs?
I want to store a small amount of data in a way where it persists between application installs. I obviously can't use SharedPreferences as they are removes upon uninstallation. Is there any way to store data so it survives a reinstall of the app?

The data I want to store is a unique ID, to allow blocking of users of the app if they misbehave. If I cannot store an ID, can I access the Google account(s) email addresses to use them as an indicator?

This blog post makes it clear none of the IDs the OS produces are any good, especially when considering tablets
Android: Identifying app installations

答: yes. you can store some data in the internal memory or the sd card.this can be done by creating(.somename)folder which is invisible to user and create a file.txt to store the data.</p>

ContentLicense: CC BY-SA 3.0


问:
Why is there a memory leak?
I need to create a large image (w <= 20k, h <= 100k)
I divide it into fragments (w = 20k, h = 5k) and store them in the database in a loop.
But I still get an out of memory error. in the heap 1.5 gigabytes.
Why is there a memory leak? According to my plan, only the current fragment, which weighs about 300 megabytes, should be stored in the heap.

```<code>@Transactional
public long createNewChart (int width, int height) {
    Chartographer chartographer = new Chartographer(width, height);
    chartRepo.save(chartographer);

    int number = 0;
    while (height >= 5000) {
        BufferedImage fragment = new BufferedImage(width, 5000, BufferedImage.TYPE_INT_RGB);
        fragmentRepo.save(new Fragment(imageOperator.imageAsBytes(fragment), number, chartographer));
        height -= 5000;
        number++;
    }
    if (height > 0) {
        BufferedImage fragment = new BufferedImage(width, height % 5000, BufferedImage.TYPE_INT_RGB);
        fragmentRepo.save(new Fragment(imageOperator.imageAsBytes(fragment), number, chartographer));
    }
    return chartographer.getCharId();
}

public byte[] imageAsBytes (BufferedImage image) {
    try(ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
        ImageIO.write(image, "bmp", stream);
        return stream.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
</code>```

enter image description here

答:
If I am not mistaking, according to your code, you are creating a new byte[] array with width, height % 5000 for every save.  So the memory is allocated either way, and the garbage collector did not have a chance to remove the older byte[] arrays before out of memory.

You could try to create a local variable byte[] array and attempt to stream.toByteArray() in it, before doing fragementRepo.save() that way java uses the same memory reference and overwrites.

Title: Why is there a memory leak?

Body:
I need to create a large image (w <= 20k, h <= 100k)
I divide it into fragments (w = 20k, h = 5k) and store them in the database in a loop.
But I still get an out of memory error. in the heap 1.5 gigabytes.
Why is there a memory leak? According to my plan, only the current fragment, which weighs about 300 megabytes, should be stored in the heap.

@Transactional
public long createNewChart (int width, int height) {
    Chartographer chartographer = new Chartographer(width, height);
    chartRepo.save(chartographer);

    int number = 0;
    while (height >= 5000) {
        BufferedImage fragment = new BufferedImage(width, 5000, BufferedImage.TYPE_INT_RGB);
        fragmentRepo.save(new Fragment(imageOperator.imageAsBytes(fragment), number, chartographer));
        height -= 5000;
        number++;
    }
    if (height > 0) {
        BufferedImage fragment = new BufferedImage(width, height % 5000, BufferedImage.TYPE_INT_RGB);
        fragmentRepo.save(new Fragment(imageOperator.imageAsBytes(fragment), number, chartographer));
    }
    return chartographer.getCharId();
}

public byte[] imageAsBytes (BufferedImage image) {
    try(ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
        ImageIO.write(image, "bmp", stream);
        return stream.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

enter image description here


问:
pulling branch that doesn't have a folder from master
I entered a new project and I cloned the repository locally. Now I see what is in the master branch on that repository. So, I did

```<code>git checkout -b new_branch
</code>```

Now I am in the new_branch. Everything is great, but I want to pull something from other branch, so I do

```<code>git pull origin other_branch
</code>```

The thing is that "other_branch" doesn't have a folder which "master" branch has, but locally I didn't loose it by pulling. I don't want that folder locally because I only want communication with "other_branch", and not "master". How to solve that issue?

答:
What does git status say about the additional folder?

EDIT 1

Since I do not know more about your situation. You could try to remove the whole repo first (I know not the git way , but without a proper git status output I am unable to resolve all the posibilites in my head) and then directly clone the repo with the proper branch git clone -b other_branch <url> see git help for more info

Body:
I entered a new project and I cloned the repository locally. Now I see what is in the master branch on that repository. So, I did

git checkout -b new_branch

Now I am in the new_branch. Everything is great, but I want to pull something from other branch, so I do

git pull origin other_branch

The thing is that "other_branch" doesn't have a folder which "master" branch has, but locally I didn't loose it by pulling. I don't want that folder locally because I only want communication with "other_branch", and not "master". How to solve that issue?


问:
How to get the key and value from map and perform certain operation on each key and value using Java8 methods
How to get the key and value from map and perform certain operation on each key and value using Java8 methods

I got some methods but it helps only to print the message(using System.out.println),but I want to perform some operations(finding duplicates in value,comparing values using casting etc.,) in each key/value pair

Map<String,String> l_map=new TreeMap<String,String>();

Thanks in advance!

答: Oldschool approach could be to use the method Map.entrySet() that returns a Set<Map.Entry<K,V>> (set of key-value pairs) where you can access data with Map.Entry<K,V>.getKey() and Map.Entry<K,V>.getValue())


问:
Crop a PNG image to its minimum size
How to cut off the blank border area of a PNG image and shrink it to its minimum size using Python?

NB: The border size is not a fixed value, but may vary per image.

答:
The other answers did not work for me while writing a Blender script (cannot use PIL), so maybe someone else will find this useful.</p>
```<code>import numpy as np

def crop(crop_file):
    """crop the image, removing invisible borders"""
    image = bpy.data.images.load(crop_file, check_existing=False)
    w, h = image.size

    print("Original size: " + str(w) + " x " + str(h))

    linear_pixels = image.pixels[:]
    pixels4d = np.reshape(linear_pixels, (h, w, 4))

    mask = pixels4d [:,:,3] != 0.
    coords = np.argwhere(mask)
    y0, x0 = coords.min(axis=0)
    y1, x1 = coords.max(axis=0) + 1
    cropped_box = pixels4d[y0:y1, x0:x1, :]

    w1, h1 = x1 - x0, y1 - y0
    print("Crop size: " + str(w1) + " x " + str(h1))

    temp_image = bpy.data.images.new(crop_file, alpha=True, width=w1, height=h1)
    temp_image.pixels[:] = cropped_box.ravel()
    temp_image.filepath_raw = crop_file
    temp_image.file_format = 'PNG'
    temp_image.alpha_mode = 'STRAIGHT'
    temp_image.save()
</code>```

Title: Crop a PNG image to its minimum size

Body:
The other answers did not work for me while writing a Blender script (cannot use PIL), so maybe someone else will find this useful.

import numpy as np

def crop(crop_file):
    """crop the image, removing invisible borders"""
    image = bpy.data.images.load(crop_file, check_existing=False)
    w, h = image.size

    print("Original size: " + str(w) + " x " + str(h))

    linear_pixels = image.pixels[:]
    pixels4d = np.reshape(linear_pixels, (h, w, 4))

    mask = pixels4d [:,:,3] != 0.
    coords = np.argwhere(mask)
    y0, x0 = coords.min(axis=0)
    y1, x1 = coords.max(axis=0) + 1
    cropped_box = pixels4d[y0:y1, x0:x1, :]

    w1, h1 = x1 - x0, y1 - y0
    print("Crop size: " + str(w1) + " x " + str(h1))

    temp_image = bpy.data.images.new(crop_file, alpha=True, width=w1, height=h1)
    temp_image.pixels[:] = cropped_box.ravel()
    temp_image.filepath_raw = crop_file
    temp_image.file_format = 'PNG'
    temp_image.alpha_mode = 'STRAIGHT'
    temp_image.save()


问:
Kendo Filter widget can support relative fields for filtering?
I am trying to implement filter which can support relative fields i.e. the first field would be table names once user choose any table then second field gets populated with all columns available for selected table. Now users can choose operator and pass value for filtering the column value. So basically I want to filter on basis of column's value. As I dont want to put all columns for all tables in one field because that makes my drop down very long as I have huge columns in some table and also user wont be able to search specific column easily hence I want to introduce one more field which is table drop down. Once user select from table drop down then column dropdown will only have selected table column which reduce the columns number and user can choose easily. see the attached screenshot for same.  So the expression preview should be something like .   e.g. "table1.column5 is equal to myvalue". How we can achieve this ? I tried using editortemplate of field property of kendo Filter widget and added field 2 as shown in attached screen shot but after that not able to get field 2 value in expression. Can someone suggest what are the other ways we can achieve this ?

答:
I have recieved the answer for this question by telerik support team. Posting same here to help someone in future:

I went through several different scenarios, however the desired functionality is not supported with the current implementation of the Filter widget. The reason is that the filter that you see in the expression preview - "field is equal to value", is based upon the filter fields in the widget's and datasource configurations.
Example:

```<code>var dataSource = new kendo.data.DataSource({
    data: data,
    schema: {
      model: {
        fields: {
          name: { type: "string" },
          age: { type: "number" },
          city: {type: "string"},
          money: {type: "number"}
        }
      }
    }
</code>```

In this case the name of the field must be one that is available in the model.fields configuration. In other words, in order for the filter to work properly, you'll need to have all of the table.column combinations inside the schema, example:

```<code>fields: {
          table1.name: { type: "string" },
          table1.age: { type: "number" },
          table1.city: {type: "string"},
          table1.money: {type: "number"},
          table2.age: { type: "number" },
          table2.city: {type: "string"},
          table2.money: {type: "number"},
          table3.age: { type: "number" },
          table3.city: {type: "string"},
          table4.money: {type: "number"},
          ...
        }
</code>```

An alternative approach that I can suggest is to filter the second dropdownlist based on the selection of the first. You should keep in mind that this doesn't change the expression itself, in other words you still won't be able to create a filter that has a table.column field name.
Example, table1 is selected in the first dropdown and we have name and age options in the second one:

Example, table2 is selected in the first dropdown and we have city and money options in the second one:

I've prepared an example which demonstrates the above functionality:
https://dojo.telerik.com/@gdenchev/AHAmocIM

DOJO link content in case link disabled in future:

 <!DOCTYPE html>

        <meta charset="utf-8"/>
        <title>Kendo UI Snippet</title>

        <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2022.1.119/styles/kendo.default-v2.min.css"/>

    ```

Body:
I have recieved the answer for this question by telerik support team. Posting same here to help someone in future:

I went through several different scenarios, however the desired functionality is not supported with the current implementation of the Filter widget. The reason is that the filter that you see in the expression preview - "field is equal to value", is based upon the filter fields in the widget's and datasource configurations.
Example:

var dataSource = new kendo.data.DataSource({
    data: data,
    schema: {
      model: {
        fields: {
          name: { type: "string" },
          age: { type: "number" },
          city: {type: "string"},
          money: {type: "number"}
        }
      }
    }

In this case the name of the field must be one that is available in the model.fields configuration. In other words, in order for the filter to work properly, you'll need to have all of the table.column combinations inside the schema, example:

fields: {
          table1.name: { type: "string" },
          table1.age: { type: "number" },
          table1.city: {type: "string"},
          table1.money: {type: "number"},
          table2.age: { type: "number" },
          table2.city: {type: "string"},
          table2.money: {type: "number"},
          table3.age: { type: "number" },
          table3.city: {type: "string"},
          table4.money: {type: "number"},
          ...
        }

An alternative approach that I can suggest is to filter the second dropdownlist based on the selection of the first. You should keep in mind that this doesn't change the expression itself, in other words you still won't be able to create a filter that has a table.column field name.
Example, table1 is selected in the first dropdown and we have name and age options in the second one:

Example, table2 is selected in the first dropdown and we have city and money options in the second one:

I've prepared an example which demonstrates the above functionality:
https://dojo.telerik.com/@gdenchev/AHAmocIM

DOJO link content in case link disabled in future:

 <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8"/>
        <title>Kendo UI Snippet</title>

        <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2022.1.119/styles/kendo.default-v2.min.css"/>

        <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
        <script src="https://kendo.cdn.telerik.com/2022.1.119/js/kendo.all.min.js"></script>
      </head>
      <body>

        <div id="filter"></div>
        <br /><br />
        <script>
          var data = [
            { name: "Jane Doe", age: 30, city: "City1", money: 60 },
            { name: "John Doe", age: 33, city: "City2", money: 90 }
          ];

          var dataSource = new kendo.data.DataSource({
            data: data,
            schema: {
              model: {
                fields: {
                  name: { type: "string" },
                  age: { type: "number" },
                  city: {type: "string"},
                  money: {type: "number"}
                }
              }
            }
          });

          $("#filter").kendoFilter({
            dataSource: dataSource,
            expressionPreview: true
          });

          $(".k-filter-toolbar-item:eq(1)").on("click", function(e) {
            let filter = $("#filter").data("kendoFilter");
            filter.one("change", function(e) {
              let filterRow = $(".k-filter-item:last").find(".k-filter-field");
              let firstDropDown = filterRow.find("select").data("kendoDropDownList");
              let secondDropDown = $("<input />")
              .insertBefore(filterRow)
              .kendoDropDownList({
                dataSource: {
                  data: ["table1", "table2"]
                },
                change: function() {
                  let value = this.value();
                  let columnsForTableOne = [{text: "name", value: "name"},{text: "age", value: "age"}];
                  let columnsForTableTwo = [{text: "city", value: "city"},{text: "money", value: "money"}];
                  let data;

                  switch(value) {
                    case "table1": data = columnsForTableOne;
                      break;
                    case "table2": data = columnsForTableTwo;
                      break;
                  }
                  firstDropDown.dataSource.data(data);
                }
              }).data("kendoDropDownList");
            });
          });

        </script>
      </body>
    </html>


问:
Pushing data in keys into a single array only values
Such data is coming from Laravel to Ajax. How do I push the values inside the keys into a single array without the keys.

```<code>$get_session = session()->get('cart.products');
return response($get_session);
</code>```

Data returned to Ajax.

```<code>data1: {
1234543: {id: 1, title: 'Product Title1', description: 'Product Descrition1'}
3453234: {id: 2, title: 'Product Title2', description: 'Product Descrition2'}
4564234: {id: 3, title: 'Product Title3', description: 'Product Descrition3'}
}

data2: {
4643345: {id: 4, title: 'Product Title4', description: 'Product Descrition4'}
8679673: {id: 5, title: 'Product Title5', description: 'Product Descrition5'}
2344565: {id: 6, title: 'Product Title6', description: 'Product Descrition6'}
}
</code>```

this is what i want to do

```<code>[
1234543: {id: 1, title: 'Product Title1', description: 'Product Descrition1'}
3453234: {id: 2, title: 'Product Title2', description: 'Product Descrition2'}
4564234: {id: 3, title: 'Product Title3', description: 'Product Descrition3'}
4643345: {id: 4, title: 'Product Title4', description: 'Product Descrition4'}
8679673: {id: 5, title: 'Product Title5', description: 'Product Descrition5'}
2344565: {id: 6, title: 'Product Title6', description: 'Product Descrition6'}
]
</code>```

How can I do it with Laravel or jquery? Thanks everyone.

答:
Say you get the ajax response as response, you can convert it to the expected object like so

```<code>var data = Object.assign(...Object.values(response));
</code>```

Example

var response = {
    data1: {
        1234543: {id: 1, title: 'Product Title1', description: 'Product Descrition1'},
        3453234: {id: 2, title: 'Product Title2', description: 'Product Descrition2'},
        4564234: {id: 3, title: 'Product Title3', description: 'Product Descrition3'}
    },
    data2: {
        4643345: {id: 4, title: 'Product Title4', description: 'Product Descrition4'},
        8679673: {id: 5, title: 'Product Title5', description: 'Product Descrition5'},
        2344565: {id: 6, title: 'Product Title6', description: 'Product Descrition6'}
    }
};
var data = Object.assign(...Object.values(response));
console.log(data)```

Body:
Such data is coming from Laravel to Ajax. How do I push the values inside the keys into a single array without the keys.

$get_session = session()->get('cart.products');
return response($get_session);

Data returned to Ajax.

data1: {
1234543: {id: 1, title: 'Product Title1', description: 'Product Descrition1'}
3453234: {id: 2, title: 'Product Title2', description: 'Product Descrition2'}
4564234: {id: 3, title: 'Product Title3', description: 'Product Descrition3'}
}

data2: {
4643345: {id: 4, title: 'Product Title4', description: 'Product Descrition4'}
8679673: {id: 5, title: 'Product Title5', description: 'Product Descrition5'}
2344565: {id: 6, title: 'Product Title6', description: 'Product Descrition6'}
}

this is what i want to do

[
1234543: {id: 1, title: 'Product Title1', description: 'Product Descrition1'}
3453234: {id: 2, title: 'Product Title2', description: 'Product Descrition2'}
4564234: {id: 3, title: 'Product Title3', description: 'Product Descrition3'}
4643345: {id: 4, title: 'Product Title4', description: 'Product Descrition4'}
8679673: {id: 5, title: 'Product Title5', description: 'Product Descrition5'}
2344565: {id: 6, title: 'Product Title6', description: 'Product Descrition6'}
]

How can I do it with Laravel or jquery? Thanks everyone.

Body:
Say you get the ajax response as response, you can convert it to the expected object like so

var data = Object.assign(...Object.values(response));

Example

var response = {
    data1: {
        1234543: {id: 1, title: 'Product Title1', description: 'Product Descrition1'},
        3453234: {id: 2, title: 'Product Title2', description: 'Product Descrition2'},
        4564234: {id: 3, title: 'Product Title3', description: 'Product Descrition3'}
    },
    data2: {
        4643345: {id: 4, title: 'Product Title4', description: 'Product Descrition4'},
        8679673: {id: 5, title: 'Product Title5', description: 'Product Descrition5'},
        2344565: {id: 6, title: 'Product Title6', description: 'Product Descrition6'}
    }
};
var data = Object.assign(...Object.values(response));
console.log(data)


问:
Why is reduce index 1-based sometimes?
I've just come across an annoying bug (in my code) that was caused by the JavaScript Array.reduce method.

I've created a minimal reproduction of the issue below.

const people = [{name: 'bob'}, {name: 'fred'}, {name: 'john'}]

people.reduce((acc, person, i) => {
  if (i === 0) throw Error('this error is never thrown')
  if (i === 1) console.log(acc === people[0])
  console.log(i, person.name)
  return acc
})

people.reduce((acc, person, i) => {
  if (i === 0) console.log(acc === null)
  console.log(i, person.name)
  return acc
}, null)```

Why does the first piece of code above iterate twice only whilst the second use of reduce iterates three times (once for each array item) as expected?

Are there any docs documenting this behaviour or is this a bug in Chrome? If its not a bug, why does this behaviour exist?

答:
reduce() has the second param (optional) as initial value of the aggregation. From the docs:

If initialValue is not specified, previousValue is initialized to the first value in the array, and currentValue is initialized to the second value in the array.

In your code bob is skipped and so is its index. So this is the correct behaviour

Title: Why is reduce index 1-based sometimes?

Body:
I've just come across an annoying bug (in my code) that was caused by the JavaScript Array.reduce method.

I've created a minimal reproduction of the issue below.

const people = [{name: 'bob'}, {name: 'fred'}, {name: 'john'}]

people.reduce((acc, person, i) => {
  if (i === 0) throw Error('this error is never thrown')
  if (i === 1) console.log(acc === people[0])
  console.log(i, person.name)
  return acc
})

people.reduce((acc, person, i) => {
  if (i === 0) console.log(acc === null)
  console.log(i, person.name)
  return acc
}, null)

Why does the first piece of code above iterate twice only whilst the second use of reduce iterates three times (once for each array item) as expected?

Are there any docs documenting this behaviour or is this a bug in Chrome? If its not a bug, why does this behaviour exist?


问:
Giving error when using Provider state management in Flutter
I am trying to increase counter when app call init and using provider to change the state of counter but getting this error i don't understand why i have made the listen to false but no solved kindly help

```<code>import 'dart:async';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:providerpractice/counter.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int count = 0;
  Timer? timer;

  @override
  void initState() {
    super.initState();

    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      var pro = Provider.of<Counter>(context, listen: false);
      pro.addCounter();
    });
  }

  @override
  Widget build(BuildContext context) {
    print("build" + count.toString());
    return Scaffold(
      appBar: AppBar(
        title: Text("Provider State Management"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Consumer<Counter>(builder: ((context, value, child) {
              return Text(
                value.counter.toString(),
                style: TextStyle(fontSize: 30),
              );
            }))
          ],
        ),
      ),
    );
  }
}
</code>```

答:
If I am not mistaken, you can't use "context" in the initState method, rather move it out of there put it in a didChangeDependancy method.

I am sure someone can elaborate more on this, but the widget has no context until after the initState.

Body:
I am trying to increase counter when app call init and using provider to change the state of counter but getting this error i don't understand why i have made the listen to false but no solved kindly help

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:providerpractice/counter.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int count = 0;
  Timer? timer;

  @override
  void initState() {
    super.initState();

    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      var pro = Provider.of<Counter>(context, listen: false);
      pro.addCounter();
    });
  }

  @override
  Widget build(BuildContext context) {
    print("build" + count.toString());
    return Scaffold(
      appBar: AppBar(
        title: Text("Provider State Management"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Consumer<Counter>(builder: ((context, value, child) {
              return Text(
                value.counter.toString(),
                style: TextStyle(fontSize: 30),
              );
            }))
          ],
        ),
      ),
    );
  }
}


问:
Instagram Graph API - media_product_type not showing STORY
I currently have the below API response for one of our instagram pages using the Graph  API that includes media_product_type, even though our Page has a STORY we are not seeing it come through, but we do see FEED and IGTV, see here for the documentation on this field. Has this happened to anyone else?</p>
```<code>/12334555/media?limit=100&period=lifetime&fields=name%2Ccaption%2Clink%2Cshortcode%2Ccomments_count%2Cmedia_type%2Cpermalink%2Clike_count%2Ctimestamp%2media_product_type&access_token='blah'
</code>```

答:
You will need to use the stories endpoint (not media)

eg:

```<code>{baseUrl}/{version}/{instagramUserId}/stories?fields=caption,media_url,timestamp,permalink,username,media_type,like_count,comments_count,shortcode,thumbnail_url,video_title,media_product_type&limit=10&access_token={accessToken}
</code>```

Note: story info is only around for 24 hours, so ideally you polls for infor and then setup the webhook to receive the final counts before the story dissapears.

Body:
I currently have the below API response for one of our instagram pages using the Graph  API that includes media_product_type, even though our Page has a STORY we are not seeing it come through, but we do see FEED and IGTV, see here for the documentation on this field. Has this happened to anyone else?

/12334555/media?limit=100&period=lifetime&fields=name%2Ccaption%2Clink%2Cshortcode%2Ccomments_count%2Cmedia_type%2Cpermalink%2Clike_count%2Ctimestamp%2media_product_type&access_token='blah'

Body:
You will need to use the stories endpoint (not media)

eg:

{baseUrl}/{version}/{instagramUserId}/stories?fields=caption,media_url,timestamp,permalink,username,media_type,like_count,comments_count,shortcode,thumbnail_url,video_title,media_product_type&limit=10&access_token={accessToken}

Note: story info is only around for 24 hours, so ideally you polls for infor and then setup the webhook to receive the final counts before the story dissapears.


问:
How to get the sub heading column in Power BI?

The above is the expected matrix in Power BI. I have to get the additional heading "MED" and "RX" for the columns "Paid" and "Unpaid" as shown in the matrix.

The above is the actual table schema, which is connected to get the data into the matrix.

How to get the column heading "MED" and "RX" in Matrix?

答:
You should put MED/RX and Paid/Unpaid attributes in separate columns, so make sure the data is transformed to look like this:

Then put Insurance to the rows of the matrix, Type and Paid as columns and Values as values, and enable the drill mode:


问:
Is there a way to restrict access to certain applications by specific users?
I have create several applications that communicate with our central auth server via doorkeeper. I want to make some applications accessible/inaccessible for specific users.

Is there a way to restrict access to specific oauth_applications and return a 401?

答:
On 9 Feb 2020 a new configuration option was introduced in Doorkeeper to exactly do this.

Therefore, you can configure config/initializer/doorkeeper.rb:

```<code>authorize_resource_owner_for_client do |client, resource_owner|
  resource_owner.admin? || client.owners_whitelist.include?(resource_owner)
end
</code>```

Body:
On 9 Feb 2020 a new configuration option was introduced in Doorkeeper to exactly do this.

Therefore, you can configure config/initializer/doorkeeper.rb:

authorize_resource_owner_for_client do |client, resource_owner|
  resource_owner.admin? || client.owners_whitelist.include?(resource_owner)
end


问:
Enable Flight mode with out disabling the wifi and bluetooth in android
I want to enable Flight mode but if i enable flight mode i cant able to use bluetooth , wifi. my purpose is to restrict only  the receiving call and sms related things.

I tried the following, but its not working;

```<code>Settings.System.putString(getContentResolver(),
           Settings.System.AIRPLANE_MODE_RADIOS, "cell,bluetooth");
</code>```

can any one help me in this

答:
Try this. I can't guarantee that it will work properly on all devices.

```<code>private ITelephony getTelephonyService() {
    try {
        TelephonyManager oTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        Method mGetITelephony = oTelephonyManager.getClass().getDeclaredMethod("getITelephony", new Class[] {});
        mGetITelephony.setAccessible(true);
        return (ITelephony) mGetITelephony.invoke(oTelephonyManager, new Object[] {});
    } catch (Exception e) {
        return null;
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try {
        boolean retval = getTelephonyService().setRadio(false);
        Log.v("Radio", "SetRadio : " + retval);
    } catch (Exception e) {
        Log.v("Radio", Log.getStackTraceString(e));
    }
}
</code>```

You will also need the ITelephony.aidl file. Create a package com.android.internal.telephony under your project's src folder and create a file ITelephony.aidl in it with the following content:

```<code>/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.internal.telephony;

import android.os.Bundle;
import java.util.List;

/**
 * Interface used to interact with the phone.  Mostly this is used by the
 * TelephonyManager class.  A few places are still using this directly.
 * Please clean them up if possible and use TelephonyManager insteadl.
 *
 * {@hide}
 */
interface ITelephony {
    /**
     * Check to see if the radio is on or not.
     * @return returns true if the radio is on.
     */
    boolean isRadioOn();

    /**
     * Toggles the radio on or off.
     */
    void toggleRadioOnOff();

    /**
     * Set the radio to on or off
     */
    boolean setRadio(boolean turnOn);
}
</code>```

Body:
I want to enable Flight mode but if i enable flight mode i cant able to use bluetooth , wifi. my purpose is to restrict only  the receiving call and sms related things.

I tried the following, but its not working;

Settings.System.putString(getContentResolver(),
           Settings.System.AIRPLANE_MODE_RADIOS, "cell,bluetooth");

can any one help me in this

Body:
Try this. I can't guarantee that it will work properly on all devices.

private ITelephony getTelephonyService() {
    try {
        TelephonyManager oTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        Method mGetITelephony = oTelephonyManager.getClass().getDeclaredMethod("getITelephony", new Class[] {});
        mGetITelephony.setAccessible(true);
        return (ITelephony) mGetITelephony.invoke(oTelephonyManager, new Object[] {});
    } catch (Exception e) {
        return null;
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try {
        boolean retval = getTelephonyService().setRadio(false);
        Log.v("Radio", "SetRadio : " + retval);
    } catch (Exception e) {
        Log.v("Radio", Log.getStackTraceString(e));
    }
}

You will also need the ITelephony.aidl file. Create a package com.android.internal.telephony under your project's src folder and create a file ITelephony.aidl in it with the following content:

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.internal.telephony;

import android.os.Bundle;
import java.util.List;

/**
 * Interface used to interact with the phone.  Mostly this is used by the
 * TelephonyManager class.  A few places are still using this directly.
 * Please clean them up if possible and use TelephonyManager insteadl.
 *
 * {@hide}
 */
interface ITelephony {
    /**
     * Check to see if the radio is on or not.
     * @return returns true if the radio is on.
     */
    boolean isRadioOn();

    /**
     * Toggles the radio on or off.
     */
    void toggleRadioOnOff();

    /**
     * Set the radio to on or off
     */
    boolean setRadio(boolean turnOn);
}


问:
SQLite: How Do I Reference Tables In Another SQLite Database?
I'm currently working with SQLite within DataGrip IDE. I am trying to reference another .sqlite database using the "attach database" method that every google search seems to bring up.

Attached are 2 screenshots, SCREENSHOT 1 shows the alias sandbox1 was created without a hitch, and the IDE seems to recognize sandbox1 as shown in the first screenshot.

Problem Point: Shown in screenshot 2, after the dot operator I was expecting tables (outlined in red) in Database1 ("sandbox_DB1.sqlite") to populate the box area but but the alias "sandbox1" doesn't seem to be attached to actual database1.

答: Did you tried to type manually? You done the right thing but seems that the the DB viewer doesn't work fine for creating the dropdown. For SQLite I am using https://sqlitebrowser.org/</p>


问:
Python subprocess returning exception
I have the following code that has been working until recently:

```<code>        si = STARTUPINFO()
        si.dwFlags |= STARTF_USESHOWWINDOW
        env = environ
        self.popen = Popen('python', [path + '\opt_module_v3.py'] + vlist, stdout=PIPE, stderr=STDOUT, stdin=PIPE, universal_newlines=True, bufsize=1, startupinfo=si, env=env)
        lines_iterator = iter(self.popen.stdout.readline, b"")
</code>```

it calls the opt_module_v3.py and returns messages as the child process runs.
When I run the main code, I'm getting the following exception:

```<code>   self.popen = Popen('python', [path + '\opt_module_v3.py'] + vlist, stdout=PIPE,
stderr=STDOUT, stdin=PIPE, universal_newlines=True, bufsize=1, startupinfo=si, env=env)
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py",
line 108, in __init__
super(SubprocessPopen, self).__init__(*args, **kwargs)
TypeError: __init__() got multiple values for argument 'bufsize'
</code>```

Like I mentioned, this code was working before but I might have stuffed up since I've been working on improvements.
Any clues on what could be happening here?

答:
The documentation says the API is:

```<code>subprocess.Popen(args, bufsize=- 1, MORE_ARGS...)
</code>```

This means your command has to be put in a list.

in your code [path + '\opt_module_v3.py'] + vlist is interpreted as bufsize

instead of

self.popen = Popen('python', [path + '\opt_module_v3.py'] + vlist, stdout=PIPE,  stderr=STDOUT, stdin=PIPE, universal_newlines=True, bufsize=1, startupinfo=si, env=env)

you should use something like

self.popen = Popen(['python', [path + '\opt_module_v3.py'] + vlist], stdout=PIPE,  stderr=STDOUT, stdin=PIPE, universal_newlines=True, bufsize=1, startupinfo=si, env=env)

I think however you may additionaly need to concatenate your path to a string to make this work

Title: Python subprocess returning exception

Body:
I have the following code that has been working until recently:

        si = STARTUPINFO()
        si.dwFlags |= STARTF_USESHOWWINDOW
        env = environ
        self.popen = Popen('python', [path + '\opt_module_v3.py'] + vlist, stdout=PIPE, stderr=STDOUT, stdin=PIPE, universal_newlines=True, bufsize=1, startupinfo=si, env=env)
        lines_iterator = iter(self.popen.stdout.readline, b"")

it calls the opt_module_v3.py and returns messages as the child process runs.
When I run the main code, I'm getting the following exception:

   self.popen = Popen('python', [path + '\opt_module_v3.py'] + vlist, stdout=PIPE,
stderr=STDOUT, stdin=PIPE, universal_newlines=True, bufsize=1, startupinfo=si, env=env)
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py",
line 108, in __init__
super(SubprocessPopen, self).__init__(*args, **kwargs)
TypeError: __init__() got multiple values for argument 'bufsize'

Like I mentioned, this code was working before but I might have stuffed up since I've been working on improvements.
Any clues on what could be happening here?

Body:
The documentation says the API is:

subprocess.Popen(args, bufsize=- 1, MORE_ARGS...)

This means your command has to be put in a list.

in your code [path + '\opt_module_v3.py'] + vlist is interpreted as bufsize

instead of

self.popen = Popen('python', [path + '\opt_module_v3.py'] + vlist, stdout=PIPE,  stderr=STDOUT, stdin=PIPE, universal_newlines=True, bufsize=1, startupinfo=si, env=env)

you should use something like

self.popen = Popen(['python', [path + '\opt_module_v3.py'] + vlist], stdout=PIPE,  stderr=STDOUT, stdin=PIPE, universal_newlines=True, bufsize=1, startupinfo=si, env=env)

I think however you may additionaly need to concatenate your path to a string to make this work


问:
Fast query runs slow in SSRS
I have an SSRS report that calls out to a stored procedure.  If I run the stored procedure directly from a query window, it will return in under 2 seconds.  However, the same query run from an 2005 SSRS report takes up to 5 minutes to complete.  This is not just happening on the first run, it happens every time.  Additionally, I don't see this same problem in other environments.

Any ideas on why the SSRS report would run so slow in this particular environment?

答: I had the same scenario occuring..Very basic report, the SP (which only takes in 1 param) was taking 5 seconds to bring back 10K records, yet the report would take 6 minutes to run.  According to profiler and the RS ExecutionLogStorage table, the report was spending all it's time on the query.  Brian S.'s comment led me to the solution..I simply added WITH RECOMPILE before the AS statement in the SP, and now the report time pretty much matches the SP execution time.</p>

ContentLicense: CC BY-SA 2.5

Title: Fast query runs slow in SSRS


问:
Sanity.io Fetching Through References
I'm trying to figure out how to access a full object reference through Sanity.io. Example code:

```<code>const fetchExperience = async () => {
  const data = await sanityClient.fetch(`*[_type == 'experience'] {
    company,
    title,
    'techStack': stack[]->technology,
    'imageUrl': image.asset->url,
  }`);

  return data;
};
</code>```

I have another schema declared called Skill that contains two fields: technology, and icon. This Experience schema that I am working with above and references the Skill schema. Using this post, I was able to figure out how to grab a singular field through the reference and populate a field called techStack. However, I want to take this one step further: how can I write a GROQ that returns me an array of objects that might look like this?:

```<code>[
  { technology: 'React.js', icon: 'pretend-this-is-a-link-to-an-asset' },
  ...
]
</code>```

Thanks in advance!

答:
You can do this to get the specific fields:</p>
```<code>"techStack": stack[]-> { technology, icon }
</code>```

Title: Sanity.io Fetching Through References

Body:
I'm trying to figure out how to access a full object reference through Sanity.io. Example code:

const fetchExperience = async () => {
  const data = await sanityClient.fetch(`*[_type == 'experience'] {
    company,
    title,
    'techStack': stack[]->technology,
    'imageUrl': image.asset->url,
  }`);

  return data;
};

I have another schema declared called Skill that contains two fields: technology, and icon. This Experience schema that I am working with above and references the Skill schema. Using this post, I was able to figure out how to grab a singular field through the reference and populate a field called techStack. However, I want to take this one step further: how can I write a GROQ that returns me an array of objects that might look like this?:

[
  { technology: 'React.js', icon: 'pretend-this-is-a-link-to-an-asset' },
  ...
]

Thanks in advance!

Body:
You can do this to get the specific fields:

"techStack": stack[]-> { technology, icon }


问:
Prometheus alerts - Absence of succeeded metrics having a date label and a timestamp value
I have a metrics of gauge type that, for each action (label step) and a give date (label day in the form 'yyyy-mm-dd'), stores the timestamp of the last succeeded event.
Something like:

```<code>{step_name="Upload table_1", day="2022-01-01"} = 1644354491
</code>```

I can, for instance, check how many hours ago data of day "2022-01-01" was uploaded in "table_1" with:

```<code>(time() - importer_succeeded_timestamp{day = "2022-01-01", step_name="Upload table_1"})/3600
</code>```

I need to be alerted if the day after data wasn't uploaded in a table, so if for a difference greater than X of the value of the gauge and the converted date-value of "day" label, the metric is not present. So somehow I need to compare the value of the gauge (timestamp) with the "day" (date in string format).
Every help is very welcome, my experience with Prometheus metrics and alerting manager is quite limited but I have the sensation that with the current metrics design is not possible.

答:
I continued to search and what I could figure out is that it's not possible.

In this conversation on Grafana blog https://community.grafana.com/t/how-to-use-a-prometheus-label-as-a-timestamp-for-grafana/54708 they speak about a:

known limitation with Prometheus. It just wasn’t designed to ingest
time-series data where the timestamp is a label.

Here another question similar to mine Prometheus label comparison with vector timestamp

This isn't possible, label values are opaque strings to Prometheus.

The only solution we've found: adding a new metrics with the same set of labels, having as value the seconds from the the "day label" to the moment of the execution. Like this it's possible to use both the metrics in AND, because how it's written here https://prometheus.io/docs/prometheus/latest/querying/operators/#logical-set-binary-operators:

vector1 and vector2 results in a vector consisting of the elements of
vector1 for which there are elements in vector2 with exactly matching
label sets. Other elements are dropped. The metric name and values are
carried over from the left-hand side vector.

Body:
I have a metrics of gauge type that, for each action (label step) and a give date (label day in the form 'yyyy-mm-dd'), stores the timestamp of the last succeeded event.
Something like:

{step_name="Upload table_1", day="2022-01-01"} = 1644354491

I can, for instance, check how many hours ago data of day "2022-01-01" was uploaded in "table_1" with:

(time() - importer_succeeded_timestamp{day = "2022-01-01", step_name="Upload table_1"})/3600

I need to be alerted if the day after data wasn't uploaded in a table, so if for a difference greater than X of the value of the gauge and the converted date-value of "day" label, the metric is not present. So somehow I need to compare the value of the gauge (timestamp) with the "day" (date in string format).
Every help is very welcome, my experience with Prometheus metrics and alerting manager is quite limited but I have the sensation that with the current metrics design is not possible.


问:
Rearanging data file in AWK providing subtotals and totals
I have the following data:

```<code>cat st_in.txt
2015-01-01  2   A   FI
2015-02-03  4   B   VI
2015-03-01  6   A   FI
2015-01-08  -4  C   VE
2016-01-05  -3  B   VE
2016-02-03  -1  D   FE
2016-04-01  -2  B   FE
2016-06-13  -5  D   VE
2017-01-01  2   A   VI
2017-02-03  3   A   VI
2017-02-04  8   C   FI
2017-01-05  -1  B   FE
</code>```

I want to output the data in this way (without comments of course):

```<code>        2015    2016    2017    # ...

A       0       0       5       # $2>0 && $4~/VI/       Ordered alphabetically asc
B       4       0       0       #       .                       .
sumVI   4       0       5

A       8       0       0       # $2>0 && $4~/FI/               .
C       0       0       8       #       .                       .
sumFI   8       0       8

sumI    12      0       13      # sumI=sumFI+sumVI

B       0       -3      0       # $2<0 && $4~/VE/               .
C       -4      0       0       #       .                       .
D       0       -5      0       #       .                       .
sumVE   -4      -8      0

B       0       -2      -1      # $2<0 && $4~/FE/               .
sumFE   0       -2      -1      #       .

sumE    -4      -10     -1      # sumE=sumFE+sumVE

NET     8       -10     12      # NET=sumI+sumE
</code>```

I am new to awk and not sure how to approach this. I have read on gnu.org awk manual about multi-dimensional arrays and arrays of arrays, which I assume I will be needing here but don't fully understand how they work. I am able to do this for one year but not multiple years. Please note that st_in.txt is very large and spans more years than in this sample. Also is there a good resource that you can recommend to learn how to pivot data tables in awk.

This is what I have attempted so far. This however does not work:

```<code>cat trans1
#!/usr/bin/env bash

awk '
    BEGIN{OFS="\t"
    cat[$3]
    height[$4][$3] +=$2
    width[substr($1,1,4)][$4][$3] +=$2
    }

    END{
    PROCINFO["sorted_in"]="@ind_str_asc";
    for (width in height){
        for (cat in height[width]){
            if($2>0 && $4~/VI/)
                {print cat, height[width]}
            else if($2>0 && $4~/FI/)
                {print cat, height[width]}
            else if($2<0 && $4~/VE/)
                {print cat, height[width]}
            else {print cat, height[width]}}}

    }
' "${@:--}"
</code>```

I get the following error:

```<code>awk: cmd. line:11: (FILENAME=st_in.txt FNR=12) fatal: attempt to use array `width' in a scalar context
</code>```

答:
At this line:

```<code>width[substr($1,1,4)][$4][$3] +=$2
</code>```

you declare width to be an array so you can't use that same name at this line:

```<code>for (width in height){
</code>```

as a scalar (the index to another array, height). Just change that second one to wid or some other name to get rid of the error message.  Obviously change width to wid where used as the index to height[] within the loop too.

Use this as a starting point, I picked variable names that better represent what they contain (though I've no idea what your 4th column represents so I just named it box - change to something meaningful) to try to help you understand what each means throughout your code as the first step to debugging and enhancing it:

```<code>$ cat trans1
#!/usr/bin/env bash

awk '
    BEGIN { OFS="\t" }
    {
        year   = substr($1,1,4)
        height = $2
        cat    = $3
        box    = $4

        cats[cat]
        boxCat_2_Heights[box][cat] += height
        yearBoxCat_2_Widths[year][box][cat] += height
    }

    END {
        PROCINFO["sorted_in"]="@ind_str_asc"
        for (box in boxCat_2_Heights) {
            for (cat in boxCat_2_Heights[box]) {
                height = boxCat_2_Heights[box][cat]

                if      (height>0 && box~/VI/) { type = "type1" }
                else if (height>0 && box~/FI/) { type = "type2" }
                else if (height<0 && box~/VE/) { type = "type3" }
                else                           { type = "type4" }

                print box, cat, height, type
            }
        }
    }
' "${@:--}"
</code>```

```<code>$ ./trans1 st_in.txt
FE      B       -3      type4
FE      D       -1      type4
FI      A       8       type2
FI      C       8       type2
VE      B       -3      type3
VE      C       -4      type3
VE      D       -5      type3
VI      A       5       type1
VI      B       4       type1
</code>```

I'm not saying the above is what you actually want, just that it does what your existing code is attempting to do but using meaningful names and valid syntax. It's a starting point for you.

Body:
I have the following data:

cat st_in.txt
2015-01-01  2   A   FI
2015-02-03  4   B   VI
2015-03-01  6   A   FI
2015-01-08  -4  C   VE
2016-01-05  -3  B   VE
2016-02-03  -1  D   FE
2016-04-01  -2  B   FE
2016-06-13  -5  D   VE
2017-01-01  2   A   VI
2017-02-03  3   A   VI
2017-02-04  8   C   FI
2017-01-05  -1  B   FE

I want to output the data in this way (without comments of course):

        2015    2016    2017    # ...

A       0       0       5       # $2>0 && $4~/VI/       Ordered alphabetically asc
B       4       0       0       #       .                       .
sumVI   4       0       5

A       8       0       0       # $2>0 && $4~/FI/               .
C       0       0       8       #       .                       .
sumFI   8       0       8

sumI    12      0       13      # sumI=sumFI+sumVI

B       0       -3      0       # $2<0 && $4~/VE/               .
C       -4      0       0       #       .                       .
D       0       -5      0       #       .                       .
sumVE   -4      -8      0

B       0       -2      -1      # $2<0 && $4~/FE/               .
sumFE   0       -2      -1      #       .

sumE    -4      -10     -1      # sumE=sumFE+sumVE

NET     8       -10     12      # NET=sumI+sumE

I am new to awk and not sure how to approach this. I have read on gnu.org awk manual about multi-dimensional arrays and arrays of arrays, which I assume I will be needing here but don't fully understand how they work. I am able to do this for one year but not multiple years. Please note that st_in.txt is very large and spans more years than in this sample. Also is there a good resource that you can recommend to learn how to pivot data tables in awk.

This is what I have attempted so far. This however does not work:

cat trans1
#!/usr/bin/env bash

awk '
    BEGIN{OFS="\t"
    cat[$3]
    height[$4][$3] +=$2
    width[substr($1,1,4)][$4][$3] +=$2
    }

    END{
    PROCINFO["sorted_in"]="@ind_str_asc";
    for (width in height){
        for (cat in height[width]){
            if($2>0 && $4~/VI/)
                {print cat, height[width]}
            else if($2>0 && $4~/FI/)
                {print cat, height[width]}
            else if($2<0 && $4~/VE/)
                {print cat, height[width]}
            else {print cat, height[width]}}}

    }
' "${@:--}"

I get the following error:

awk: cmd. line:11: (FILENAME=st_in.txt FNR=12) fatal: attempt to use array `width' in a scalar context

Body:
At this line:

width[substr($1,1,4)][$4][$3] +=$2

you declare width to be an array so you can't use that same name at this line:

for (width in height){

as a scalar (the index to another array, height). Just change that second one to wid or some other name to get rid of the error message.  Obviously change width to wid where used as the index to height[] within the loop too.

Use this as a starting point, I picked variable names that better represent what they contain (though I've no idea what your 4th column represents so I just named it box - change to something meaningful) to try to help you understand what each means throughout your code as the first step to debugging and enhancing it:

$ cat trans1
#!/usr/bin/env bash

awk '
    BEGIN { OFS="\t" }
    {
        year   = substr($1,1,4)
        height = $2
        cat    = $3
        box    = $4

        cats[cat]
        boxCat_2_Heights[box][cat] += height
        yearBoxCat_2_Widths[year][box][cat] += height
    }

    END {
        PROCINFO["sorted_in"]="@ind_str_asc"
        for (box in boxCat_2_Heights) {
            for (cat in boxCat_2_Heights[box]) {
                height = boxCat_2_Heights[box][cat]

                if      (height>0 && box~/VI/) { type = "type1" }
                else if (height>0 && box~/FI/) { type = "type2" }
                else if (height<0 && box~/VE/) { type = "type3" }
                else                           { type = "type4" }

                print box, cat, height, type
            }
        }
    }
' "${@:--}"

$ ./trans1 st_in.txt
FE      B       -3      type4
FE      D       -1      type4
FI      A       8       type2
FI      C       8       type2
VE      B       -3      type3
VE      C       -4      type3
VE      D       -5      type3
VI      A       5       type1
VI      B       4       type1

I'm not saying the above is what you actually want, just that it does what your existing code is attempting to do but using meaningful names and valid syntax. It's a starting point for you.


问:
Can't find how to use CONFIG:: directives properly
Let's say I have to compile two different versions of my .swf for different sites. The difference is in hostnames for the ajax and redirection, several minor tweaks in code and in graphics added to the project in .swc. I can switch different swcs easily, but the code tweaks are hard to manage easily. I've got

```<code>CONFIG::site1
{
    private var _domainName:String = "site1.com";
}

CONFIG::site2
{
    private var _domainName:String = "site2.com";
}
</code>```

FB brings up an error: 1151: A conflict exists with definition _domainName in namespace internal.

What I need is smthn like this in C:

```<code>#ifdef SITE1
char hostname[] = "site1";
#endif

#ifdef SITE2
char hostname[] = "site2";
#endif
</code>```

Is there any way to use compile directives that way using mxmlc?

P.S. Everything works now

答:
I think this documentation will help you.

In your case it is something like the following:

```<code>private var _domainName:String = NAMES::site;
</code>```

And mxmlc arguments will look like:

```<code>-define+=NAMES::site,"'site1.com'"
</code>```

Body:
Let's say I have to compile two different versions of my .swf for different sites. The difference is in hostnames for the ajax and redirection, several minor tweaks in code and in graphics added to the project in .swc. I can switch different swcs easily, but the code tweaks are hard to manage easily. I've got

CONFIG::site1
{
    private var _domainName:String = "site1.com";
}

CONFIG::site2
{
    private var _domainName:String = "site2.com";
}

FB brings up an error: 1151: A conflict exists with definition _domainName in namespace internal.

What I need is smthn like this in C:

#ifdef SITE1
char hostname[] = "site1";
#endif

#ifdef SITE2
char hostname[] = "site2";
#endif

Is there any way to use compile directives that way using mxmlc?

P.S. Everything works now

Body:
I think this documentation will help you.

In your case it is something like the following:

private var _domainName:String = NAMES::site;

And mxmlc arguments will look like:

-define+=NAMES::site,"'site1.com'"


问:
How to create a factory of context manager class
Working with python3

I have an existing class which connects to a remote directory server

```<code>class ldap:
  def __init__(self, name):
    self.name = name

  def __enter__(self):
    print("ldap connecting: %s" % self.name)

  def __exit__(self, exc_type, exc_value, traceback):
    print("ldap disconnecting: %s" % self.name)
</code>```

I am trying to create another class which will have multiple instances of this LDAP class.

Basically

```<code>class driver:
    def __init__(self):
        self.connections = {}
        self.count = count(1)
        self.connector = ldap_connector()

    def junk(self, name):
        self.connections[next(self.count)] = self.connector.get_me_connected(name)
</code>```

These are my failed attempts to come up with the ldap_connector class :)

```<code>class ldap_connector:
    def __init__(self):
        self.connections = []

#    def __enter__(self):
#        print("ldap_connector init")
#        with ldap(self.name) as p:
#            yield p    # Yield doesn't work well in __enter__

#    def __exit__(self, exc_type, exc_value, traceback):
#        print("ldap_connector de-init")

    def get_me_connected(self, name):
        try:
            while True:
                with ldap(name) as pc:
                    self.connections.append(pc)
                    yield pc
        finally:
            for conn in self.connections:
                print("Dumping conn")

#def get_me_connected():
#    def _connect(name):
#        print("Getting connected with {}".format(name))
#        with ldap_connector(name) as pc:
#            yield pc
#    return _connect
</code>```

At this point I am not sure how to achieve this

Any suggestions on what would be the best approach ?

答:
This is what I could come up with as a crude factory, more of a garage ;)

```<code>class ldap_connector:
    def __init__(self):
        self.connections = {}

    def get_me_connected(self, name):
        pc = ldap(name)
        self.connections[name] = pc.__enter__()
        return pc

    def destruct(self):
        for conn in self.connections:
            conn.__exit__(None, None, None)
</code>```

The issue with this is that the caller needs to call destruct() explicitly

I feel there would be a more pythonic way of making this a contextmanager class in itself and it keeps generating class ldap objects when get_me_connected() is called

Body:
Working with python3

I have an existing class which connects to a remote directory server

class ldap:
  def __init__(self, name):
    self.name = name

  def __enter__(self):
    print("ldap connecting: %s" % self.name)

  def __exit__(self, exc_type, exc_value, traceback):
    print("ldap disconnecting: %s" % self.name)

I am trying to create another class which will have multiple instances of this LDAP class.

Basically

class driver:
    def __init__(self):
        self.connections = {}
        self.count = count(1)
        self.connector = ldap_connector()

    def junk(self, name):
        self.connections[next(self.count)] = self.connector.get_me_connected(name)

These are my failed attempts to come up with the ldap_connector class :)

class ldap_connector:
    def __init__(self):
        self.connections = []

#    def __enter__(self):
#        print("ldap_connector init")
#        with ldap(self.name) as p:
#            yield p    # Yield doesn't work well in __enter__

#    def __exit__(self, exc_type, exc_value, traceback):
#        print("ldap_connector de-init")

    def get_me_connected(self, name):
        try:
            while True:
                with ldap(name) as pc:
                    self.connections.append(pc)
                    yield pc
        finally:
            for conn in self.connections:
                print("Dumping conn")

#def get_me_connected():
#    def _connect(name):
#        print("Getting connected with {}".format(name))
#        with ldap_connector(name) as pc:
#            yield pc
#    return _connect

At this point I am not sure how to achieve this

Any suggestions on what would be the best approach ?

Body:
This is what I could come up with as a crude factory, more of a garage ;)

class ldap_connector:
    def __init__(self):
        self.connections = {}

    def get_me_connected(self, name):
        pc = ldap(name)
        self.connections[name] = pc.__enter__()
        return pc

    def destruct(self):
        for conn in self.connections:
            conn.__exit__(None, None, None)

The issue with this is that the caller needs to call destruct() explicitly

I feel there would be a more pythonic way of making this a contextmanager class in itself and it keeps generating class ldap objects when get_me_connected() is called


问:
Select the filtered option from the dropdown using Cypress
I have a dropdown, kind of lookup, to test. I have to type a value and based on the value, the options will be filtered. And, I have to chose the option I want.

For example, some of the options filtered based on the value provided will be in the below format:

```<code>ENG 101 English-Read and Write
ENG 101 English-Speaking
ENG 101 English-Listening
MAT 201 Mathematics-Algebra
CSC 301 JAVA-Programming
CSC 301 CSharp-Programming
</code>```

I can only type the values in the first column - 'ENG' or 'MAT' or 'CSC' in the field to filter the options.

Now, if I provide value 'MAT' in the field then only one option will be filtered. No issue with selecting the option 'Mathematics-Algebra'.

If I provide value as 'ENG' to filter then multiple options are filtered. Now, I have to select the option 'English-Listening'. This is where I have the problem.

```<code>cy.get('app-screen').find('#paper-description').type('ENG'); // this is for providing input 'ENG'
cy.get('.overlay-pane').find('mat-option span:nth-child(3)').should('have.text', 'English-Listening'); // this is for selecting the required filtered option.
</code>```

When the above statement is executed, I am getting the below Assertion Error.

```<code>Timed out retrying after 4000ms: expected '[ <span.col-3>, 2 more... ]' to have text English-Listening, but the text was English-Read and WriteEnglish-SpeakingEnglish-Listenting
</code>```

The html structure would be in the below format:

```<code><div class='overlay-pane'>
    <mat-option>
        <span class='.col-1>ENG</span>
        <span class='.col-2>101</span>
        <span class='.col-3>English-Read and Write</span>
    </mat-option>
    <mat-option>
        <span class='.col-1>ENG</span>
        <span class='.col-2>101</span>
        <span class='.col-3>English-Speaking</span>
    </mat-option>
    <mat-option>
        <span class='.col-1>ENG</span>
        <span class='.col-2>101</span>
        <span class='.col-3>English-Listening</span>
    </mat-option>
</div>
</code>```

The option to be selected this time may be 'English-Listening'. Next time, it could be 'English-Speaking' or some other option. How to select the required option out of multiple filtered items from lookup?

答:
For material options, you should click the mat-option

cy.get('app-screen').find('#paper-description').type('ENG')
cy.contains('mat-option', 'English-Listening').click()
```

Body:
I have a dropdown, kind of lookup, to test. I have to type a value and based on the value, the options will be filtered. And, I have to chose the option I want.

For example, some of the options filtered based on the value provided will be in the below format:

ENG 101 English-Read and Write
ENG 101 English-Speaking
ENG 101 English-Listening
MAT 201 Mathematics-Algebra
CSC 301 JAVA-Programming
CSC 301 CSharp-Programming

I can only type the values in the first column - 'ENG' or 'MAT' or 'CSC' in the field to filter the options.

Now, if I provide value 'MAT' in the field then only one option will be filtered. No issue with selecting the option 'Mathematics-Algebra'.

If I provide value as 'ENG' to filter then multiple options are filtered. Now, I have to select the option 'English-Listening'. This is where I have the problem.

cy.get('app-screen').find('#paper-description').type('ENG'); // this is for providing input 'ENG'
cy.get('.overlay-pane').find('mat-option span:nth-child(3)').should('have.text', 'English-Listening'); // this is for selecting the required filtered option.

When the above statement is executed, I am getting the below Assertion Error.

Timed out retrying after 4000ms: expected '[ , 2 more... ]' to have text English-Listening, but the text was English-Read and WriteEnglish-SpeakingEnglish-Listenting

The html structure would be in the below format:

    <mat-option>
        ENG
        101
        English-Read and Write
    </mat-option>
    <mat-option>
        ENG
        101
        English-Speaking
    </mat-option>
    <mat-option>
        ENG
        101
        English-Listening
    </mat-option>

The option to be selected this time may be 'English-Listening'. Next time, it could be 'English-Speaking' or some other option. How to select the required option out of multiple filtered items from lookup?


问:
C# - using ColorDialog across forms
I have a windows form application.  On the main form a user will enter a number of item, etc and then click a button which will open a new form (either a small form or a large form depending on a checkbox).  Now on my main application I have a file menu - under which is settings - change background colour.  This opens the colordialog.  If a user does not pick anything the background colours will stay default.  However if they change it on the main entry form i change the background of a few textboxes - code below.

```<code>private void warning1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    colorDialog1.ShowDialog();
    Warn1Color = colorDialog1.Color.ToString();
    if (Warn1Color != null)
    {
        tbWarn1Hrs.BackColor = colorDialog1.Color;
        tbWarn1Mins.BackColor = colorDialog1.Color;
        tbWarn1Secs.BackColor = colorDialog1.Color;
        tbWarn1Msg.BackColor = colorDialog1.Color;
    }
}
</code>```

Now my problem is how to I get this to then change the background in the other form that opens.  I was hoping I could pass the string across in the new form constructor as i do with a number of other values.

i.e - here is my code in the new form....(note - string Warn1Color was passed across in constructor and then made = to the string _Warn1Color.  If it is null then background will be default yellow but it cant convert type string to system.drawing.color.  Does anyone see an easy solution to this or what I could do to get this working easily.

```<code>if (_Warn1Color == null)
{
    this.BackColor = System.Drawing.Color.Yellow;
}
else
    this.BackColor = _Warn1Color;
</code>```

答:
You should create a static class to store your configuration data such as this colour style. You can then set this value once you have prompted the user for the change and you can also call the Color value from any other form when you need to use it.

Your static class should look something like this...

```<code>public static class StyleSettings{
   private static Color _warn1Color = Color.FromArgb(255, 0, 0);//default colour
   public static Color Warn1Color {
      get { return _warn1Color; }
      set { _warn1Color = value; }
   }
}
</code>```

Then you can use this in your example method like...

```<code>private void warning1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (colorDialog1.ShowDialog() == DialogResult.OK)
    {
        StyleSettings.Warn1Color = colorDialog1.Color;

        tbWarn1Hrs.BackColor = StyleSettings.Warn1Color;
        tbWarn1Mins.BackColor = StyleSettings.Warn1Color;
        tbWarn1Secs.BackColor = StyleSettings.Warn1Color;
        tbWarn1Msg.BackColor = StyleSettings.Warn1Color;
    }
}
</code>```

Title: C# - using ColorDialog across forms

Body:
I have a windows form application.  On the main form a user will enter a number of item, etc and then click a button which will open a new form (either a small form or a large form depending on a checkbox).  Now on my main application I have a file menu - under which is settings - change background colour.  This opens the colordialog.  If a user does not pick anything the background colours will stay default.  However if they change it on the main entry form i change the background of a few textboxes - code below.

private void warning1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    colorDialog1.ShowDialog();
    Warn1Color = colorDialog1.Color.ToString();
    if (Warn1Color != null)
    {
        tbWarn1Hrs.BackColor = colorDialog1.Color;
        tbWarn1Mins.BackColor = colorDialog1.Color;
        tbWarn1Secs.BackColor = colorDialog1.Color;
        tbWarn1Msg.BackColor = colorDialog1.Color;
    }
}

Now my problem is how to I get this to then change the background in the other form that opens.  I was hoping I could pass the string across in the new form constructor as i do with a number of other values.

i.e - here is my code in the new form....(note - string Warn1Color was passed across in constructor and then made = to the string _Warn1Color.  If it is null then background will be default yellow but it cant convert type string to system.drawing.color.  Does anyone see an easy solution to this or what I could do to get this working easily.

if (_Warn1Color == null)
{
    this.BackColor = System.Drawing.Color.Yellow;
}
else
    this.BackColor = _Warn1Color;

Body:
You should create a static class to store your configuration data such as this colour style. You can then set this value once you have prompted the user for the change and you can also call the Color value from any other form when you need to use it.

Your static class should look something like this...

public static class StyleSettings{
   private static Color _warn1Color = Color.FromArgb(255, 0, 0);//default colour
   public static Color Warn1Color {
      get { return _warn1Color; }
      set { _warn1Color = value; }
   }
}

Then you can use this in your example method like...

private void warning1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (colorDialog1.ShowDialog() == DialogResult.OK)
    {
        StyleSettings.Warn1Color = colorDialog1.Color;

        tbWarn1Hrs.BackColor = StyleSettings.Warn1Color;
        tbWarn1Mins.BackColor = StyleSettings.Warn1Color;
        tbWarn1Secs.BackColor = StyleSettings.Warn1Color;
        tbWarn1Msg.BackColor = StyleSettings.Warn1Color;
    }
}


问:
Problem while populating orders and an array of products
I'm trying to create an e commerce web site using react, node and mongodb.
I created the order schema which comports the cmdRef(string), theClient(Id of the user) and an array of Products(with ProductId and qty) like the code below:

```<code>Orderchema=new mongoose.Schema({
    CmdRef:String,
    Client:{type: mongoose.Schema.Types.ObjectId,
    ref: 'User'},
    TotalProducts:[{ProductId:{type: mongoose.Schema.Types.ObjectId,
    ref: 'Product'},Quantity:Number}],
</code>```

and now I'm trying to create the route to get all the Orders

```<code>    CommandRouter.get('/AllCommands',async(req,res)=>{
  try {
    const cmd= await  Command.find({}).populate({path: 'Client', select: 'firstName lastName'}).populate({path:'TotalProducts'})
    //
    res.json(cmd)
} catch(error)
    {

        return res.status(500).send({message : "error get orders"})

    }
})
</code>```

Here I found a problem while populating the products Id in the table
it populates the client Id and returns all information about the User but fail with the product table   this is the full response using PostMan

Have any of you any Idea about how to populate the productId in the TotalProducts table?

答:
Total products is not an ObjectId. You should be populating ProductId instead.

This should work.

```<code>const cmd = await Command
    .find({})
    .populate([
      {
        path: 'Client',
        select: 'firstName lastName'
      },
      {
        path: 'TotalProducts'
        populate: 'ProductId'
      }
    ]);
</code>```

Body:
I'm trying to create an e commerce web site using react, node and mongodb.
I created the order schema which comports the cmdRef(string), theClient(Id of the user) and an array of Products(with ProductId and qty) like the code below:

Orderchema=new mongoose.Schema({
    CmdRef:String,
    Client:{type: mongoose.Schema.Types.ObjectId,
    ref: 'User'},
    TotalProducts:[{ProductId:{type: mongoose.Schema.Types.ObjectId,
    ref: 'Product'},Quantity:Number}],

and now I'm trying to create the route to get all the Orders

    CommandRouter.get('/AllCommands',async(req,res)=>{
  try {
    const cmd= await  Command.find({}).populate({path: 'Client', select: 'firstName lastName'}).populate({path:'TotalProducts'})
    //
    res.json(cmd)
} catch(error)
    {

        return res.status(500).send({message : "error get orders"})

    }
})

Here I found a problem while populating the products Id in the table
it populates the client Id and returns all information about the User but fail with the product table   this is the full response using PostMan

Have any of you any Idea about how to populate the productId in the TotalProducts table?

Body:
Total products is not an ObjectId. You should be populating ProductId instead.

This should work.

const cmd = await Command
    .find({})
    .populate([
      {
        path: 'Client',
        select: 'firstName lastName'
      },
      {
        path: 'TotalProducts'
        populate: 'ProductId'
      }
    ]);


问:
Is there a good obfuscater for Perl code?
Does anyone know of a good code obsfucator for Perl? I'm being ask to look into the option of obsfucating code before releasing it to a client. I know obsfucated code can still be reverse engineered, but that's not our main concern.

Some clients are making small changes to the source code that we give them and it's giving us nightmares when something goes wrong and we have to fix it, or when we release a patch that doesn't work with what they've changed. So the intention is just to make it so that it's difficult for them to make their own changes to the code(they're not supposed to be doing that anyway).

答:
Please don't do that. If you don't want people to alter your Perl code then put it under an appropriate licence and enforce that licence. If people change your code when you licence says that they shouldn't do that, then it's not your problem when your updates not longer work with their installation.

See perlfaq3's answer to "How Can I hide the source for my Perl programs? for more details.

LastEditorDisplayName: brian d foy

OwnerDisplayName: davorg


问:
Trying to multiply a certain data cell by another certain data cell in pandas
Due to misunderstanding using my real scenario I am going to create one.

Here is the DataFrame.

```<code>import pandas as pd
num1df = pd.DataFrame({'Number 1': [1, 4, 3, 2, 100]})
num2df = pd.DataFrame({'Number 2': [1, 2, 'NaN', 4, 5]})
num3df = pd.DataFrame({'Number 3': [1, 2, 3, 1000, 0]})
numsdf = pd.concat([num1df, num2df, num3df], axis=1, join="inner")
print(numsdf)
</code>```
```<code>   Number 1 Number 2  Number 3
0         1        1         1
1         4        2         2
2         3      NaN         3
3         2        4      1000
4       100        5         0
</code>```

I want to be able to do the follow addition. Column Number 1 row 4 plus column Number 3 row 3 = Column Number 2 row 2. 100 + 1000 = 1100 (the answer should be in place of the NaN)

This should be the expected outcome:

```<code>   Number 1 Number 2  Number 3
0         1        1         1
1         4        2         2
2         3     1100         3
3         2        4      1000
4       100        5         0
</code>```

How would I do that? I cannot figure it out.

答:
Notice: Solution working only if sme indices in all 3 DataFrames.

If possible replace non numeric values by missing values and then forward filling last non missng values in same column use:

```<code>marketcapdf['Market Cap'] = stockpricedf['Stock Price'] *
                            pd.to_numeric(outstandingdf['Outstanding'],
                                          errors='coerce').ffill()
</code>```

If working in one DataFrame:

```<code>df['Market Cap'] = df['Stock Price'] *
                   pd.to_numeric(df['Outstanding'],
                                 errors='coerce').ffill()
</code>```

EDIT: If need multiple by shifted second column with no change first value use:

```<code>numsdf['new'] = numsdf['Number 1'] * numsdf['Number 2'].shift(fill_value=1)
print(numsdf)
   Number 1  Number 2  new
0         5         1    5
1         4         2    4
2         3         3    6
3         2         4    6
4         1         5    4
</code>```

EDIT1: I create new columns for better understanding:

```<code>num1df = pd.DataFrame({'Number 1': [1, 4, 3, 2, 100]})
num2df = pd.DataFrame({'Number 2': [1, 2, np.nan, 4, 5]})
num3df = pd.DataFrame({'Number 3': [1, 2, 3, 1000, 0]})
numsdf = pd.concat([num1df, num2df, num3df], axis=1, join="inner")

#add by shifted values
numsdf['new'] = numsdf['Number 1'].shift(-1, fill_value=0) + numsdf['Number 3']
#shift again
numsdf['new1'] = numsdf['new'].shift(-1, fill_value=0)
#replace NaN by another column
numsdf['new2'] = numsdf['Number 2'].fillna(numsdf['new1'])
print(numsdf)
   Number 1  Number 2  Number 3   new  new1    new2
0         1       1.0         1     5     5     1.0
1         4       2.0         2     5     5     2.0
2         3       NaN         3     5  1100  1100.0
3         2       4.0      1000  1100     0     4.0
4       100       5.0         0     0     0     5.0
</code>```

Body:
Due to misunderstanding using my real scenario I am going to create one.

Here is the DataFrame.

import pandas as pd
num1df = pd.DataFrame({'Number 1': [1, 4, 3, 2, 100]})
num2df = pd.DataFrame({'Number 2': [1, 2, 'NaN', 4, 5]})
num3df = pd.DataFrame({'Number 3': [1, 2, 3, 1000, 0]})
numsdf = pd.concat([num1df, num2df, num3df], axis=1, join="inner")
print(numsdf)

   Number 1 Number 2  Number 3
0         1        1         1
1         4        2         2
2         3      NaN         3
3         2        4      1000
4       100        5         0

I want to be able to do the follow addition. Column Number 1 row 4 plus column Number 3 row 3 = Column Number 2 row 2. 100 + 1000 = 1100 (the answer should be in place of the NaN)

This should be the expected outcome:

   Number 1 Number 2  Number 3
0         1        1         1
1         4        2         2
2         3     1100         3
3         2        4      1000
4       100        5         0

How would I do that? I cannot figure it out.

Body:
Notice: Solution working only if sme indices in all 3 DataFrames.

If possible replace non numeric values by missing values and then forward filling last non missng values in same column use:

marketcapdf['Market Cap'] = stockpricedf['Stock Price'] *
                            pd.to_numeric(outstandingdf['Outstanding'],
                                          errors='coerce').ffill()

If working in one DataFrame:

df['Market Cap'] = df['Stock Price'] *
                   pd.to_numeric(df['Outstanding'],
                                 errors='coerce').ffill()

EDIT: If need multiple by shifted second column with no change first value use:

numsdf['new'] = numsdf['Number 1'] * numsdf['Number 2'].shift(fill_value=1)
print(numsdf)
   Number 1  Number 2  new
0         5         1    5
1         4         2    4
2         3         3    6
3         2         4    6
4         1         5    4

EDIT1: I create new columns for better understanding:

num1df = pd.DataFrame({'Number 1': [1, 4, 3, 2, 100]})
num2df = pd.DataFrame({'Number 2': [1, 2, np.nan, 4, 5]})
num3df = pd.DataFrame({'Number 3': [1, 2, 3, 1000, 0]})
numsdf = pd.concat([num1df, num2df, num3df], axis=1, join="inner")

#add by shifted values
numsdf['new'] = numsdf['Number 1'].shift(-1, fill_value=0) + numsdf['Number 3']
#shift again
numsdf['new1'] = numsdf['new'].shift(-1, fill_value=0)
#replace NaN by another column
numsdf['new2'] = numsdf['Number 2'].fillna(numsdf['new1'])
print(numsdf)
   Number 1  Number 2  Number 3   new  new1    new2
0         1       1.0         1     5     5     1.0
1         4       2.0         2     5     5     2.0
2         3       NaN         3     5  1100  1100.0
3         2       4.0      1000  1100     0     4.0
4       100       5.0         0     0     0     5.0


问:
Cypress get href attribute
I have a test case in which I have a link which opens in a new tab. Since Cypress doesn't support multiple tabs, I want to get the href attribute of that link and then open it in the same tab. I'm trying to do it this way, but for some reason it doesn't work.

```<code>it('Advertise link should refer to Contact page', () => {
    var link = document.querySelector("div.footer-nav > ul > li:nth-child(2) > a").href;
    cy.visit(link);
    cy.title().should('include', 'Text');
});
</code>```

答:
I used something similar in a test:</p>
```<code>cy.get('a').each(($el) => {
    const herf = $el.attr('href');
    cy.log(herf);

    // then I will do your test:
    cy.visit(link);
    cy.title().should('include', 'Text');

});
</code>```

Title: Cypress get href attribute

Body:
I have a test case in which I have a link which opens in a new tab. Since Cypress doesn't support multiple tabs, I want to get the href attribute of that link and then open it in the same tab. I'm trying to do it this way, but for some reason it doesn't work.

it('Advertise link should refer to Contact page', () => {
    var link = document.querySelector("div.footer-nav > ul > li:nth-child(2) > a").href;
    cy.visit(link);
    cy.title().should('include', 'Text');
});

Body:
I used something similar in a test:

cy.get('a').each(($el) => {
    const herf = $el.attr('href');
    cy.log(herf);

    // then I will do your test:
    cy.visit(link);
    cy.title().should('include', 'Text');

});


问:
git pull remote branch cannot find remote ref
I'm not sure why this doesn't work.  When I do git branch -a, this is what I see:

I'm trying to pull from the DownloadManager on the online GitHub repository.  I have tried

git pull, but then it complains about not knowing which branch to pull from

git pull origin, doesn't know which branch

git pull origin downloadmanager gives fatal: Couldn't find remote ref downloadmanager.  Unexpected end of commands stream

git pull origin remotes/origin/DownloadManager gives fatal couldn't find remote ref remotes/origin/DownloadManager.  Unexpected end of commands stream

Is there something I'm missing?  In Xcode, When I try to connect to the repository, nothing ever shows up.  I have been able to push to it in the past.  But I can't push again until I pull the most recent changes.

答:
In my case I had a branch in my local branches that was removed from the server

just remove it from the local branches and pull will works as expected


问:
Why does Visual Studio check out the .vspscc file when I add a file to a project?
If I add a new file to a project under TFS source control, it will check out the project file and the corresponding .vspscc file for that project file.

The project file itself changes (to include the new file), but the .vspscc file doesn't change at all. Why bother checking it out? Is there a way to disable it from being checked out and if there is, should I?

答:
According to this post of Ben Ryan:

Team Foundation uses these to store lists of files that have been excluded from source control.  We leveraged some of the existing SCC integration layer in Visual Studio to integrate Team Foundation, and these files were one of the carryovers.  I'll have to check into what the logic was in breaking out these SCC settings into separate files as opposed to putting them in the solution and project files' SCC sections.


问:
Can i use if condition in spring xml bean definition?
I have Spring Boot application where i use bean definition on xml.

I want to set bean property depends on my application's version. Can id do it?

Example how i see it:

```<code> <bean class="Pojo">
        <property name="field" value="sample-value"></property>
        <if expression="version=3.0">
        <property name="field2" value="sample-value2"></property>
        </if>
 </bean>
</code>```

答: If you can not switch to java configs, you can use a ref instead of value, implement a bean that checks the condition and returns the expected value.</p>

Body:
I have Spring Boot application where i use bean definition on xml.

I want to set bean property depends on my application's version. Can id do it?

Example how i see it:

 <bean class="Pojo">
        <property name="field" value="sample-value"></property>
        <if expression="version=3.0">
        <property name="field2" value="sample-value2"></property>
        </if>
 </bean>


问:
Using 'default' as a variable
Hello I have an object that has the value "default". But I can't do it because it gives error: Identifier expected.I receive this object from a service and I cannot modify the values.
https://developers.braintreepayments.com/reference/response/credit-card/node#default

private String default;
or
private Boolean default;

I want to do getter and setter.

Any way to solve?

答:
I ran into the same issue where I needed to use the 'default' and 'ref' as class members in order to create objects because the server would require this format. I got no solution to define members with these name, so I ended up creating a list that would create static strings as required (with default and ref in them) based on conditions (parameters passed while creating objects).

This is a work around to live with in case you cannot get the other side to stop using these names.

Title: Using 'default' as a variable


问:
Django: is it possible to make the statement displayed with red color when we use a form crispy?
Hi i want if a user forgot to fill out any field from the form , the phrase ""

This field is required. "" displayed with red color and not with black color , is it possible if yes! , How i can do that please or is there another way to do that!

enter image description here

答:
Find out what css class(es) are being attached to the error text and then supply CSS to cause it to display the way you want.  If there isn't an appropriate css class, you can add one with Crispy css_class arguments.

Browser right-click on an error text and "inspect object" should tell you the first part.

It seems to happen automagically for me, using Bootstrap and Crispy bootstrap Layout. However, the above answer is quite independent of Bootstrap.


问:
Embed 3D models on website
Is there a way to embed Sketchup models on a website? Preferably a free one, if it's a commercial solution I'd like a confirmation that it's actually worth the money... I know about the 3D warehouse thingy where you can rotate it (javascript and some images), but I can't upload anything to the 3D warehouse 'cause it always "resets the connection".</p>

答:
Yes, you can do it without cost. See here: https://help.sketchup.com/en/article/3000258

EDIT:

There were some free rendering sites apart from Google, but they don't seem to be in operation anymore. Posting to the Google 3D warehouse is going to be your best bet. Regarding your problem posting there, try it with Chrome.

EDIT #2:
If you don't want to upload to Google 3D Warehouse, you can achieve a similar effect with a little work. 3D Warehouse doesn't actually give the visitor the power to manipulate something in 3D, but rather it lets them "rotate" the image horizontally by simply showing a series of preset images of the 3D from various angles. You can take shots of your 3D object, import to Photoshop and create your own gif of the spinning object. A little more work than relying on Google, so you'll have to decide if it's worth it.

EDIT #3: If all else fails you can simply post the 3D model on your site as a downloadable file and advise visitors to get Sketchup to view it.

Title: Embed 3D models on website