问:
How can We create dynamic route navigation Link in angular with multi level children and which will recreate whole navigation on reload
I wanted to create a navigation list based on some configuration.
like an Array of

```<code>export interface LeftNavModel {
name: string,
route: string,
iconName?: string,
data?: any }
</code>```

so navigation data will look something like

```<code>[
  {
    name: "First Route",
    route:"first",
    sectionName: "First Section",
    iconName: "home",
    children: [
      {
        name: "First Child Route",
        route:`first/firstChild`,
        iconName: "folder"
        children: [
          {
            name: "First Sub Child Route",
            route:"first/firstChild/firstSubChild",
            iconName: "image"
          }
        ]
      }
    ]
  }
]
</code>```

This data will create nav link like

And in a component create routerLink using the routes from the config JSON.
I was able to create the same and is working fine. The issue is I wanted to share the navigated URL so other users can open the same page with navigation created dynamically.

Page Refresh can be handled by keeping config as state in router. Or using any storage mechanism like localStorage. But how can we share the link along with config data.
Passing config as queryParam will create huge url. Any other option for the same?

答:
I had to do this in a project I am working on a while back.

I am using bootstrap accordions for my sidebar, and as such needed to give each menu item an id. You could accomplish the same thing with anything though doesn't have to be bootstrap.

Create a class to represent the menu/nav items (Mine is something like this)

```<code>export class MenuItem {
  id: number;
  text: string;
  icon: string;
  url?: string;
  children?: MenuItem[];
}
</code>```

Create a menu items array which will store the list of items. This is a shortened version of what mine looks like:

```<code>export const menuItems = [
  {
    id: 1,
    text: 'Dashboard',
    icon: 'dashboard',
    url: 'dashboard',
  },
  {
    id: 2,
    text: 'Organizational Documents',
    icon: 'library_books',
    children: [
      {
        id: 3,
        text: 'View',
        icon: 'search',
        url: 'organizational-documents/view',
      },
    ],
  },
  {
    id: 4,
    text: 'Qualifications',
    icon: 'school',
    children: [
      {
        id: 5,
        text: 'Create',
        icon: 'create',
        url: 'qualifications/create',
      },
      {
        id: 6,
        text: 'View',
        icon: 'search',
        url: 'qualifications/view',
      },
    ],
  },
 {
    id: 7,
    text: 'Programmes',
    icon: 'library_books',
    children: [
      {
        id: 8,
        text: 'Create',
        icon: 'create',
        children: [
          {
            id: 9,
            text: 'Learnership',
            icon: 'add',
            url: 'programmes/create/learnership',
          },
          {
            id: 10,
            text: 'Internship',
            icon: 'add',
            url: 'programmes/create/internship',
          },
        ],
      },
{
        id: 11,
        text: 'View',
        icon: 'search',
        children: [
          {
            id: 12,
            text: 'Learnerships',
            icon: 'search',
            url: 'programmes/view/learnerships',
          },
          {
            id: 13,
            text: 'Internships',
            icon: 'search',
            url: 'programmes/view/internships',
          },
        ],
      },
]
</code>```

Initialize the menu items from the component that contains the nav items

```<code>import { menuItems } from '../menuItems';

public ngOnInit() {
    this.renderMenu();
}

private renderMenu(): void {
  this.renderedMenuItems = JSON.parse(JSON.stringify(menuItems));
}
</code>```

Add HTML similar to below in order to iterate over the menu items

```<code> <nav id="sidebar" class="sidebar-open overflow-auto shadow">
    <div class="accordion accordion-flush mb-2" id="sidebarAccordion">
      <div *ngFor="let item of renderedMenuItems">
        <div *ngIf="!item.children">
          <a
            id="flush-{{ item.id }}"
            class="
              fs-6
              d-flex
              align-items-center
              p-2
              pt-3
              pb-3
              cursor-pointer
              non-dropdown
            "
            routerLink="{{ item.url }}"
            routerLinkActive="active-route-dash"
          >
            <mat-icon class="ms-1 me-3">{{ item.icon }}</mat-icon>
            {{ item.text }}
          </a>
        </div>
        <div *ngIf="item.children" class="accordion-item">
          <h2 class="accordion-header m-0" id="flush-{{ item.id }}">
            <div
              id="menu-button-{{ item.id }}"
              class="accordion-button collapsed cursor-pointer p-2"
              data-bs-toggle="collapse"
              attr.data-bs-target="#flush-collapse-{{ item.id }}"
              aria-expanded="false"
              attr.aria-controls="flush-collapse-{{ item.id }}"
            >
              <mat-icon class="ms-1 me-3">{{ item.icon }}</mat-icon>
              {{ item.text }}
            </div>
          </h2>
          <div
            id="flush-collapse-{{ item.id }}"
            class="accordion-collapse collapse"
            attr.aria-labelledby="flush-{{ item.id }}"
            data-bs-parent="#sidebarAccordion"
          >
            <ul class="list-unstyled mb-0">
              <li *ngFor="let child of item.children">
                <div
                  *ngIf="child.children"
                  class="accordion accordion-flush"
                  id="accordion-{{ child.id }}"
                >
                  <div class="accordion-item">
                    <h2 class="accordion-header m-0" id="flush-{{ child.id }}">
                      <div
                        id="menu-button-{{ child.id }}"
                        class="accordion-button collapsed cursor-pointer p-2"
                        data-bs-toggle="collapse"
                        attr.data-bs-target="#flush-collapse-{{ child.id }}"
                        aria-expanded="false"
                        attr.aria-controls="flush-collapse-{{ child.id }}"
                      >
                        <div class="ps-2 fw-normal d-flex align-items-center">
                          <mat-icon class="ms-1 me-3">{{
                            child.icon
                          }}</mat-icon>
                          {{ child.text }}
                        </div>
                      </div>
                    </h2>
                    <div
                      id="flush-collapse-{{ child.id }}"
                      class="accordion-collapse collapse"
                      attr.aria-labelledby="flush-{{ child.id }}"
                      attr.data-bs-parent="#accordion-{{ child.id }}"
                    >
                      <ul class="list-unstyled mb-0">
                        <li *ngFor="let subChild of child.children">
                          <a
                            class="
                              cursor-pointer
                              nav-item
                              ps-4
                              d-flex
                              align-items-center
                              non-dropdown
                            "
                            routerLink="{{ subChild.url }}"
                            routerLinkActive="active-route-3rd"
                          >
                            <mat-icon class="ms-1 me-3">{{
                              subChild.icon
                            }}</mat-icon>
                            {{ subChild.text }}
                          </a>
                        </li>
                      </ul>
                    </div>
                  </div>
                </div>
                <div *ngIf="!child.children">
                  <a
                    class="
                      cursor-pointer
                      nav-item
                      ps-3
                      d-flex
                      align-items-center
                      non-dropdown
                    "
                    routerLink="{{ child.url }}"
                    routerLinkActive="active-route-2nd"
                  >
                    <mat-icon class="ms-1 me-3">{{ child.icon }}</mat-icon>
                    {{ child.text }}
                  </a>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </nav>
</code>```

With the above code, I end up with the following (after styling obviously)

Body:
I wanted to create a navigation list based on some configuration.
like an Array of

export interface LeftNavModel {
name: string,
route: string,
iconName?: string,
data?: any }

so navigation data will look something like

[
  {
    name: "First Route",
    route:"first",
    sectionName: "First Section",
    iconName: "home",
    children: [
      {
        name: "First Child Route",
        route:`first/firstChild`,
        iconName: "folder"
        children: [
          {
            name: "First Sub Child Route",
            route:"first/firstChild/firstSubChild",
            iconName: "image"
          }
        ]
      }
    ]
  }
]

This data will create nav link like

And in a component create routerLink using the routes from the config JSON.
I was able to create the same and is working fine. The issue is I wanted to share the navigated URL so other users can open the same page with navigation created dynamically.

Page Refresh can be handled by keeping config as state in router. Or using any storage mechanism like localStorage. But how can we share the link along with config data.
Passing config as queryParam will create huge url. Any other option for the same?

Body:
I had to do this in a project I am working on a while back.

I am using bootstrap accordions for my sidebar, and as such needed to give each menu item an id. You could accomplish the same thing with anything though doesn't have to be bootstrap.

Create a class to represent the menu/nav items (Mine is something like this)

export class MenuItem {
  id: number;
  text: string;
  icon: string;
  url?: string;
  children?: MenuItem[];
}

Create a menu items array which will store the list of items. This is a shortened version of what mine looks like:

export const menuItems = [
  {
    id: 1,
    text: 'Dashboard',
    icon: 'dashboard',
    url: 'dashboard',
  },
  {
    id: 2,
    text: 'Organizational Documents',
    icon: 'library_books',
    children: [
      {
        id: 3,
        text: 'View',
        icon: 'search',
        url: 'organizational-documents/view',
      },
    ],
  },
  {
    id: 4,
    text: 'Qualifications',
    icon: 'school',
    children: [
      {
        id: 5,
        text: 'Create',
        icon: 'create',
        url: 'qualifications/create',
      },
      {
        id: 6,
        text: 'View',
        icon: 'search',
        url: 'qualifications/view',
      },
    ],
  },
 {
    id: 7,
    text: 'Programmes',
    icon: 'library_books',
    children: [
      {
        id: 8,
        text: 'Create',
        icon: 'create',
        children: [
          {
            id: 9,
            text: 'Learnership',
            icon: 'add',
            url: 'programmes/create/learnership',
          },
          {
            id: 10,
            text: 'Internship',
            icon: 'add',
            url: 'programmes/create/internship',
          },
        ],
      },
{
        id: 11,
        text: 'View',
        icon: 'search',
        children: [
          {
            id: 12,
            text: 'Learnerships',
            icon: 'search',
            url: 'programmes/view/learnerships',
          },
          {
            id: 13,
            text: 'Internships',
            icon: 'search',
            url: 'programmes/view/internships',
          },
        ],
      },
]

Initialize the menu items from the component that contains the nav items

import { menuItems } from '../menuItems';

public ngOnInit() {
    this.renderMenu();
}

private renderMenu(): void {
  this.renderedMenuItems = JSON.parse(JSON.stringify(menuItems));
}

Add HTML similar to below in order to iterate over the menu items

 <nav id="sidebar" class="sidebar-open overflow-auto shadow">
    <div class="accordion accordion-flush mb-2" id="sidebarAccordion">
      <div *ngFor="let item of renderedMenuItems">
        <div *ngIf="!item.children">
          <a
            id="flush-{{ item.id }}"
            class="
              fs-6
              d-flex
              align-items-center
              p-2
              pt-3
              pb-3
              cursor-pointer
              non-dropdown
            "
            routerLink="{{ item.url }}"
            routerLinkActive="active-route-dash"
          >
            <mat-icon class="ms-1 me-3">{{ item.icon }}</mat-icon>
            {{ item.text }}
          </a>
        </div>
        <div *ngIf="item.children" class="accordion-item">
          <h2 class="accordion-header m-0" id="flush-{{ item.id }}">
            <div
              id="menu-button-{{ item.id }}"
              class="accordion-button collapsed cursor-pointer p-2"
              data-bs-toggle="collapse"
              attr.data-bs-target="#flush-collapse-{{ item.id }}"
              aria-expanded="false"
              attr.aria-controls="flush-collapse-{{ item.id }}"
            >
              <mat-icon class="ms-1 me-3">{{ item.icon }}</mat-icon>
              {{ item.text }}
            </div>
          </h2>
          <div
            id="flush-collapse-{{ item.id }}"
            class="accordion-collapse collapse"
            attr.aria-labelledby="flush-{{ item.id }}"
            data-bs-parent="#sidebarAccordion"
          >
            <ul class="list-unstyled mb-0">
              <li *ngFor="let child of item.children">
                <div
                  *ngIf="child.children"
                  class="accordion accordion-flush"
                  id="accordion-{{ child.id }}"
                >
                  <div class="accordion-item">
                    <h2 class="accordion-header m-0" id="flush-{{ child.id }}">
                      <div
                        id="menu-button-{{ child.id }}"
                        class="accordion-button collapsed cursor-pointer p-2"
                        data-bs-toggle="collapse"
                        attr.data-bs-target="#flush-collapse-{{ child.id }}"
                        aria-expanded="false"
                        attr.aria-controls="flush-collapse-{{ child.id }}"
                      >
                        <div class="ps-2 fw-normal d-flex align-items-center">
                          <mat-icon class="ms-1 me-3">{{
                            child.icon
                          }}</mat-icon>
                          {{ child.text }}
                        </div>
                      </div>
                    </h2>
                    <div
                      id="flush-collapse-{{ child.id }}"
                      class="accordion-collapse collapse"
                      attr.aria-labelledby="flush-{{ child.id }}"
                      attr.data-bs-parent="#accordion-{{ child.id }}"
                    >
                      <ul class="list-unstyled mb-0">
                        <li *ngFor="let subChild of child.children">
                          <a
                            class="
                              cursor-pointer
                              nav-item
                              ps-4
                              d-flex
                              align-items-center
                              non-dropdown
                            "
                            routerLink="{{ subChild.url }}"
                            routerLinkActive="active-route-3rd"
                          >
                            <mat-icon class="ms-1 me-3">{{
                              subChild.icon
                            }}</mat-icon>
                            {{ subChild.text }}
                          </a>
                        </li>
                      </ul>
                    </div>
                  </div>
                </div>
                <div *ngIf="!child.children">
                  <a
                    class="
                      cursor-pointer
                      nav-item
                      ps-3
                      d-flex
                      align-items-center
                      non-dropdown
                    "
                    routerLink="{{ child.url }}"
                    routerLinkActive="active-route-2nd"
                  >
                    <mat-icon class="ms-1 me-3">{{ child.icon }}</mat-icon>
                    {{ child.text }}
                  </a>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </nav>

With the above code, I end up with the following (after styling obviously)


来源: stackexchange

问:
Subselect in Update Statment with where
How can I make this PHP script in a one Single SQL statement?

```<code>$sql = 'SELECT oxtprice from oxarticles where oxparentid = ? and nrseriesarticle = 1';
        $price = DatabaseProvider::getDb()->getOne($sql, [$id]);

        if ($price) {
            $updateSql = "Update oxarticles SET nrseriestprice = ? WHERE oxid = ? and oxparentid = ''";
            DatabaseProvider::getDb()->execute($updateSql, [$price, $id]);
</code>```

I want something like this but it didn't work

```<code>UPDATE oxarticles SET
nrseriesprice = (SELECT oxprice from oxarticles where oxparentid = ? and nrseriesarticle = 1)
WHERE oxid = ?
</code>```

答:
You only need one query like below

```<code>CREATE TABLE parent (oxid int ,nrseriesprice DECIMAL (10,2))
</code>```

```<code>INSERT INTO parent VALUES (1,NULL)
</code>```

```<code>CREATE TABLE oxarticles (oxprice DECIMAL(19,2), oxparentid int,nrseriesarticle int)
</code>```

```<code>INSERT INTO oxarticles VALUES (19.2,1,1)
</code>```

```<code>UPDATE parent p SET
nrseriesprice = (SELECT oxprice from oxarticles where oxparentid = p.oxid and nrseriesarticle = 1)
WHERE p.oxid = 1
</code>```

```<code>SELECT * FROM parent
</code>```
```
oxid | nrseriesprice
---: | ------------:
   1 |         19.20
```

db<>fiddle here

ContentLicense: CC BY-SA 4.0

Title: Subselect in Update Statment with where

Body:
How can I make this PHP script in a one Single SQL statement?

$sql = 'SELECT oxtprice from oxarticles where oxparentid = ? and nrseriesarticle = 1';
        $price = DatabaseProvider::getDb()->getOne($sql, [$id]);

        if ($price) {
            $updateSql = "Update oxarticles SET nrseriestprice = ? WHERE oxid = ? and oxparentid = ''";
            DatabaseProvider::getDb()->execute($updateSql, [$price, $id]);

I want something like this but it didn't work

UPDATE oxarticles SET
nrseriesprice = (SELECT oxprice from oxarticles where oxparentid = ? and nrseriesarticle = 1)
WHERE oxid = ?

Body:
You only need one query like below

CREATE TABLE parent (oxid int ,nrseriesprice DECIMAL (10,2))

INSERT INTO parent VALUES (1,NULL)

CREATE TABLE oxarticles (oxprice DECIMAL(19,2), oxparentid int,nrseriesarticle int)

INSERT INTO oxarticles VALUES (19.2,1,1)

UPDATE parent p SET
nrseriesprice = (SELECT oxprice from oxarticles where oxparentid = p.oxid and nrseriesarticle = 1)
WHERE p.oxid = 1

SELECT * FROM parent

oxid | nrseriesprice
---: | ------------:
   1 |         19.20

db<>fiddle here


问:
Breakpoints in JRE System Library in Eclipse
I tried to make breakpoint in the class from JRE System Library, but when I started debug I recieved message: "Unable to install breakpoint at ... due to missing line number attributes. Modify compiler options to generate line number attributes."
So what should I do: recompile JRE System Library from sources with debug information and use it? Or there is some more simple way?</p>

答: You just have to enable some compiler options. Right click your project and select Properties. Go to Java Compiler and enable the checkboxes Add line number to generated class files (used by the debugger) and the other ones.

ContentLicense: CC BY-SA 3.0


问:
Im trying to call dio interceptor class but when im gettin 401 nothing happens
```<code>class RefreshToken extends Interceptor {

  Future<void> tryGetToken() async {

    print("asd");
    Dio dio = Dio();
    SharedPreferences pref = await SharedPreferences.getInstance();
    final token = pref.getString("access_token");
    final refreshtoken = pref.getString("refresh_token");
    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (request, handler) {
          if (token != null && token != '') {
            request.headers['Authorization'] = 'Bearer $token';
          }
          return handler.next(request);
        },
        onError: (e, handler) async {
          if (e.response?.statusCode == 401) {
            try {
              var headers = {
                //my header
              };
              var bodyFields = {
                //my body
              };
              await dio
                  .post(globals.apiUrl + "connect/token",
                      data: bodyFields,
                      options: Options(
                        headers: headers,
                        validateStatus: (status) {
                          return status! < 501;
                        },
                      ))
                  .then((value) async {
                if (value.statusCode! < 300) {
                  //get new tokens ...
                  print("access token" + token!);
                  print("refresh token" + refreshtoken!);
                  //set bearer
                  e.requestOptions.headers["Authorization"] = "Bearer " + token;
                  //create request with new access token
                  final opts = new Options(
                      method: e.requestOptions.method,
                      headers: e.requestOptions.headers);
                  final cloneReq = await dio.request(e.requestOptions.path,
                      options: opts,
                      data: e.requestOptions.data,
                      queryParameters: e.requestOptions.queryParameters);

                  return handler.resolve(cloneReq);
                }
              });
            } catch (e, st) {
              print(e);
            }
          }
        },
      ),
    );
  }
}
</code>```

this is my code. I dont know where's the problem. im gettin 401 from another requests but this interceptor not calls. I researched alot site but i never find any call method. Can anybody help me ? is my interceptor true ? if its true how can i use this ?

答: status code 404 is not a dio error, dio errors are related to connectivity status and connection timeout means, this type of interception will be initiated when your request fails, what you want to do, is to intercept the response ... when you get 404 , means you got the response from the server now you can handle it</p>

Body:
class RefreshToken extends Interceptor {

  Future<void> tryGetToken() async {

    print("asd");
    Dio dio = Dio();
    SharedPreferences pref = await SharedPreferences.getInstance();
    final token = pref.getString("access_token");
    final refreshtoken = pref.getString("refresh_token");
    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (request, handler) {
          if (token != null && token != '') {
            request.headers['Authorization'] = 'Bearer $token';
          }
          return handler.next(request);
        },
        onError: (e, handler) async {
          if (e.response?.statusCode == 401) {
            try {
              var headers = {
                //my header
              };
              var bodyFields = {
                //my body
              };
              await dio
                  .post(globals.apiUrl + "connect/token",
                      data: bodyFields,
                      options: Options(
                        headers: headers,
                        validateStatus: (status) {
                          return status! < 501;
                        },
                      ))
                  .then((value) async {
                if (value.statusCode! < 300) {
                  //get new tokens ...
                  print("access token" + token!);
                  print("refresh token" + refreshtoken!);
                  //set bearer
                  e.requestOptions.headers["Authorization"] = "Bearer " + token;
                  //create request with new access token
                  final opts = new Options(
                      method: e.requestOptions.method,
                      headers: e.requestOptions.headers);
                  final cloneReq = await dio.request(e.requestOptions.path,
                      options: opts,
                      data: e.requestOptions.data,
                      queryParameters: e.requestOptions.queryParameters);

                  return handler.resolve(cloneReq);
                }
              });
            } catch (e, st) {
              print(e);
            }
          }
        },
      ),
    );
  }
}

this is my code. I dont know where's the problem. im gettin 401 from another requests but this interceptor not calls. I researched alot site but i never find any call method. Can anybody help me ? is my interceptor true ? if its true how can i use this ?


问:
How do you use the Discord API to find server member count for OTHER servers?
How would i use python to find the server count for other servers? One's I'm not a part of? I can figure it out for my own, but not for others.</p>

答:
You will need to have the server's guild ID for this. You can then fetch the guild from the discord API using fetch_guild() and then access the guild's member_count attribute.

async def get_guild_members(guild_id: int):
    guild = bot.fetch_guild(guild_id)

    return guild.member_count
```


问:
Not able to import saved keras model from load_model in VSCode
I trained a keras model on Colab to predict skin diseases from images and when I try to call the model through VSCode, I get the following error.

```<code>  File "e:/github/Skin_Disease_Assessment/app.py", line 7, in <module>
    from keras.preprocessing import image

  File "C:\Users\Dilrose\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\__init__.py", line 25, in <module>
    from keras import models

  File "C:\Users\Dilrose\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\models.py", line 19, in <module>
    from keras import backend

  File "C:\Users\Dilrose\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\backend.py", line 301, in <module>
    tf.__internal__.register_clear_session_function(clear_session)
AttributeError: module 'tensorflow.compat.v2.__internal__' has no attribute 'register_clear_session_function'
</code>```

I'm able to predict the disease when I give images on Colab but since my project is a web application, I want the users to input the image through html and get the answer as well on the website.

My Python code

```<code>from flask import Flask, render_template, request, flash, redirect, session, url_for
from sqlite3 import *
from flask import request
from keras.models import load_model
from keras.preprocessing import image
import cv2
import requests

app = Flask(__name__)
app.secret_key = 'abc'

@app.route("/skinExam", methods=["GET", "POST"])
def skinExam():
    if request.method == 'POST':
        f = request.files['file']
        path='static/data/'+ f.filename
        f.save(path)
        model = load_model('models/final_mobilenet.h5')
        img1 = image.load_img(f, target_size=(224,224))
        img = cv2.resize(img1, (224,224)) / 255.0
        prediction = model.predict(img.reshape(1,224,224,3))
    return render_template('skinExam.html')
</code>```

My HTML code

```<code><div class="col-md-6" style='margin-left:250px;'>
        <form class="form-group" action="/skinExam" method='post' enctype="multipart/form-data">
            <label>Upload Image</label>
            <div class="input-group">
                <span class="input-group-btn">
                    <span class="btn btn-default btn-file">
                        Browse… <input type="file" id="imgInp" name="file">
                    </span>
                </span>
                <input type="text" class="form-control" readonly>
            </div>
            <input type='submit' id='upload' class='btn btn-lg btn-success' value='Upload'>
        </form>
    </div>
</code>```

Can someone help me in resolving this issue please?

答: Use tensorflow.keras instead of just keras, that usually solves this issue

Body:
I trained a keras model on Colab to predict skin diseases from images and when I try to call the model through VSCode, I get the following error.

  File "e:/github/Skin_Disease_Assessment/app.py", line 7, in <module>
    from keras.preprocessing import image

  File "C:\Users\Dilrose\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\__init__.py", line 25, in <module>
    from keras import models

  File "C:\Users\Dilrose\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\models.py", line 19, in <module>
    from keras import backend

  File "C:\Users\Dilrose\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\backend.py", line 301, in <module>
    tf.__internal__.register_clear_session_function(clear_session)
AttributeError: module 'tensorflow.compat.v2.__internal__' has no attribute 'register_clear_session_function'

I'm able to predict the disease when I give images on Colab but since my project is a web application, I want the users to input the image through html and get the answer as well on the website.

My Python code

from flask import Flask, render_template, request, flash, redirect, session, url_for
from sqlite3 import *
from flask import request
from keras.models import load_model
from keras.preprocessing import image
import cv2
import requests

app = Flask(__name__)
app.secret_key = 'abc'

@app.route("/skinExam", methods=["GET", "POST"])
def skinExam():
    if request.method == 'POST':
        f = request.files['file']
        path='static/data/'+ f.filename
        f.save(path)
        model = load_model('models/final_mobilenet.h5')
        img1 = image.load_img(f, target_size=(224,224))
        img = cv2.resize(img1, (224,224)) / 255.0
        prediction = model.predict(img.reshape(1,224,224,3))
    return render_template('skinExam.html')

My HTML code

        <form class="form-group" action="/skinExam" method='post' enctype="multipart/form-data">
            Upload Image

                        Browse… <input type="file" id="imgInp" name="file">

                <input type="text" class="form-control" readonly>

            <input type='submit' id='upload' class='btn btn-lg btn-success' value='Upload'>
        </form>

Can someone help me in resolving this issue please?


问:
Spring ScheduledTask - start/stop support?
Is there a way to start or stop a task scheduled using Spring Scheduled Tasks initialized using context file or @Scheduled annotation?

I would like to start the task when required and stop it when the task is no longer needed to be run.

If this is not possible, any alternative to injecting spring variables to a thread?

答:
Have the @Scheduled method look for a variable held in Application state or ServletContext, or from a value stored in the DB.  If the value is TRUE, proceed with the task; if FALSE, don't start.  This setup will control the scheduled run.

If you want to also be able to fire the task at will, reference the task's method from a Controller; that way you can fire it at will.  Additionally, if its a longer running task, create a second method annotated @Async and call that method from your Controller so that it runs in its own thread.


问:
How can i append RN/ line to upper line without RN/ in C#?
R/DOCS HK1/P/XX/123456789/XX/XXXXX/M/XXXXX/STAC

RN/K/OVER/FLOW

I need to merge above text like the below;

R/DOCS HK1/P/XX/123456789/XX/XXXXX/M/XXXXX/STACK/OVER/FLOW

The second line starts with RN/ which means everything after the slash should be appended to the previous line.

I searching with foreach. So i can't add as a string.

答:
If the content you want to add from the second string always starts after "RN/", you can do it like this:</p>
```<code>string string1 = "R/DOCS HK1/P/XX/123456789/XX/XXXXX/M/XXXXX/STAC";
string string2 = "RN/K/OVER/FLOW";

string result = string1 + string2.Substring(3);
</code>```

Body:
If the content you want to add from the second string always starts after "RN/", you can do it like this:

string string1 = "R/DOCS HK1/P/XX/123456789/XX/XXXXX/M/XXXXX/STAC";
string string2 = "RN/K/OVER/FLOW";

string result = string1 + string2.Substring(3);


问:
Rails mailer and links not working under Thunderbird
I want to send html email's with my Rails Mailer.
Could be multipart/alternative or only text/html.
Problem is, when I send an email with a link, it appears well on Gmail, but not so good in Thunderbird.

The problem is, that in Thunderbird, the link is 'not clickable' - it's highlighted like a link, but clicking on it does nothing.

Links on other mails (not sent from Rails Mailer) work flawlessly.

So my question is: how to properly send an html email, so it will be viewed properly?

Mailer code:

class MyMailer < ActionMailer::Base
  def mailing_delivery(email, subject)
    mail(:to => email, :subject => subject)
  end
```

<p><strong>Mail view:</strong></p>

```# mailing_delivery.html.haml
%p
  Thanks! Its your mailer!
%p
  = link_to "Google", "google.com"
```

<p><strong>Source of email</strong> <em>(some parts cut-out)<strong></em>:</strong></p>

```Date: Thu, 18 Aug 2011 14:32:34 +0200
From: xxx
To: xxx
Message-ID: <4e4d0662bf96e_41024be957a57974@xxx.mail>
Subject: Super news!
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit
X-O2-Trust: 2, 64
X-O2-SPF: neutral

  Thanks! It's your mailer!

  Google

```

<p>Of course Rails 3. Thunderbird 5.0, but that's not the issue - because somehow other mails show up good.. And I don't think it's app specific.</p>

<p>What should I do, to make this work?</p>

<p><strong>Edit:</strong> I tried to change the 'content-transfer-encoding' header with no success, by doing <code>mail(:to => email, :subject => subject, "Content-Transfer-Encoding" => value)</code> or in class <code>default "Content-Transfer-Encoding" => value</code> with no luck.. how to change that?</p>

<p>Emails that works good under Thunderbird have <code>Content-Transfer-Encoding: quoted-printable</code> (or eventually <code>base64</code>) so maybe that's the issue? How do I change it?</p>

<p><strong>Edit 2:</strong> I managed to change the <code>Content-Transfer-Encoding</code> to <code>quoted-printable</code> but it's cutting the content, like this:</p>

```Date: Thu, 18 Aug 2011 22:04:21 +0200
From: xxx
To: xxx
Message-ID: <4e4d704557839_151c4e4957c2132e@xxx.mail>
Subject: Super news!
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: quoted-printable
X-O2-Trust: 2, 63
X-O2-SPF: neutral

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://ww=
w.w3.org/TR/html4/loose.dtd">

      Thanks! It's your mailer!

      <a href=
```

One other thing: why is there a newline in Content-Type ? I didn't see it in other (working good) mails. How I can get rid of it?

答:
Maybe it'll work if you fix your html. So instead of just having:

```<code><p>
  Thanks! It's your mailer!
</p>
<p>
  <a href="google.com">Google</a>
</p>
</code>```

try:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <body>
    <p>
      Thanks! It's your mailer!
    </p>
    <p>
      <a href="http://google.com">Google</a>
    </p>
  </body>
</html>
</code>```

Body:
I want to send html email's with my Rails Mailer.
Could be multipart/alternative or only text/html.
Problem is, when I send an email with a link, it appears well on Gmail, but not so good in Thunderbird.

The problem is, that in Thunderbird, the link is 'not clickable' - it's highlighted like a link, but clicking on it does nothing.

Links on other mails (not sent from Rails Mailer) work flawlessly.

So my question is: how to properly send an html email, so it will be viewed properly?

Mailer code:

class MyMailer < ActionMailer::Base
  def mailing_delivery(email, subject)
    mail(:to => email, :subject => subject)
  end

Mail view:

# mailing_delivery.html.haml
%p
  Thanks! Its your mailer!
%p
  = link_to "Google", "google.com"

Source of email (some parts cut-out):

Date: Thu, 18 Aug 2011 14:32:34 +0200
From: xxx
To: xxx
Message-ID: <4e4d0662bf96e_41024be957a57974@xxx.mail>
Subject: Super news!
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit
X-O2-Trust: 2, 64
X-O2-SPF: neutral

  Thanks! It's your mailer!

  Google

Of course Rails 3. Thunderbird 5.0, but that's not the issue - because somehow other mails show up good.. And I don't think it's app specific.

What should I do, to make this work?

Edit: I tried to change the 'content-transfer-encoding' header with no success, by doing mail(:to => email, :subject => subject, "Content-Transfer-Encoding" => value) or in class default "Content-Transfer-Encoding" => value with no luck.. how to change that?

Emails that works good under Thunderbird have Content-Transfer-Encoding: quoted-printable (or eventually base64) so maybe that's the issue? How do I change it?

Edit 2: I managed to change the Content-Transfer-Encoding to quoted-printable but it's cutting the content, like this:

Date: Thu, 18 Aug 2011 22:04:21 +0200
From: xxx
To: xxx
Message-ID: <4e4d704557839_151c4e4957c2132e@xxx.mail>
Subject: Super news!
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: quoted-printable
X-O2-Trust: 2, 63
X-O2-SPF: neutral

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://ww=
w.w3.org/TR/html4/loose.dtd">

      Thanks! It's your mailer!

      <a href=

One other thing: why is there a newline in Content-Type ? I didn't see it in other (working good) mails. How I can get rid of it?

Body:
Maybe it'll work if you fix your html. So instead of just having:

<p>
  Thanks! It's your mailer!
</p>
<p>
  <a href="google.com">Google</a>
</p>

try:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <body>
    <p>
      Thanks! It's your mailer!
    </p>
    <p>
      <a href="http://google.com">Google</a>
    </p>
  </body>
</html>


问:
xamarin Android.Content.Res.Resources+NotFoundException: 'Unable to find resource ID #0xffffffff'
error:

```<code>xamarin Android.Content.Res.Resources+NotFoundException: 'Unable to find resource ID #0xffffffff'
</code>```

error is on line  auth = DependencyService.Get<IAuth>();

shared project

```<code> public partial class PhoneAuthPage : ContentPage
{
      IAuth auth;

        public PhoneAuthPage()
        {
            InitializeComponent();

            auth = DependencyService.Get<IAuth>();
       }
       ...
}
</code>```

android project

```<code>[assembly: Dependency(typeof(AuthDriod))]
namespace TestApp_Firebase.Droid.Views.PhoneViews
{
    public class AuthDriod : PhoneAuthProvider.OnVerificationStateChangedCallbacks, IAuth
    {
...
}
</code>```

AppShell.xaml

```<code><Shell ...
   xmlns:local="clr-namespace:TestApp_Firebase.Views"
   xmlns:PhoneViews="clr-namespace:TestApp_Firebase.vPhone"
   ...>

<FlyoutItem Title="Main Home Page" Icon="icon_about.png">
    <ShellContent Route="MainHomePage" ContentTemplate="{DataTemplate local:MainHomePage}" />
</FlyoutItem>
<FlyoutItem Title="Phone Auth Page" Icon="icon_about.png">
    <ShellContent Route="PhoneAuthPage" ContentTemplate="{DataTemplate PhoneViews:PhoneAuthPage}" />
</FlyoutItem>

</Shell>
</code>```

答:
I just got it working by downgrading my

Xamarin.GooglePlayServices.Base

To version 116.0.1.  Did not touch anything else

Body:
error:

xamarin Android.Content.Res.Resources+NotFoundException: 'Unable to find resource ID #0xffffffff'

error is on line  auth = DependencyService.Get<IAuth>();

shared project

 public partial class PhoneAuthPage : ContentPage
{
      IAuth auth;

        public PhoneAuthPage()
        {
            InitializeComponent();

            auth = DependencyService.Get<IAuth>();
       }
       ...
}

android project

[assembly: Dependency(typeof(AuthDriod))]
namespace TestApp_Firebase.Droid.Views.PhoneViews
{
    public class AuthDriod : PhoneAuthProvider.OnVerificationStateChangedCallbacks, IAuth
    {
...
}

AppShell.xaml

<Shell ...
   xmlns:local="clr-namespace:TestApp_Firebase.Views"
   xmlns:PhoneViews="clr-namespace:TestApp_Firebase.vPhone"
   ...>

<FlyoutItem Title="Main Home Page" Icon="icon_about.png">
    <ShellContent Route="MainHomePage" ContentTemplate="{DataTemplate local:MainHomePage}" />
</FlyoutItem>
<FlyoutItem Title="Phone Auth Page" Icon="icon_about.png">
    <ShellContent Route="PhoneAuthPage" ContentTemplate="{DataTemplate PhoneViews:PhoneAuthPage}" />
</FlyoutItem>

</Shell>


问:
get displayed data of a website and store the data in your firebase?
I know how to get displayed data of someone's website  and display it in my Flutter app. But don't know how to get the displayed data and store it in my firebase firestore. is it possible to get the displayed data from a website and store it in my firebase firestore???

答:
You can use FlutterFire.
FlutterFire is a set of Flutter plugins which connect your Flutter application to Firebase.

https://firebase.flutter.dev

See docs for firestore:

https://firebase.flutter.dev/docs/firestore/overview


问:
Virtual Range object in VBA
I have a macro that I am trying to use to crawl through a Workbook looking for instances of a specific User-Defined Function (UDF), and checking whether a criterion is met for the arguments to each UDF that it finds.

The fundamental issue is how to take a Range object (single cell) and resolve the arguments to a UDF to actual values i.e. not simply read the .Formula string, which may contain a mixture of actual values and cell references, but to recognise the arguments that are actually cell references and resolve those. If I were doing this manually, it would be a bit like selecting each argument to the UDF and hitting F9 to calculate, if that makes sense?

I am open to any robust ways to achieve the end goal, which as I said, is to be able to resolve the actual values of the arguments passed to a UDF, obviously not from within the UDF code itself.

To be specific, I am looping through all worksheets in the Workbook using:

```<code>For Each ws in ActiveWorkbook.Worksheets
</code>```

I am then using a search function (outside of the scope of this issue) to return a collection of cells that are using my UDF, which I will call

```<code>UDF(arg1, arg2)
</code>```

for the purposes of keeping it simple.

I then iterate through that collection of cells, and for each one, I would like to essentially concatenate the arguments into a ""-delimited string. So, if a particular cell contains the formula

```<code>=UDF(A1, "test")
</code>```

Let's say cell A1 contains "January", to be clear, I do not want "A1\test" to be returned, but "January\test".

答:
I think I have solved this (there may be other, more elegant ways).
I ended up writing a helper function to attempt to resolve a cell reference (same sheet, different sheet, Named Range) and used that (along with special-character trimming) to resolve all the arguments to my UDF. Essentially it's a parser.

The code is (for the argument resolver - assuming one has already parsed the UDF .Formula string to extract the arguments using Split on commas or whatever):

```<code>Private Function resolveCellRef(cellRef As String, cell As Range) As String
    ' This function takes an argument to a UDF that might be a cell reference or Named Range, and tries to resolve the value.
    ' It needs to handle the cases where a value has been passed, and just return the value again.
    ' Created by Rob Baker, 11/02/2022
    Dim pos1 As Integer, tmpStr As String
    Dim ws As Worksheet
    Dim error_raised As Boolean

    ' Check if it is already a string argument. If so, trim the quotation marks and return
    If Left(cellRef, 1) = """" Then
        resolveCellRef = Replace(cellRef, """", vbNullString)
        Exit Function
    End If
    ' Check for whether the argument is a cell reference to a foreign sheet
    error_raised = False
    pos1 = InStr(1, cellRef, "!")
    Select Case pos1
    Case 0
        Set ws = cell.Parent                            ' Cell reference must be local to sheet
        tmpStr = cellRef
    Case Else
        tmpStr = Left(cellRef, pos1 - 1)
        If Left(tmpStr, 1) = "'" Then                   ' Trim apostrophes if present
            tmpStr = Left(tmpStr, Len(tmpStr) - 1)
            tmpStr = Right(tmpStr, Len(tmpStr) - 1)
        End If
        Set ws = ActiveWorkbook.Worksheets(tmpStr)      ' Set the ws reference
        tmpStr = Right(cellRef, Len(cellRef) - pos1)    ' This is now the cell reference alone
    End Select
    On Error GoTo errhandler                            ' Use error handling to handle two known issues
    resolveCellRef = ws.Range(tmpStr).Value2
    If error_raised Then resolveCellRef = ActiveWorkbook.Names(cellRef).RefersToRange.Value2
    Exit Function

errhandler:
    If Err.Number = 1004 And Not error_raised Then      ' Set the error_raised flag and resume next to try a Named Range
        Err.Clear: error_raised = True
        Resume Next
    ElseIf Err.Number = 1004 And error_raised Then      ' If we get here, then the cellRef isn't a cell reference or Named Range, so just return it as is
        Err.Clear
        resolveCellRef = cellRef
        Resume Next
    End If
End Function
</code>```

Title: Virtual Range object in VBA

Body:
I have a macro that I am trying to use to crawl through a Workbook looking for instances of a specific User-Defined Function (UDF), and checking whether a criterion is met for the arguments to each UDF that it finds.

The fundamental issue is how to take a Range object (single cell) and resolve the arguments to a UDF to actual values i.e. not simply read the .Formula string, which may contain a mixture of actual values and cell references, but to recognise the arguments that are actually cell references and resolve those. If I were doing this manually, it would be a bit like selecting each argument to the UDF and hitting F9 to calculate, if that makes sense?

I am open to any robust ways to achieve the end goal, which as I said, is to be able to resolve the actual values of the arguments passed to a UDF, obviously not from within the UDF code itself.

To be specific, I am looping through all worksheets in the Workbook using:

For Each ws in ActiveWorkbook.Worksheets

I am then using a search function (outside of the scope of this issue) to return a collection of cells that are using my UDF, which I will call

UDF(arg1, arg2)

for the purposes of keeping it simple.

I then iterate through that collection of cells, and for each one, I would like to essentially concatenate the arguments into a ""-delimited string. So, if a particular cell contains the formula

=UDF(A1, "test")

Let's say cell A1 contains "January", to be clear, I do not want "A1\test" to be returned, but "January\test".

Body:
I think I have solved this (there may be other, more elegant ways).
I ended up writing a helper function to attempt to resolve a cell reference (same sheet, different sheet, Named Range) and used that (along with special-character trimming) to resolve all the arguments to my UDF. Essentially it's a parser.

The code is (for the argument resolver - assuming one has already parsed the UDF .Formula string to extract the arguments using Split on commas or whatever):

Private Function resolveCellRef(cellRef As String, cell As Range) As String
    ' This function takes an argument to a UDF that might be a cell reference or Named Range, and tries to resolve the value.
    ' It needs to handle the cases where a value has been passed, and just return the value again.
    ' Created by Rob Baker, 11/02/2022
    Dim pos1 As Integer, tmpStr As String
    Dim ws As Worksheet
    Dim error_raised As Boolean

    ' Check if it is already a string argument. If so, trim the quotation marks and return
    If Left(cellRef, 1) = """" Then
        resolveCellRef = Replace(cellRef, """", vbNullString)
        Exit Function
    End If
    ' Check for whether the argument is a cell reference to a foreign sheet
    error_raised = False
    pos1 = InStr(1, cellRef, "!")
    Select Case pos1
    Case 0
        Set ws = cell.Parent                            ' Cell reference must be local to sheet
        tmpStr = cellRef
    Case Else
        tmpStr = Left(cellRef, pos1 - 1)
        If Left(tmpStr, 1) = "'" Then                   ' Trim apostrophes if present
            tmpStr = Left(tmpStr, Len(tmpStr) - 1)
            tmpStr = Right(tmpStr, Len(tmpStr) - 1)
        End If
        Set ws = ActiveWorkbook.Worksheets(tmpStr)      ' Set the ws reference
        tmpStr = Right(cellRef, Len(cellRef) - pos1)    ' This is now the cell reference alone
    End Select
    On Error GoTo errhandler                            ' Use error handling to handle two known issues
    resolveCellRef = ws.Range(tmpStr).Value2
    If error_raised Then resolveCellRef = ActiveWorkbook.Names(cellRef).RefersToRange.Value2
    Exit Function

errhandler:
    If Err.Number = 1004 And Not error_raised Then      ' Set the error_raised flag and resume next to try a Named Range
        Err.Clear: error_raised = True
        Resume Next
    ElseIf Err.Number = 1004 And error_raised Then      ' If we get here, then the cellRef isn't a cell reference or Named Range, so just return it as is
        Err.Clear
        resolveCellRef = cellRef
        Resume Next
    End If
End Function


问:
Small web Q&A page - JSP or HTML? 1 page or several?
I've been tasked with a small web flow. I need to ask a series of questions, then stop them or send them to a specified URL. I envision each line below shown by itself:

- Q1. If Yes goto URL, No goto Q2

- Q2. If Yes goto URL, No goto Q3-7

- Q3-7 Any Yes goto Stop page, all No goto Input page

- Input customer name, Next

- Print Preview - show all 7 Q&A, customer name and current date, let user print, then Next to final URL

So my questions are, should I have each of these be a separate JSP pages with a Form carrying the answers as hidden? Or should I put them all on one HTML page, and hide/display the questions using JavaScript (it would only appear they are moving page to page)? Either way I'll use JavaScript to validate the questions.

This is an internal-use only thing, and no data is saved. It will be hosted on a Tomcat server with other Java apps running, so JSP's are not a problem - I'm just wondering if its overkill.

答:
I'd approach this issue from a maintenance standpoint. How often do you think there could be changes to the questions? If your boss calls you in and wants to see every Q in the app, printing one HTML page would be easy enough for him/her to do themselves.

If there was no saving of data, I would go one with the one page approach to keep it simple and easy to manage.


问:
How to view cypress mochawesome reports in jenkins after running test step inside docker container?
I'm running my cypress tests on Jenkins inside a dockerized container and I generate cypress mocha awesome report, but I don't know how to display it inside Jenkins.

This is my cypress.json content

```<code>{
  "integrationFolder": "test/specs",
  "supportFile": "test/support/index.js",
  "video": true,
  "reporter": "node_modules/cypress-multi-reporters",
  "reporterOptions": {
    "reporterEnabled": "mochawesome",
    "mochawesomeReporterOptions": {
      "reportDir": "results/mocha",
      "overwrite": false,
      "html": false,
      "json": true,
      "timestamp": "mmddyyyy_HHMMss",
      "showSkipped": true,
      "charts": true,
      "quite": true,
      "embeddedScreenshots": true
    }
  },
  "screenshotOnRunFailure": true,
  "screenshotsFolder": "results/mochareports/assets/screenshots",
  "videosFolder": "results/mochareports/assets/videos",
  "baseUrl": "http://testurl.com",
  "viewportWidth": 1920,
  "viewportHeight": 1080,
  "requestTimeout": 10000,
  "responseTimeout": 10000,
  "defaultCommandTimeout": 10000,
  "watchForFileChanges": true,
  "chromeWebSecurity": false
}
</code>```

And here is my scripts which I run locally.

```<code>  "clean:reports": "rm -R -f results && mkdir results && mkdir results/mochareports",
    "pretest": "npm run clean:reports",
    "cypress:interactive": "cypress open",
    "scripts:e2e": "cypress run",
    "combine-reports": "mochawesome-merge results/mocha/*.json > results/mochareports/report.json",
    "generate-report": "marge results/mochareports/report.json -f report -o results/mochareports -- inline",
    "posttest": "npm run combine-reports && npm run generate-report",
    "test:e2e": "npm run pretest && npm run scripts:e2e || npm run posttest",
</code>```

I can view my generated report successfully in the local environment.
Here is my jenkinsfile content

```<code>#!groovy

pipeline {
    agent any

    stages {
        stage('Checkout') {
            steps {
                echo 'Checking out the PR'
                checkout scm
            }
        }

        stage('Build') {
            steps {
                echo 'Destroy Old Build'
                sh 'make destroy'
                echo 'Building'
                sh 'make upbuild_d'
            }
        }

        stage('Test') {
            steps {
                echo 'Running Tests'
                sh 'make test-e2e'
            }
        }

        stage('Destroy') {
            steps {
                echo 'Destroy Build'
                sh 'make destroy'
            }
        }
    }
}
</code>```

The make test-e2e actually runs the test:e2e script inside a docker container, the tests actually run and I can see the reports get generated on Jenkins but I don't know how to view it.

I need to view it in a separate inside Jenkins, also I don't know why I can't access it via Jenkins workspace.
btw. I'm adding the results file in .gitignore

This is my local report preview

答:
You can use the HTML publisher plugin for Jenkins for this:

https://plugins.jenkins.io/htmlpublisher/

Within your Jenkinsfile add a stage to publish the HTML reports

e.g.

```<code>    publishHTML([
        allowMissing: false,
        alwaysLinkToLastBuild: false,
        keepAll: true,
        reportDir: 'cypress/cypress/reports/html',
        reportFiles: 'index.html',
        reportName: 'HTML Report',
        reportTitles: ''])
</code>```

Body:
I'm running my cypress tests on Jenkins inside a dockerized container and I generate cypress mocha awesome report, but I don't know how to display it inside Jenkins.

This is my cypress.json content

{
  "integrationFolder": "test/specs",
  "supportFile": "test/support/index.js",
  "video": true,
  "reporter": "node_modules/cypress-multi-reporters",
  "reporterOptions": {
    "reporterEnabled": "mochawesome",
    "mochawesomeReporterOptions": {
      "reportDir": "results/mocha",
      "overwrite": false,
      "html": false,
      "json": true,
      "timestamp": "mmddyyyy_HHMMss",
      "showSkipped": true,
      "charts": true,
      "quite": true,
      "embeddedScreenshots": true
    }
  },
  "screenshotOnRunFailure": true,
  "screenshotsFolder": "results/mochareports/assets/screenshots",
  "videosFolder": "results/mochareports/assets/videos",
  "baseUrl": "http://testurl.com",
  "viewportWidth": 1920,
  "viewportHeight": 1080,
  "requestTimeout": 10000,
  "responseTimeout": 10000,
  "defaultCommandTimeout": 10000,
  "watchForFileChanges": true,
  "chromeWebSecurity": false
}

And here is my scripts which I run locally.

  "clean:reports": "rm -R -f results && mkdir results && mkdir results/mochareports",
    "pretest": "npm run clean:reports",
    "cypress:interactive": "cypress open",
    "scripts:e2e": "cypress run",
    "combine-reports": "mochawesome-merge results/mocha/*.json > results/mochareports/report.json",
    "generate-report": "marge results/mochareports/report.json -f report -o results/mochareports -- inline",
    "posttest": "npm run combine-reports && npm run generate-report",
    "test:e2e": "npm run pretest && npm run scripts:e2e || npm run posttest",

I can view my generated report successfully in the local environment.
Here is my jenkinsfile content

#!groovy

pipeline {
    agent any

    stages {
        stage('Checkout') {
            steps {
                echo 'Checking out the PR'
                checkout scm
            }
        }

        stage('Build') {
            steps {
                echo 'Destroy Old Build'
                sh 'make destroy'
                echo 'Building'
                sh 'make upbuild_d'
            }
        }

        stage('Test') {
            steps {
                echo 'Running Tests'
                sh 'make test-e2e'
            }
        }

        stage('Destroy') {
            steps {
                echo 'Destroy Build'
                sh 'make destroy'
            }
        }
    }
}

The make test-e2e actually runs the test:e2e script inside a docker container, the tests actually run and I can see the reports get generated on Jenkins but I don't know how to view it.

I need to view it in a separate inside Jenkins, also I don't know why I can't access it via Jenkins workspace.
btw. I'm adding the results file in .gitignore

This is my local report preview

Body:
You can use the HTML publisher plugin for Jenkins for this:

https://plugins.jenkins.io/htmlpublisher/

Within your Jenkinsfile add a stage to publish the HTML reports

e.g.

    publishHTML([
        allowMissing: false,
        alwaysLinkToLastBuild: false,
        keepAll: true,
        reportDir: 'cypress/cypress/reports/html',
        reportFiles: 'index.html',
        reportName: 'HTML Report',
        reportTitles: ''])


问:
Vscode keras intellisense(suggestion) not working properly
Intellisense works fine on importing phrase

But when it comes with chaining method, it shows different suggestions

Python & Pylance extensions are installed.

答:
From this issue on github
try adding this to the bottom of your tensorflow/__init__.py (in .venv/Lib/site-packages/tensorflow for me)

```<code># Explicitly import lazy-loaded modules to support autocompletion.
# pylint: disable=g-import-not-at-top
if _typing.TYPE_CHECKING:
  from tensorflow_estimator.python.estimator.api._v2 import estimator as estimator
  from keras.api._v2 import keras
  from keras.api._v2.keras import losses
  from keras.api._v2.keras import metrics
  from keras.api._v2.keras import optimizers
  from keras.api._v2.keras import initializers
# pylint: enable=g-import-not-at-top
</code>```

The problem is because keras is a special class that enables lazy loading and not a normal module.

Edit: With updates to tf, vscode, or something else I'm not having this issue and don't need to use the above fix anymore. I just have to use keras = tf.keras instead of from tensorflow import keras and I have Intellisense working now.

Body:
From this issue on github
try adding this to the bottom of your tensorflow/__init__.py (in .venv/Lib/site-packages/tensorflow for me)

# Explicitly import lazy-loaded modules to support autocompletion.
# pylint: disable=g-import-not-at-top
if _typing.TYPE_CHECKING:
  from tensorflow_estimator.python.estimator.api._v2 import estimator as estimator
  from keras.api._v2 import keras
  from keras.api._v2.keras import losses
  from keras.api._v2.keras import metrics
  from keras.api._v2.keras import optimizers
  from keras.api._v2.keras import initializers
# pylint: enable=g-import-not-at-top

The problem is because keras is a special class that enables lazy loading and not a normal module.

Edit: With updates to tf, vscode, or something else I'm not having this issue and don't need to use the above fix anymore. I just have to use keras = tf.keras instead of from tensorflow import keras and I have Intellisense working now.


问:
Azure Cognitive Services: Problem with Text Analytics PII Endpoint in Python SDK
I'm trying to perform some more in-depth PII detection as the standard code that might be found here: https://learn.microsoft.com/en-us/azure/cognitive-services/language-service/personally-identifiable-information/quickstart?pivots=programming-language-python fails to find some more detailed entities (like French registration plates number, for example).

Everything works fine when I use the standard endpoint: 'https://whatever.cognitiveservices.azure.com/'

However, when I switch to 'https://whatever.cognitiveservices.azure.com/text/analytics/v3.1/entities/recognition/pii?piiCategories=default,FRDriversLicenseNumber" (an example found here: https://learn.microsoft.com/en-us/azure/cognitive-services/language-service/personally-identifiable-information/how-to-call ) I get an 404 error.

I believe it might be the Python SDK Issue, as when I try the API console - it works just fine. https://westus2.dev.cognitive.microsoft.com/docs/services/TextAnalytics-v3-1/operations/EntitiesRecognitionPii

The code:

```<code>key = "key"
endpoint = "https://whatever.cognitiveservices.azure.com/text/analytics/v3.1/entities/recognition/pii?piiCategories=default,FRDriversLicenseNumber/"

from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

# Authenticate the client using your key and endpoint
def authenticate_client():
    ta_credential = AzureKeyCredential(key)
    text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint,
            credential=ta_credential)
    return text_analytics_client

client = authenticate_client()

# Example method for detecting sensitive information (PII) from text
def pii_recognition_example(client):
    documents = [
        "The employee's SSN is 859-98-0987.",
        "The employee's phone number is 555-555-5555."
    ]
    response = client.recognize_pii_entities(documents, language="en")
    result = [doc for doc in response if not doc.is_error]
    for doc in result:
        print("Redacted Text: {}".format(doc.redacted_text))
        for entity in doc.entities:
            print("Entity: {}".format(entity.text))
            print("\tCategory: {}".format(entity.category))
            print("\tConfidence Score: {}".format(entity.confidence_score))
            print("\tOffset: {}".format(entity.offset))
            print("\tLength: {}".format(entity.length))
pii_recognition_example(client)
</code>```

答:
As it is not stated in the MS docs yet, the endpoint should be kept simple:

endpoint = "https://.cognitiveservices.azure.com"

and the details passed to the response = client.recognize_pii_entities().

The below code works just fine:

```<code> key = "key"
 endpoint = "https://<name>.cognitiveservices.azure.com"

 from azure.ai.textanalytics import TextAnalyticsClient
 from azure.core.credentials import AzureKeyCredential

 # Authenticate the client using your key and endpoint
 def authenticate_client():
     ta_credential = AzureKeyCredential(key)
     text_analytics_client = TextAnalyticsClient(
             endpoint=endpoint,
             credential=ta_credential)
     return text_analytics_client

 client = authenticate_client()

 # Example method for detecting sensitive information (PII) from text
 def pii_recognition_example(client):
     documents = [
         "The employee's SSN is 859-98-0987.",
         "The employee's phone number is 555-555-5555."
     ]
     response = client.recognize_pii_entities(documents, language="en", categories_filter=["default", "FRDriversLicenseNumber"])
     result = [doc for doc in response if not doc.is_error]
     for doc in result:
         print("Redacted Text: {}".format(doc.redacted_text))
         for entity in doc.entities:
             print("Entity: {}".format(entity.text))
             print("\tCategory: {}".format(entity.category))
             print("\tConfidence Score: {}".format(entity.confidence_score))
             print("\tOffset: {}".format(entity.offset))
             print("\tLength: {}".format(entity.length))
 pii_recognition_example(client)

</code>```

Body:
I'm trying to perform some more in-depth PII detection as the standard code that might be found here: https://learn.microsoft.com/en-us/azure/cognitive-services/language-service/personally-identifiable-information/quickstart?pivots=programming-language-python fails to find some more detailed entities (like French registration plates number, for example).

Everything works fine when I use the standard endpoint: 'https://whatever.cognitiveservices.azure.com/'

However, when I switch to 'https://whatever.cognitiveservices.azure.com/text/analytics/v3.1/entities/recognition/pii?piiCategories=default,FRDriversLicenseNumber" (an example found here: https://learn.microsoft.com/en-us/azure/cognitive-services/language-service/personally-identifiable-information/how-to-call ) I get an 404 error.

I believe it might be the Python SDK Issue, as when I try the API console - it works just fine. https://westus2.dev.cognitive.microsoft.com/docs/services/TextAnalytics-v3-1/operations/EntitiesRecognitionPii

The code:

key = "key"
endpoint = "https://whatever.cognitiveservices.azure.com/text/analytics/v3.1/entities/recognition/pii?piiCategories=default,FRDriversLicenseNumber/"

from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

# Authenticate the client using your key and endpoint
def authenticate_client():
    ta_credential = AzureKeyCredential(key)
    text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint,
            credential=ta_credential)
    return text_analytics_client

client = authenticate_client()

# Example method for detecting sensitive information (PII) from text
def pii_recognition_example(client):
    documents = [
        "The employee's SSN is 859-98-0987.",
        "The employee's phone number is 555-555-5555."
    ]
    response = client.recognize_pii_entities(documents, language="en")
    result = [doc for doc in response if not doc.is_error]
    for doc in result:
        print("Redacted Text: {}".format(doc.redacted_text))
        for entity in doc.entities:
            print("Entity: {}".format(entity.text))
            print("\tCategory: {}".format(entity.category))
            print("\tConfidence Score: {}".format(entity.confidence_score))
            print("\tOffset: {}".format(entity.offset))
            print("\tLength: {}".format(entity.length))
pii_recognition_example(client)

Body:
As it is not stated in the MS docs yet, the endpoint should be kept simple:

endpoint = "https://.cognitiveservices.azure.com"

and the details passed to the response = client.recognize_pii_entities().

The below code works just fine:

 key = "key"
 endpoint = "https://<name>.cognitiveservices.azure.com"

 from azure.ai.textanalytics import TextAnalyticsClient
 from azure.core.credentials import AzureKeyCredential

 # Authenticate the client using your key and endpoint
 def authenticate_client():
     ta_credential = AzureKeyCredential(key)
     text_analytics_client = TextAnalyticsClient(
             endpoint=endpoint,
             credential=ta_credential)
     return text_analytics_client

 client = authenticate_client()

 # Example method for detecting sensitive information (PII) from text
 def pii_recognition_example(client):
     documents = [
         "The employee's SSN is 859-98-0987.",
         "The employee's phone number is 555-555-5555."
     ]
     response = client.recognize_pii_entities(documents, language="en", categories_filter=["default", "FRDriversLicenseNumber"])
     result = [doc for doc in response if not doc.is_error]
     for doc in result:
         print("Redacted Text: {}".format(doc.redacted_text))
         for entity in doc.entities:
             print("Entity: {}".format(entity.text))
             print("\tCategory: {}".format(entity.category))
             print("\tConfidence Score: {}".format(entity.confidence_score))
             print("\tOffset: {}".format(entity.offset))
             print("\tLength: {}".format(entity.length))
 pii_recognition_example(client)


问:
Empty input stream that can be loaded in Properties
I have beans:

```<code>@Bean(name = "input_bean")
@ConditionalOnResource(resources = "classpath:input.xml")
public InputStream getInputStream() {
    return getClass().getClassLoader().getResourceAsStream(CachedProperty.INPUT_FILE_NAME);
}

@Bean
@ConditionalOnMissingBean(name = "input_bean")
public InputStream getInputStreamDefault() {
    //empty input stream
    return new InputStream() {
        @Override
        public int read() throws IOException {
            return 0;
        }
    };
}
</code>```

If the input.xml file exists, the file is loaded into input stream (as bean ), if not the empty input stream is created.

The problem is i am doing it cuz library demands it, and inside that library the input stream is being loaded into property file.

So when i create empty inputstream and properties try to laod it, it results in error.

How can i create placeholder for inputstream, such that it will not throw error when being loaded by properties?

答: Instead of creating an anoymous inner class just return InputStream.nullInputStream();

Body:
I have beans:

@Bean(name = "input_bean")
@ConditionalOnResource(resources = "classpath:input.xml")
public InputStream getInputStream() {
    return getClass().getClassLoader().getResourceAsStream(CachedProperty.INPUT_FILE_NAME);
}

@Bean
@ConditionalOnMissingBean(name = "input_bean")
public InputStream getInputStreamDefault() {
    //empty input stream
    return new InputStream() {
        @Override
        public int read() throws IOException {
            return 0;
        }
    };
}

If the input.xml file exists, the file is loaded into input stream (as bean ), if not the empty input stream is created.

The problem is i am doing it cuz library demands it, and inside that library the input stream is being loaded into property file.

So when i create empty inputstream and properties try to laod it, it results in error.

How can i create placeholder for inputstream, such that it will not throw error when being loaded by properties?


问:
Why should we use sp for font sizes in Android?

Possible Duplicate:

  Difference of px, dp, dip and sp in android

I am new to Android and I was trying out this tutorial

In that tutorial, they used the unit "sp" for textSize attribute and "dp" for other attributes.

Please tell me how sp differs from dp?

答:
Sp is scaled independently with respect to the normal font size of the device.
http://developer.android.com/guide/practices/screens_support.html

Similarly, you should prefer the sp (scale-independent pixel) to define text sizes. The sp scale factor depends on a user setting and the system scales the size the same as it does for dp.


问:
How to catch Delphi App shutting down when run in IDE?
Scenario

Using Delphi 2009 on Windows 10 I have an app that performs shut down operations such as logging and database manipulation.
Anywhere the user is able to exit the app I call Form.Close on the main form which calls a procedure to do the required operations. This works ok regardless of whether the user exits via the menu or by using the Windows task bar icon to close the window (as some of my users do).

Problem

When debugging the app in the IDE however, clicking the red square in the Delphi menu bar to stop the app running does not call Form.Close and hence doesn't call my shut down procedure.

Question

Is there a way to make the app correctly call form.close when shut down via the IDE so that I can ensure all parts get debugged?

Other info

I've looked here which describes a method using WMQueryEndSession to catch windows shut down messages but when I use that code in my app it is not called when the IDE shuts down the application, so maybe the IDE is using a different method.

Code used in my WMQueryEndSession procedure

```<code>procedure TFrmMain.WMQueryEndSession(var Msg: TWMQueryEndSession);
  {intercept the shut down message and call our proc first
   SafeFormClose is very simple and quick so no issues.
   Also called first in case the inherited procedure shuts us down
   before SafeFormClose has a chance to run}
begin
  SafeFormClose;    //Do our shut down and logging stuff
  Msg.Result := 1;  //Signal that it is OK for Windows to shut us down
  inherited;        //Do whatever the original handler would have done.
end;
</code>```

答:
If you are running the program in debugger, clicking the red square (reset button) terminates the program immediately. The debugger has full control of the program, and no more code is run after you click the reset button.

This is different than for example terminating the program in the task manager (in which case Windows would send a close signal to the program, which could reject it if it doesn't want to close yet).

You should design the program so that if it stops at any point, the next time it is started it fixes any problems caused by the reset (for example fixes corrupted database files). This is a real situation that can occur when power is lost or the operating system crashes. You cannot trust that your shutdown routine can be run every time.

Body:
Scenario

Using Delphi 2009 on Windows 10 I have an app that performs shut down operations such as logging and database manipulation.
Anywhere the user is able to exit the app I call Form.Close on the main form which calls a procedure to do the required operations. This works ok regardless of whether the user exits via the menu or by using the Windows task bar icon to close the window (as some of my users do).

Problem

When debugging the app in the IDE however, clicking the red square in the Delphi menu bar to stop the app running does not call Form.Close and hence doesn't call my shut down procedure.

Question

Is there a way to make the app correctly call form.close when shut down via the IDE so that I can ensure all parts get debugged?

Other info

I've looked here which describes a method using WMQueryEndSession to catch windows shut down messages but when I use that code in my app it is not called when the IDE shuts down the application, so maybe the IDE is using a different method.

Code used in my WMQueryEndSession procedure

procedure TFrmMain.WMQueryEndSession(var Msg: TWMQueryEndSession);
  {intercept the shut down message and call our proc first
   SafeFormClose is very simple and quick so no issues.
   Also called first in case the inherited procedure shuts us down
   before SafeFormClose has a chance to run}
begin
  SafeFormClose;    //Do our shut down and logging stuff
  Msg.Result := 1;  //Signal that it is OK for Windows to shut us down
  inherited;        //Do whatever the original handler would have done.
end;


问:
How to reduce the amount of Thunk code in the reudx-toolkit?
There is a huge amount of thanks on the project, because this is the api backend. The question is how do I better group these thanks? I thought for a long time, but apart from the try catch block, I didn't come up with any more ideas to throw everything thanks. Below are just them and this is only 1\4 part of them...</p>

答:
If you are using the thunks for normal data fetching, it might be interesting for you to look into RTK Query, which is also a part of Redux Toolkit and does all the thunks, reducers etc. for you - it just creates hooks for you that you can use in your application.

You can look at the corresponding chapter in the Redux documentation


问:
How do I index an item in a JSON array from Python
I was thinking to myself how one would find the position of a JSON object in a JSON array through python

for example

```<code>{
    "users": [
        {
            "person1": [
                {
                    "money": 769967967456795806758905768494685798974560,
                    "name": "person1"
                }
            ]
        },
        {
            "person2": [
                {
                    "money": 696969696969969696969696969,
                    "name": "person2"
                }
            ]
        }
    ]
}
</code>```

For instance let's say I wanted to get the position of person 2 from the array in python so position 2

(I looked through websites and previous questions but couldn't figure it out)

(hello people from my last post :) )

If you need any extra materials posted please request it here

答:
```<code>i = 0
for person in json["users"]:
    if "person2" in person:
        print(i)
        break
    i += 1
</code>```

You have to break the loop otherwise "i" is gonna be the value of the whole array.

Body:
I was thinking to myself how one would find the position of a JSON object in a JSON array through python

for example

{
    "users": [
        {
            "person1": [
                {
                    "money": 769967967456795806758905768494685798974560,
                    "name": "person1"
                }
            ]
        },
        {
            "person2": [
                {
                    "money": 696969696969969696969696969,
                    "name": "person2"
                }
            ]
        }
    ]
}

For instance let's say I wanted to get the position of person 2 from the array in python so position 2

(I looked through websites and previous questions but couldn't figure it out)

(hello people from my last post :) )

If you need any extra materials posted please request it here

Body:
i = 0
for person in json["users"]:
    if "person2" in person:
        print(i)
        break
    i += 1

You have to break the loop otherwise "i" is gonna be the value of the whole array.


问:
Dynamically adding SQL Logins to DSC for Azure Automation Credentials
I have a SQL Server on a VM being setup using a DSC file. I have been able to use SQL Login in the past (https://github.com/dsccommunity/SqlServerDsc/wiki/SqlLogin) but that only allows me to use it one at a time. I am trying to take all logins attached to my Azure Automation Credentials account and ensure the SQL Server has a login for each credential but I have not been able to figure out how to make it dynamic. I tried the following

```<code>$logins = Get-AzAutomationCredential -ResourceGroupName "resourceGroup" -AutomationAccountName "automationAccount"

    foreach($login in $logins.Where{$_.UserName -like "*dbuser*"})
    {
        Write-Output "Creating Login"
        Write-Output $login.Name
        SqlLogin 'Add_User'
        {
            Ensure = 'Present'
            Name = $login.Name
            LoginType = 'SqlLogin'
            InstanceName = 'Instance'
            LoginCredentials = Get-AutomationPSCredential -Name $login.Name
            LoginMustChangePassword = $false
            LoginPasswordExpirationEnabled = $false
            LoginPasswordPolicyEnforced = $true
        }
    }
</code>```

But, it seems like I cannot use Powershell when I am setting up the DSC so I am wondering if it is even possible to make this dynamic. Does anyone know how to do this dynamically?

答:
Every DSC-resource that is added to your configuration needs to have a unique name, so that might be where the problem is. Could you change your SqlLogin 'Add_User' to maybe have a username part of its name, so it's SqlLogin "Add_User_$($login.Username)" and see if that helps.
It should be able to work as you have set it up. Though it is not completely dynamic, as it will create a mof-file that will then contain the variables you push in with the extra powershell scripting you are using.</p>

Body:
I have a SQL Server on a VM being setup using a DSC file. I have been able to use SQL Login in the past (https://github.com/dsccommunity/SqlServerDsc/wiki/SqlLogin) but that only allows me to use it one at a time. I am trying to take all logins attached to my Azure Automation Credentials account and ensure the SQL Server has a login for each credential but I have not been able to figure out how to make it dynamic. I tried the following

$logins = Get-AzAutomationCredential -ResourceGroupName "resourceGroup" -AutomationAccountName "automationAccount"

    foreach($login in $logins.Where{$_.UserName -like "*dbuser*"})
    {
        Write-Output "Creating Login"
        Write-Output $login.Name
        SqlLogin 'Add_User'
        {
            Ensure = 'Present'
            Name = $login.Name
            LoginType = 'SqlLogin'
            InstanceName = 'Instance'
            LoginCredentials = Get-AutomationPSCredential -Name $login.Name
            LoginMustChangePassword = $false
            LoginPasswordExpirationEnabled = $false
            LoginPasswordPolicyEnforced = $true
        }
    }

But, it seems like I cannot use Powershell when I am setting up the DSC so I am wondering if it is even possible to make this dynamic. Does anyone know how to do this dynamically?


问:
Elasticsearch: case insensitive in output of terms aggregation
I store the a field of value like 'AA', but when using terms aggregation in search, it returns the value in lowercase like 'aa'.

when search with aggs like this:

```<code>POST /113/_search
{
  "query": {
    "query_string": {
      "query": "Jack"
    }
  },
    "aggs" : {
      "gender" : {
        "terms" : {
        "field" : "gender"
        }
      },
      "grade" : {
        "terms" : {
            "field" : "grade",
            "order" : {"_count" : "asc"}
        }

      }
    }
}
</code>```

outputs like this:

```<code>{
  "hits": {
    "total": 4,
    "max_score": 1.3862944,
    "hits": [
      {
        "_index": "113",
        "_type": "default_type",
        "_id": "1",
        "_score": 0.07419574,
        "_source": {
          "name": "Tome Jack",
          "grade": "AA",
          "gender": 1
        }
      }
    ]
  },
  "aggregations": {
    "grade": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "b",
          "doc_count": 1
        },
        {
          "key": "c",
          "doc_count": 1
        },
        {
          "key": "aa",
          "doc_count": 2
        }
      ]
    }
  }
}
</code>```

Why the key become lowercase like 'aa' instead of 'AA'? How to get the key as its original value.

property setting like this:

```<code>       "grade": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword"
          }
        },
        "analyzer": "ik_max_word",
        "fielddata": true
      },
</code>```

答: This is caused because you are using lowercase filter in your ik_max_word analyzer, Elastic search would use index data for aggregation purposes the best approach would be to remove lowercase filter or have another mapping for the field that are not Analyzed for aggregation purposes, for more information check  ES aggregation documentation here.

Body:
I store the a field of value like 'AA', but when using terms aggregation in search, it returns the value in lowercase like 'aa'.

when search with aggs like this:

POST /113/_search
{
  "query": {
    "query_string": {
      "query": "Jack"
    }
  },
    "aggs" : {
      "gender" : {
        "terms" : {
        "field" : "gender"
        }
      },
      "grade" : {
        "terms" : {
            "field" : "grade",
            "order" : {"_count" : "asc"}
        }

      }
    }
}

outputs like this:

{
  "hits": {
    "total": 4,
    "max_score": 1.3862944,
    "hits": [
      {
        "_index": "113",
        "_type": "default_type",
        "_id": "1",
        "_score": 0.07419574,
        "_source": {
          "name": "Tome Jack",
          "grade": "AA",
          "gender": 1
        }
      }
    ]
  },
  "aggregations": {
    "grade": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "b",
          "doc_count": 1
        },
        {
          "key": "c",
          "doc_count": 1
        },
        {
          "key": "aa",
          "doc_count": 2
        }
      ]
    }
  }
}

Why the key become lowercase like 'aa' instead of 'AA'? How to get the key as its original value.

property setting like this:

       "grade": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword"
          }
        },
        "analyzer": "ik_max_word",
        "fielddata": true
      },


问:
How do I remove parentheses and single quotation marks from my output?
How do I remove parentheses and single quotation marks from my output? There is no requirement in my code to show brackets and single quotation marks.

person = "    xx   "
what_he_said = "    abc！"
print(f"{person.split()}曾经说过，“{what_he_said.split()}”")
```
<p>This is the actual output:</p>
```['xx']曾经说过，“['abc！']”
```

I don't want to output the middle brackets and quotation marks.
I'm using Python 3.10, the IDE is pycharm.

答:
The split() function will separate the data with the [sep] parameter, it's empty by default, I assume you're using split to remove "[space-k]", but note that it will always return a separate argument list

```<code>"hola como estas ".split(sep=" ")
</code>```

will return:

```<code>[hola, como, estas]
</code>```

If you really need to use the split() function, you can get its values with the index.

E.g

```<code>person = "    xx   "
what_he_said = "    abc！"
print(f"{person.split()[0]}曾经说过，“{what_he_said.split()[0]}”")
</code>```

will return:

```<code>xx曾经说过，“abc！”
</code>```

Body:
How do I remove parentheses and single quotation marks from my output? There is no requirement in my code to show brackets and single quotation marks.

person = "    xx   "
what_he_said = "    abc！"
print(f"{person.split()}曾经说过，“{what_he_said.split()}”")

This is the actual output:

['xx']曾经说过，“['abc！']”

I don't want to output the middle brackets and quotation marks.
I'm using Python 3.10, the IDE is pycharm.

Body:
The split() function will separate the data with the [sep] parameter, it's empty by default, I assume you're using split to remove "[space-k]", but note that it will always return a separate argument list

"hola como estas ".split(sep=" ")

will return:

[hola, como, estas]

If you really need to use the split() function, you can get its values with the index.

E.g

person = "    xx   "
what_he_said = "    abc！"
print(f"{person.split()[0]}曾经说过，“{what_he_said.split()[0]}”")

will return:

xx曾经说过，“abc！”


问:
WKWebView does not allow camera access in application
We are trying to make a conference call with multiple users, So by using Kurento server we have achieved this and it's working on safari browser. But when it comes to implementation in WebView / WKWebView. It does not even ask for permissions.

```<code>@IBOutlet weak var webViewContainer: UIView!
var webView: WKWebView!

override open func loadView() {
    super.loadView()

    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.ignoresViewportScaleLimits = true
    webConfiguration.suppressesIncrementalRendering = true
    webConfiguration.allowsInlineMediaPlayback = true
    webConfiguration.allowsAirPlayForMediaPlayback = false
    webConfiguration.allowsPictureInPictureMediaPlayback = true
    webConfiguration.mediaTypesRequiringUserActionForPlayback = .all
    webConfiguration.requiresUserActionForMediaPlayback = true
    webView = WKWebView(frame: webViewContainer.frame, configuration: webConfiguration)
    webView.uiDelegate = self
    webView.navigationDelegate = self
    webView.sizeToFit()
    webView.backgroundColor = .black
    webView.isOpaque = false
    self.webViewContainer.addSubview(webView)

}

func webContentController()-> WKUserContentController {
    let contentController = WKUserContentController()
    let script = try! String(contentsOf: Bundle.main.url(forResource: "WebRTC", withExtension: "js")!, encoding: String.Encoding.utf8)
    contentController.addUserScript(WKUserScript(source: script, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true))
    contentController.add(self, name: "callbackHandler")
    return contentController
}

override func viewDidLoad() {
    super.viewDidLoad()
    guard let url = URL (string: urlStr) else { return
    }
    let myRequest = URLRequest(url: url)
    self.webView.load(myRequest)
}
</code>```

I even have tried this link in safariViewController, but it does not ask for camera permissions.

答:
I had to do this:

```<code>import AVFoundation

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        AVCaptureDevice.requestAccess(for: .audio) { haveMicAccess in
            print("Access to Microphone: \(haveMicAccess)")
        }

        return true
    }

    ...

}
</code>```

It still asks me each time I use the camera with getUserMedia() in the page script too. But without the above code getUserMedia is null. The above code triggers the request for access to the microphone so long as you provide a message in the info.plist for NSMicrophoneUsageDescription

Body:
We are trying to make a conference call with multiple users, So by using Kurento server we have achieved this and it's working on safari browser. But when it comes to implementation in WebView / WKWebView. It does not even ask for permissions.

@IBOutlet weak var webViewContainer: UIView!
var webView: WKWebView!

override open func loadView() {
    super.loadView()

    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.ignoresViewportScaleLimits = true
    webConfiguration.suppressesIncrementalRendering = true
    webConfiguration.allowsInlineMediaPlayback = true
    webConfiguration.allowsAirPlayForMediaPlayback = false
    webConfiguration.allowsPictureInPictureMediaPlayback = true
    webConfiguration.mediaTypesRequiringUserActionForPlayback = .all
    webConfiguration.requiresUserActionForMediaPlayback = true
    webView = WKWebView(frame: webViewContainer.frame, configuration: webConfiguration)
    webView.uiDelegate = self
    webView.navigationDelegate = self
    webView.sizeToFit()
    webView.backgroundColor = .black
    webView.isOpaque = false
    self.webViewContainer.addSubview(webView)

}

func webContentController()-> WKUserContentController {
    let contentController = WKUserContentController()
    let script = try! String(contentsOf: Bundle.main.url(forResource: "WebRTC", withExtension: "js")!, encoding: String.Encoding.utf8)
    contentController.addUserScript(WKUserScript(source: script, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true))
    contentController.add(self, name: "callbackHandler")
    return contentController
}

override func viewDidLoad() {
    super.viewDidLoad()
    guard let url = URL (string: urlStr) else { return
    }
    let myRequest = URLRequest(url: url)
    self.webView.load(myRequest)
}

I even have tried this link in safariViewController, but it does not ask for camera permissions.

Body:
I had to do this:

import AVFoundation

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        AVCaptureDevice.requestAccess(for: .audio) { haveMicAccess in
            print("Access to Microphone: \(haveMicAccess)")
        }

        return true
    }

    ...

}

It still asks me each time I use the camera with getUserMedia() in the page script too. But without the above code getUserMedia is null. The above code triggers the request for access to the microphone so long as you provide a message in the info.plist for NSMicrophoneUsageDescription


问:
PHP - access 2 different databases from one class
Please help me set the required database! Thank you!</p>

```<code><?php
require_once("adodb5/adodb.inc.php");

$web = NewAdoConnection("mysqlt");
$server     = "*";
$user       = "*";
$password   = "*";
$database   = "web";
$web->Connect($server, $user, $password, $database);

$modul = NewAdoConnection("mysqlt");
$server     = "*";
$user       = "*";
$password   = "*";
$database   = "modul";
$modul->Connect($server, $user, $password, $database);

$rs = $web->execute("SELECT DATABASE()");
echo $rs->fields[0];    // EXPECTED: "web", ACTUAL: "modul"
?>
</code>```

答:
Not sure, but I think you're looking for the __construct function.

EDIT:

Scratch that, I understand your question better now. It looks like you need to use ADOdb_Active_Record. Specifically, look at part 17. This page may also be helpful.

Body:
Please help me set the required database! Thank you!

<?php
require_once("adodb5/adodb.inc.php");

$web = NewAdoConnection("mysqlt");
$server     = "*";
$user       = "*";
$password   = "*";
$database   = "web";
$web->Connect($server, $user, $password, $database);

$modul = NewAdoConnection("mysqlt");
$server     = "*";
$user       = "*";
$password   = "*";
$database   = "modul";
$modul->Connect($server, $user, $password, $database);

$rs = $web->execute("SELECT DATABASE()");
echo $rs->fields[0];    // EXPECTED: "web", ACTUAL: "modul"
?>


问:
python del operator not working inside for loop
Here i want to remove duplicate objects from transaction_list. I have 7 objects in transaction_list 2 of them are duplicate. But when i run the following script it remove only one duplicate object in transaction_list. i think the issue is del operator but i don't know how to solve this.

```<code>'''
    create list of trnasactions objects using ids
    Remove the duplicates from transaction_list

    current output:
        7
        6

    correct output:
        7
        5
'''

class Transactions:
    tid = None
    def __init__(self, tid):
        self.tid = tid

# creating transaction_list
transaction_list = []
ids = [1,2,3,1,5,5,6]
for x in ids:
    transaction_list.append(Transactions(x))

# initial length of transaction_list
print(len(transaction_list))

tmp = []

for idx,obj in enumerate(transaction_list):
    if obj.tid not in tmp:
        tmp.append(obj.tid)
    else:
        del transaction_list[idx]

# final length of transaction_list
print(len(transaction_list))

</code>```

答:
In a for loop you need to pass a copy of a list because currently you try to delete element by id and you modify the original list so next time the list has changed.

To solve it you can add : like so for idx,obj in enumerate(transaction_list[:]): and it will work like so:

class Transactions:
    def __init__(self, tid):
        self.tid = tid

# creating transaction_list
transaction_list = []
ids = [1,2,3,1,5,5,6]
for x in ids:
    transaction_list.append(Transactions(x))

# initial length of transaction_list
print(len(transaction_list))

tmp = []

for idx,obj in enumerate(transaction_list[:]):
    if obj.tid not in tmp:
        tmp.append(obj.tid)
    else:
        del transaction_list[idx]

# final length of transaction_list
print(len(transaction_list))
```
<p>The output is:</p>
```7
5
```

Body:
Here i want to remove duplicate objects from transaction_list. I have 7 objects in transaction_list 2 of them are duplicate. But when i run the following script it remove only one duplicate object in transaction_list. i think the issue is del operator but i don't know how to solve this.

'''
    create list of trnasactions objects using ids
    Remove the duplicates from transaction_list

    current output:
        7
        6

    correct output:
        7
        5
'''

class Transactions:
    tid = None
    def __init__(self, tid):
        self.tid = tid

# creating transaction_list
transaction_list = []
ids = [1,2,3,1,5,5,6]
for x in ids:
    transaction_list.append(Transactions(x))

# initial length of transaction_list
print(len(transaction_list))

tmp = []

for idx,obj in enumerate(transaction_list):
    if obj.tid not in tmp:
        tmp.append(obj.tid)
    else:
        del transaction_list[idx]

# final length of transaction_list
print(len(transaction_list))

Body:
In a for loop you need to pass a copy of a list because currently you try to delete element by id and you modify the original list so next time the list has changed.

To solve it you can add : like so for idx,obj in enumerate(transaction_list[:]): and it will work like so:

class Transactions:
    def __init__(self, tid):
        self.tid = tid

# creating transaction_list
transaction_list = []
ids = [1,2,3,1,5,5,6]
for x in ids:
    transaction_list.append(Transactions(x))

# initial length of transaction_list
print(len(transaction_list))

tmp = []

for idx,obj in enumerate(transaction_list[:]):
    if obj.tid not in tmp:
        tmp.append(obj.tid)
    else:
        del transaction_list[idx]

# final length of transaction_list
print(len(transaction_list))

The output is:

7
5


问:
How do I get the list of imports and dependant files from python script?
I have a .py file that imports from other python modules that import from config files, other modules, etc.

I am to move the code needed to run that .py file, but only whatever the py file is reading from (I am not talking about packages installed by pip install, it's more about other python files in the project directory, mostly classes, functions and ini files).

Is there a way to find out only the external files used by that particular python script? Is it something that can be found using PyCharm for example?

Thanks!

答:
Static analysis tools (such as PyCharm's refactoring tools) can (mostly) figure out the module import tree for a program (unless you do dynamic imports using e.g. importlib.import_module()).

However, it's not quite possible to statically definitively know what other files are required for your program to function. You could use Python's audit events (or strace/ptrace or similar OS-level functions) to look at what files are being opened by your program (e.g. during your tests being run (you do have tests, right?), or during regular program use), but it's likely not going to be exhaustive.