问:
Android - Setting absolute dimensions and position programmatically
I have a specific use-case where I will be doing all the computation of the layout to calculate the x and y position, height and width etc and then place the widgets accordingly. I am creating the layouts and widgets programmatically i.e. not using the xml way of layouting.
I understand that absolute-layout is deprecated in Android.
I tried creating a layout by using LinerLayout as well as Relative Layout. The position/dimension were set as follows.

```<code>button.setX(pPosX);
button.setY(pPosY);
button.setHeight(pHeight);
button.setWidth(pWidth);
</code>```

The behaviour if width is different for Linear and Relative layout. In Linear (with orientation as Vertical), it seems to be taking the full width even if a smaller width is given. With Horizontal Orientation, it doesnt take the width as given.

Which is the right layout to use when i want to do absolute positioning ? Is there any considerations to keep in mind for this.

Am a little new to this hence would be good to get any inputs/suggestions.

Body:
I have a specific use-case where I will be doing all the computation of the layout to calculate the x and y position, height and width etc and then place the widgets accordingly. I am creating the layouts and widgets programmatically i.e. not using the xml way of layouting.
I understand that absolute-layout is deprecated in Android.
I tried creating a layout by using LinerLayout as well as Relative Layout. The position/dimension were set as follows.

button.setX(pPosX);
button.setY(pPosY);
button.setHeight(pHeight);
button.setWidth(pWidth);

The behaviour if width is different for Linear and Relative layout. In Linear (with orientation as Vertical), it seems to be taking the full width even if a smaller width is given. With Horizontal Orientation, it doesnt take the width as given.

Which is the right layout to use when i want to do absolute positioning ? Is there any considerations to keep in mind for this.

Am a little new to this hence would be good to get any inputs/suggestions.


来源: stackexchange

问:
Macro Scoping to Module
I'm having some trouble trying to scope a macro.

I have my library abc with lib.rs that contains only:

pub mod example;
```
<p>and then in <code>example.rs</code> at the same level as <code>lib.rs</code>:</p>
<pre class="lang-rust prettyprint-override"><code>#[macro_export]
macro_rules! my_example {
    () => {
        no.arg.passed(None)
    };

    ($x:expr) => {
        arg.passed(Some($x))
    };
}
</code>```

I want the my_example! macro to be only accessible through abc::example::my_example!, however the above code seems to result in it being only accessible through abc::my_example!.

I think I may be misunderstanding the #[macro_export]'s effect. Any suggestions on how to achieve the module-scoped macro?

ContentLicense: CC BY-SA 4.0

Title: Macro Scoping to Module

Body:
I'm having some trouble trying to scope a macro.

I have my library abc with lib.rs that contains only:

pub mod example;

and then in example.rs at the same level as lib.rs:

#[macro_export]
macro_rules! my_example {
    () => {
        no.arg.passed(None)
    };

    ($x:expr) => {
        arg.passed(Some($x))
    };
}

I want the my_example! macro to be only accessible through abc::example::my_example!, however the above code seems to result in it being only accessible through abc::my_example!.

I think I may be misunderstanding the #[macro_export]'s effect. Any suggestions on how to achieve the module-scoped macro?


问:
accidentally used git commit --amend --no-edit after adding changes to files. what happened?
still learning how to use git.

i added changes to the files from the last commit. Then i ran the git commit --amend --no-edit command, which was
a mistake.

After trying to push changes, it said I had a merge conflict.

I resolved the merge conflict (my repository is still very small, so it wasn't very confusing). I just don't understand what happened to the repo.

Can someone explain what happened?


问:
pip3 install gives me error 128 when trying to install from github
I am trying to install wav2vec and per instructions on their github I'm using

```<code>pip3 install git+https://github.com/vasudevgupta7/gsoc-wav2vec2@main
</code>```

it gives me

ERROR: Command errored out with exit status 128: git clone -q https://github.com/vasudevgupta7/gsoc-wav2vec2 /tmp/pip-req-build-7pnrs747 Check the logs for full command output.

what is the problem?

Body:
I am trying to install wav2vec and per instructions on their github I'm using

pip3 install git+https://github.com/vasudevgupta7/gsoc-wav2vec2@main

it gives me

ERROR: Command errored out with exit status 128: git clone -q https://github.com/vasudevgupta7/gsoc-wav2vec2 /tmp/pip-req-build-7pnrs747 Check the logs for full command output.

what is the problem?


问:
tf.data variable length input with generator
Mini-batch input is [batch, seq_len, feature_dim], and seq_len is different for each mini-batch.

```<code>tf.data.Dataset.from_generator(lambda : (x for x in mini_batches),
                               output_signatures = (None, None, feature_dim))
</code>```

generator yielded an element of shape (9, 30, 6) where an element of
shape (None, None, 6) was expected

How can I solve this problem?

Body:
Mini-batch input is [batch, seq_len, feature_dim], and seq_len is different for each mini-batch.

tf.data.Dataset.from_generator(lambda : (x for x in mini_batches),
                               output_signatures = (None, None, feature_dim))

generator yielded an element of shape (9, 30, 6) where an element of
shape (None, None, 6) was expected

How can I solve this problem?


问:
How to create a document file with the data from the backend?
I have a user name, age, and locality from the backend. Now, I want to create a file or print the details in a specific format. I also have an organization image to be inserted in the file. How can I achieve this?

For Example,

Above the name, the image has to be inserted.

I have tried this with the Quill Package but can't able to create a document.

this is my code:

```<code>Future<void> downloadingOpdCard({required int index}) async {
    quill.QuillController controller = quill.QuillController(
        document: quill.Document.fromJson(jsondata),
        selection: const TextSelection.collapsed(offset: 0));
    Directory dir = Directory("/storage/emulated/0/MedBook");
    PermissionStatus permission = await Permission.storage.status;

    try {
      if (permission.isDenied) {
        Permission.storage.request();
      }
      if (await permission.isGranted) {
        if (!dir.existsSync()) {
          dir.createSync(recursive: true);
          File file = File("${dir.path}/sample.doc");
          print(file.absolute);
          if (file.existsSync()) {
            file.deleteSync();
            file.writeAsString(controller.document.getPlainText(0, 300));
          } else {
            file.writeAsString(controller.document.getPlainText(0, 300));
          }
        } else {
          File file = File("${dir.path}/sample.doc");
          print(file.absolute);
          file.writeAsString(
              controller.document.toDelta().first.data.toString());
        }
      } else {
        print("Permission Denied");
      }
    } catch (e) {
      print(e);
    }
  }
</code>```

Body:
I have a user name, age, and locality from the backend. Now, I want to create a file or print the details in a specific format. I also have an organization image to be inserted in the file. How can I achieve this?

For Example,

Above the name, the image has to be inserted.

I have tried this with the Quill Package but can't able to create a document.

this is my code:

Future<void> downloadingOpdCard({required int index}) async {
    quill.QuillController controller = quill.QuillController(
        document: quill.Document.fromJson(jsondata),
        selection: const TextSelection.collapsed(offset: 0));
    Directory dir = Directory("/storage/emulated/0/MedBook");
    PermissionStatus permission = await Permission.storage.status;

    try {
      if (permission.isDenied) {
        Permission.storage.request();
      }
      if (await permission.isGranted) {
        if (!dir.existsSync()) {
          dir.createSync(recursive: true);
          File file = File("${dir.path}/sample.doc");
          print(file.absolute);
          if (file.existsSync()) {
            file.deleteSync();
            file.writeAsString(controller.document.getPlainText(0, 300));
          } else {
            file.writeAsString(controller.document.getPlainText(0, 300));
          }
        } else {
          File file = File("${dir.path}/sample.doc");
          print(file.absolute);
          file.writeAsString(
              controller.document.toDelta().first.data.toString());
        }
      } else {
        print("Permission Denied");
      }
    } catch (e) {
      print(e);
    }
  }


问:
Go-micro v3 on mac micro signup Failed to connect to micro server at 127.0.0.1:8081
Here I try to run a test example of go-micro-v3 locally. I have set micro env set local
And I fail to see the properly micro service
When I run micro service, it shows

```<code>2022-12-18 15:55:29  file=service/service.go:118 level=info Service [mucp] Serving service at endpoint localhost:9090
2022-12-18 15:55:29  file=service/service.go:195 level=info Starting [service] service
2022-12-18 15:55:29  file=grpc/grpc.go:998 level=info Server [grpc] Listening on [::]:63958
2022-12-18 15:55:29  file=grpc/grpc.go:828 level=info Registry [service] Registering node: service-26a4dfdc-1bd4-4b3e-b3ac-d79a530e1a44
2022-12-18 15:55:32  file=grpc/grpc.go:1022 level=error Server register error: {"id":"go.micro.client","code":500,"detail":"connection error: desc = \"transport: Error while dialing dial tcp 127.0.0.1:8081: connect: connection refused\"","status":"Internal Server Error"}
</code>```

And I try to use login/signup it all shows
Failed to connect to micro server at 127.0.0.1:8081

Anyone can offer some ideas?

Body:
Here I try to run a test example of go-micro-v3 locally. I have set micro env set local
And I fail to see the properly micro service
When I run micro service, it shows

2022-12-18 15:55:29  file=service/service.go:118 level=info Service [mucp] Serving service at endpoint localhost:9090
2022-12-18 15:55:29  file=service/service.go:195 level=info Starting [service] service
2022-12-18 15:55:29  file=grpc/grpc.go:998 level=info Server [grpc] Listening on [::]:63958
2022-12-18 15:55:29  file=grpc/grpc.go:828 level=info Registry [service] Registering node: service-26a4dfdc-1bd4-4b3e-b3ac-d79a530e1a44
2022-12-18 15:55:32  file=grpc/grpc.go:1022 level=error Server register error: {"id":"go.micro.client","code":500,"detail":"connection error: desc = \"transport: Error while dialing dial tcp 127.0.0.1:8081: connect: connection refused\"","status":"Internal Server Error"}

And I try to use login/signup it all shows
Failed to connect to micro server at 127.0.0.1:8081

Anyone can offer some ideas?


问:
Create a test cases document covering positive and negative test cases of above scenario
Take an online HRMS portal where the employee logs in with his user account and password. On the
login page, there are two text fields for the username & password, and two buttons: Login and Cancel. Successful login takes the user to the HRMS home page and cancel will cancel the login. Specifications:
#1 ) The user id field takes a minimum of 6 characters, a maximum of 10 characters, numbers(0-9),
letters(a-z, A-z), special characters (only underscore, period, hyphen allowed) and it cannot be left
blank. User id must begin with a character or a number and not special characters. #2) Password field takes a minimum of 6 characters, a maximum of 8 characters, numbers (0-9),
letters (a-z, A-Z), special characters (all) and cannot be blank. Create a test cases document covering positive and negative test cases of above scenario

i tried writing test case but it failed


问:
Different size of forms even though they have the same size
I have 4 images here. I am using Visual Studio 2019.

As you can see there, they have the same width and height.
But when I run the program this comes out.

As you can see. They are not even the same size, not even close at all. How to fix this?

What I remembered doing is when I was fixing the fonts in Add Operation. It suddenly auto adjusted its size and it became like that. I would want Record to do the same.


问:
Mark High/Low of 2nd 5min candle from market open
Is there anyway to get the high and low value of the 2nd 5min candle from market open also target lines of 1:2 i.e
If 2nd candle is green,Target= high + 2*(high -low)
If 2nd candle is red, Target= Low - 2*(high-low)

thanks in advance


问:
address of static variable are different from `this` only when source file exists - but problem disappears if all code is in one header
I tested this in wandbox.org

Foo.h ::-

```<code>struct Foo {
    Foo();
    void dummy(){}
};
static Foo foo;
</code>```

Foo.cpp ::-

```<code>#include "Foo.h"
#include <iostream>
Foo::Foo()  {
    std::cout<<&foo<<std::endl;
    std::cout<<this<<std::endl;
};
</code>```

main.cpp ::-

```<code>#include "a.h"
int main(){
    foo.dummy();
}
</code>```

Result ::-

```<code>0x7f333ff1077e
0x7f333ff1077e
0x7f333ff1077e
0x7f333ff1077c
</code>```

Why 2 thread local variables are created?    (not 1? / is it actually 1?)

Why the address of &foo and this are not the same?

If I pack all of code into 1 header, the result will be as expected.  ( https://coliru.stacked-crooked.com/a/d9184eae09b0bffd )

```<code>0x7f385b59973f
0x7f385b59973f
</code>```

Body:
I tested this in wandbox.org

Foo.h ::-

struct Foo {
    Foo();
    void dummy(){}
};
static Foo foo;

Foo.cpp ::-

#include "Foo.h"
#include <iostream>
Foo::Foo()  {
    std::cout<<&foo<<std::endl;
    std::cout<<this<<std::endl;
};

main.cpp ::-

#include "a.h"
int main(){
    foo.dummy();
}

Result ::-

0x7f333ff1077e
0x7f333ff1077e
0x7f333ff1077e
0x7f333ff1077c

Why 2 thread local variables are created?    (not 1? / is it actually 1?)

Why the address of &foo and this are not the same?

If I pack all of code into 1 header, the result will be as expected.  ( https://coliru.stacked-crooked.com/a/d9184eae09b0bffd )

0x7f385b59973f
0x7f385b59973f


问:
How do I suppress printing codes from system headers in gcc -E
Basically, I need to amalgamate the source code into a single file . gcc -E almost does the job for me, except for the fact that I don't need to print the codes from system headers.
That is it should print my code as well as any codes from 3rd party library used but nothing from a system library.

I was wondering if I can tweak gcc -E such that it suppresses printing the codes from system headers.
In case that's already achievable by a combination of some other options, you can mention that as well.

I have gone through this answer. this hack doesn't work because the 3rd party libraries themselves call system headers which need to be suppressed as well.


问:
How to stop scrolling of Main body from iframe css
I am creating a small webpage with pure HTML & CSS only in which I created a lightbox with the help of CSS because using of any kind of script or library is prohibited. I successfully created the lightbox in div which is targeted by an image. when I target that div it will appear like a full page modal with a lightbox in it and when it is targeted, the body scrolling stops or overflow is hidden also. the problem is that this web page is used in an iframe of another page and both the functionalities of full page modal and stop scrolling are worked in a container of iframe only but I want that it works to the main page body means when I click on the image which targeted my modal. the modal/popup should appear outside the iframe and fit the device screen and also the main page in the iframe contains is stop scrolling. Can anyone help me.

One more thing we cannot change outside the iframe structure because we just allow adding a webpage inside an iframe so we just only have the possibility to change and control everything from inside the iframe CSS.

#popup = (The Modal body in which the lightbox contains)

```<code>#popup {
        position: fixed;
        background-color: rgba(0, 0, 0, 0.75);
        top: 0px;
        left: 0px;
        width: 100%;
        height: 100%;
        z-index: 99;
        display: none;
    }

when the modal targeted by href
    #popup:target {
        display: block;
    }

when the modal target by href the body stops scrolling
    body:has(iframe #popup:target) {
        overflow: hidden ! important;
    }
</code>```

Body:
I am creating a small webpage with pure HTML & CSS only in which I created a lightbox with the help of CSS because using of any kind of script or library is prohibited. I successfully created the lightbox in div which is targeted by an image. when I target that div it will appear like a full page modal with a lightbox in it and when it is targeted, the body scrolling stops or overflow is hidden also. the problem is that this web page is used in an iframe of another page and both the functionalities of full page modal and stop scrolling are worked in a container of iframe only but I want that it works to the main page body means when I click on the image which targeted my modal. the modal/popup should appear outside the iframe and fit the device screen and also the main page in the iframe contains is stop scrolling. Can anyone help me.

One more thing we cannot change outside the iframe structure because we just allow adding a webpage inside an iframe so we just only have the possibility to change and control everything from inside the iframe CSS.

#popup = (The Modal body in which the lightbox contains)

#popup {
        position: fixed;
        background-color: rgba(0, 0, 0, 0.75);
        top: 0px;
        left: 0px;
        width: 100%;
        height: 100%;
        z-index: 99;
        display: none;
    }

when the modal targeted by href
    #popup:target {
        display: block;
    }

when the modal target by href the body stops scrolling
    body:has(iframe #popup:target) {
        overflow: hidden ! important;
    }


问:
How to convert int 255 to char type 1 byte variable in Android?
I am trying to send 0xff(255) value by ble communication
The 255 value in int is converted using Character.toChars and then sent, but C3 BF data is received at the receiving end. Is there a way to convert 0xff into a 1-byte char variable and send it?

thank you


问:
Extending Sequelize Model for Inheritance
I have build some sequelize models with strict typing extending Model like Account, ContactData, Address and so on. Since I‘m persisting roles for an Account and I came across Domain-Driven Design, I am going to split up my code and shift the roles away from database to Account Entity. Also splitting up the account model into several „more detailed“ models like Admin and Customer, is it possible to extend one model with like BaseAccount to inherit properties and methods for code reduction at all?

I've declared my Parent class like:

```<code>type Account = Admin | Customer | Editor | Partner;

export default class BaseAccount<T extends Account> extends Model<InferAttributes<T>, InferCreationAttributes<T>> {
    declare id: CreationOptional<number>;
    declare email: string;
    declare password: string;

    public async encryptPasswordHook(account: T) {
        const passwordHasChanged = account.changed("password");

        if (passwordHasChanged) {
            const password = account.getDataValue("password");
            const hashedPassword = await this.hashPassword(password);

            return Promise.resolve(account.setDataValue("password", hashedPassword));
        } else return;
    }
}
</code>```

and then extending my model with BaseAccount like:

```<code>export default class Admin extends BaseAccount<Admin> {}
</code>```

But this does not work since sequelized .change() method has no overload for this

Body:
I have build some sequelize models with strict typing extending Model like Account, ContactData, Address and so on. Since I‘m persisting roles for an Account and I came across Domain-Driven Design, I am going to split up my code and shift the roles away from database to Account Entity. Also splitting up the account model into several „more detailed“ models like Admin and Customer, is it possible to extend one model with like BaseAccount to inherit properties and methods for code reduction at all?

I've declared my Parent class like:

type Account = Admin | Customer | Editor | Partner;

export default class BaseAccount<T extends Account> extends Model<InferAttributes<T>, InferCreationAttributes<T>> {
    declare id: CreationOptional<number>;
    declare email: string;
    declare password: string;

    public async encryptPasswordHook(account: T) {
        const passwordHasChanged = account.changed("password");

        if (passwordHasChanged) {
            const password = account.getDataValue("password");
            const hashedPassword = await this.hashPassword(password);

            return Promise.resolve(account.setDataValue("password", hashedPassword));
        } else return;
    }
}

and then extending my model with BaseAccount like:

export default class Admin extends BaseAccount<Admin> {}

But this does not work since sequelized .change() method has no overload for this


问:
Not able to build solution for webservice in azure devops pipeline
I am azure devops person and deploy web app for.Net framework projects using yaml pipeline. Recently I was asked to deploy webservices. But my regular yaml pipeline not building the solution and artifact produced by it is empty. Has anyone ever deployed webservices in Azure devops. Please help.

Task I use

Nuget install

Nuget restore

VsBuild

PublishBuildArtifacts

Vsbuild task looks like below

```<code>- task: VSBuild@1inputs:solution: ‘$(solution)’msbuildArgs: ‘/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation=”$(build.artifactstagingdirectory)\\”
</code>```

For webapps it works perfectly fine but not working for webservices

In solution I tried providing cproj file path but didn't work.

Only thing seems to work for me is in msbuildargs i am using '/p:depliyonbuild=true;OutDir="$(System.DefaultWorkingDirectory) \any_folder_name

This is creating two directories which I zip in one zip file using ArchiveFile task after VSbuild task and trying to deploy it on webservice in release part. But not sure if it's correct way

Body:
I am azure devops person and deploy web app for.Net framework projects using yaml pipeline. Recently I was asked to deploy webservices. But my regular yaml pipeline not building the solution and artifact produced by it is empty. Has anyone ever deployed webservices in Azure devops. Please help.

Task I use

Nuget install

Nuget restore

VsBuild

PublishBuildArtifacts

Vsbuild task looks like below

- task: VSBuild@1inputs:solution: ‘$(solution)’msbuildArgs: ‘/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation=”$(build.artifactstagingdirectory)\\”

For webapps it works perfectly fine but not working for webservices

In solution I tried providing cproj file path but didn't work.

Only thing seems to work for me is in msbuildargs i am using '/p:depliyonbuild=true;OutDir="$(System.DefaultWorkingDirectory) \any_folder_name

This is creating two directories which I zip in one zip file using ArchiveFile task after VSbuild task and trying to deploy it on webservice in release part. But not sure if it's correct way


问:
ngxDaterangepickerMd Open datepicker from outside in angular
I struggle to open ngxDaterangepickerMd from outside. I need two single-datepickers, one for the "from date" and one for the "to date". When I click on the from-button the from-datepicker should open and when I click on the to-button the to-datepicker should show up. Yet in my case when I click on the to-datepicker, the from-datepicker opens instead.

This is the code for my from-button:

```<code> <input type="text" class="datepicker-calendar-icon"  ngxDaterangepickerMd  [locale]="{ format: 'DD/MM/YYYY' }" [(ngModel)]="startDate" [singleDatePicker]="true"
                        [autoApply]="true" [minDate]="minDate" (change)="setStartDate()" />
<button>from</button>
</code>```

This is the code for my to-button:

```<code> <input type="text" class="datepicker-calendar-icon"  ngxDaterangepickerMd  [locale]="{ format: 'DD/MM/YYYY' }" [(ngModel)]="endDate" [singleDatePicker]="true"
                        [autoApply]="true" [minDate]="minDate" (change)="setStartDate()" />
<button>to</button>
</code>```

I followed this as reference  https://github.com/fetrarij/ngx-daterangepicker-material#open-datepicker-from-outside

Do you have any idea how I can solve this problem?

Body:
I struggle to open ngxDaterangepickerMd from outside. I need two single-datepickers, one for the "from date" and one for the "to date". When I click on the from-button the from-datepicker should open and when I click on the to-button the to-datepicker should show up. Yet in my case when I click on the to-datepicker, the from-datepicker opens instead.

This is the code for my from-button:

 <input type="text" class="datepicker-calendar-icon"  ngxDaterangepickerMd  [locale]="{ format: 'DD/MM/YYYY' }" [(ngModel)]="startDate" [singleDatePicker]="true"
                        [autoApply]="true" [minDate]="minDate" (change)="setStartDate()" />
<button>from</button>

This is the code for my to-button:

 <input type="text" class="datepicker-calendar-icon"  ngxDaterangepickerMd  [locale]="{ format: 'DD/MM/YYYY' }" [(ngModel)]="endDate" [singleDatePicker]="true"
                        [autoApply]="true" [minDate]="minDate" (change)="setStartDate()" />
<button>to</button>

I followed this as reference  https://github.com/fetrarij/ngx-daterangepicker-material#open-datepicker-from-outside

Do you have any idea how I can solve this problem?


问:
How can I Make the User get a Notification When Another User Sends him a Chat Message
So I'm using the Firebase and React to make a chat.

And I need to notify the user when another user sends him a message in the chat.

Is there an easy way to do it.

Input.js File with sending system.

```<code>import React, { useContext, useState } from "react";
import Img from "../../static/chat/add-img.png";
import Attach from "../../static/chat/attach.png";
import { AuthContext } from "./AuthContext";
import { ChatContext } from "./ChatContext";
import {
  arrayUnion,
  doc,
  serverTimestamp,
  Timestamp,
  updateDoc,
} from "firebase/firestore";
import { db, storage } from "../../firebase";
import { v4 as uuid } from "uuid";
import { getDownloadURL, ref, uploadBytesResumable } from "firebase/storage";

const Input = () => {
  const [text, setText] = useState("");
  const [img, setImg] = useState(null);
  const { currentUser } = useContext(AuthContext);
  const { data } = useContext(ChatContext);

  const handleSend = async () => {
    if (img) {
      const storageRef = ref(storage, uuid());

      const uploadTask = uploadBytesResumable(storageRef, img);

      uploadTask.on(
        (error) => {
          //TODO:Handle Error
        },
        () => {
          getDownloadURL(uploadTask.snapshot.ref).then(async (downloadURL) => {
            await updateDoc(doc(db, "chats", data.chatId), {
              messages: arrayUnion({
                id: uuid(),
                text,
                senderId: currentUser.uid,
                date: Timestamp.now(),
                img: downloadURL,
              }),
            });
          });
        }
      );
    } else {
      await updateDoc(doc(db, "chats", data.chatId), {
        messages: arrayUnion({
          id: uuid(),
          text,
          senderId: currentUser.uid,
          date: Timestamp.now(),
        }),
      });
    }

    await updateDoc(doc(db, "userChats", currentUser.uid), {
      [data.chatId + ".lastMessage"]: {
        text,
      },
      [data.chatId + ".date"]: serverTimestamp(),
    });

    await updateDoc(doc(db, "userChats", data.user.uid), {
      [data.chatId + ".lastMessage"]: {
        text,
      },
      [data.chatId + ".date"]: serverTimestamp(),
    });

    setText("");
    setImg(null);
  };
  return (
    <div className="input">
      <input
        type="text"
        placeholder="Type something..."
        onChange={(e) => setText(e.target.value)}
        value={text}
      />
      <div className="send">
        <img src={Attach} alt="" />
        <input
          type="file"
          style={{ display: "none" }}
          id="file"
          onChange={(e) => setImg(e.target.files[0])}
        />
        <label htmlFor="file">
          <img src={Img} alt="" />
        </label>
        <button onClick={handleSend}>Send</button>
      </div>
    </div>
  );
};

export default Input;
</code>```

Message.jsThe file that shows the messages.

```<code>import React, { useContext, useEffect, useRef } from "react";
import { AuthContext } from "./AuthContext";
import { ChatContext } from "./ChatContext";

const Message = ({ message }) => {
  const { currentUser } = useContext(AuthContext);
  const { data } = useContext(ChatContext);
  const ref = useRef();

  useEffect(() => {
    ref.current?.scrollIntoView({ behavior: "smooth" });
  }, [message]);

  return (
    <div
      ref={ref}
      className={`message ${message.senderId === currentUser.uid && "owner"}`}
    >
      <div className="messageInfo">
        <img
          src={
            message.senderId === currentUser.uid
              ? currentUser.photoURL
              : data.user.photoURL
          }
          alt=""
        />
        <span>just now</span>
      </div>
      <div className="messageContent">
        <p>{message.text}</p>
        {message.img && <img src={message.img} alt="" />}
      </div>
    </div>
  );
};

export default Message;
</code>```

Can you help me Implement it.

Body:
So I'm using the Firebase and React to make a chat.

And I need to notify the user when another user sends him a message in the chat.

Is there an easy way to do it.

Input.js File with sending system.

import React, { useContext, useState } from "react";
import Img from "../../static/chat/add-img.png";
import Attach from "../../static/chat/attach.png";
import { AuthContext } from "./AuthContext";
import { ChatContext } from "./ChatContext";
import {
  arrayUnion,
  doc,
  serverTimestamp,
  Timestamp,
  updateDoc,
} from "firebase/firestore";
import { db, storage } from "../../firebase";
import { v4 as uuid } from "uuid";
import { getDownloadURL, ref, uploadBytesResumable } from "firebase/storage";

const Input = () => {
  const [text, setText] = useState("");
  const [img, setImg] = useState(null);
  const { currentUser } = useContext(AuthContext);
  const { data } = useContext(ChatContext);

  const handleSend = async () => {
    if (img) {
      const storageRef = ref(storage, uuid());

      const uploadTask = uploadBytesResumable(storageRef, img);

      uploadTask.on(
        (error) => {
          //TODO:Handle Error
        },
        () => {
          getDownloadURL(uploadTask.snapshot.ref).then(async (downloadURL) => {
            await updateDoc(doc(db, "chats", data.chatId), {
              messages: arrayUnion({
                id: uuid(),
                text,
                senderId: currentUser.uid,
                date: Timestamp.now(),
                img: downloadURL,
              }),
            });
          });
        }
      );
    } else {
      await updateDoc(doc(db, "chats", data.chatId), {
        messages: arrayUnion({
          id: uuid(),
          text,
          senderId: currentUser.uid,
          date: Timestamp.now(),
        }),
      });
    }

    await updateDoc(doc(db, "userChats", currentUser.uid), {
      [data.chatId + ".lastMessage"]: {
        text,
      },
      [data.chatId + ".date"]: serverTimestamp(),
    });

    await updateDoc(doc(db, "userChats", data.user.uid), {
      [data.chatId + ".lastMessage"]: {
        text,
      },
      [data.chatId + ".date"]: serverTimestamp(),
    });

    setText("");
    setImg(null);
  };
  return (

      <input
        type="text"
        placeholder="Type something..."
        onChange={(e) => setText(e.target.value)}
        value={text}
      />

        <input
          type="file"
          style={{ display: "none" }}
          id="file"
          onChange={(e) => setImg(e.target.files[0])}
        />

        <button onClick={handleSend}>Send</button>

  );
};

export default Input;

Message.jsThe file that shows the messages.

import React, { useContext, useEffect, useRef } from "react";
import { AuthContext } from "./AuthContext";
import { ChatContext } from "./ChatContext";

const Message = ({ message }) => {
  const { currentUser } = useContext(AuthContext);
  const { data } = useContext(ChatContext);
  const ref = useRef();

  useEffect(() => {
    ref.current?.scrollIntoView({ behavior: "smooth" });
  }, [message]);

  return (
    <div
      ref={ref}
      className={`message ${message.senderId === currentUser.uid && "owner"}`}
    >

        just now

{message.text}

        {message.img && }

  );
};

export default Message;

Can you help me Implement it.


问:
How to manage so many charts in Apache Superset?
In Apache Superset for preparing a dashboard first we have to prepare charts and then add them to dashboard in this process ample number of charts got created and there is difficulty in finding some previous chart we made. Is there any way to manage those charts.

I tried providing a nomenclature to the charts but still it is confusing.


问:
Display profile using current user
```<code>Padding(
  padding: const EdgeInsets.all(16.0),
  child: Text(FirebaseAuth.instance.currentUser!.email!),
),
Padding(
  padding: const EdgeInsets.all(16.0),
  child: Text(
    FirebaseAuth.instance.currentUser!.displayName ?? 'No Name' // I can't display the current username in my firebase
  ),
),
</code>```

I can't display username of current user in order to update profile purposes.How to use uid current user please help me im stucked now :(

Title: Display profile using current user

Body:
Padding(
  padding: const EdgeInsets.all(16.0),
  child: Text(FirebaseAuth.instance.currentUser!.email!),
),
Padding(
  padding: const EdgeInsets.all(16.0),
  child: Text(
    FirebaseAuth.instance.currentUser!.displayName ?? 'No Name' // I can't display the current username in my firebase
  ),
),

I can't display username of current user in order to update profile purposes.How to use uid current user please help me im stucked now :(


问:
Possible to pass through all functions of PCI devices in Openstack?
Many PCI devices (e.g. GPUs) are multifunction.

For instance, for an NVIDIA 3090:

```<code>02:00.0 VGA compatible controller: NVIDIA Corporation GA102 [GeForce RTX 3090] (rev a1)
02:00.1 Audio device: NVIDIA Corporation GA102 High Definition Audio Controller (rev a1)
</code>```

However, OpenStack only supports passing through the root device (like 02:00.0). Separately, you can pass through the other sub-devices.

When passing through all devices separately on multi-GPU servers, we sometimes get this situation:

```<code>mysql> use nova;
mysql> select address, product_id, dev_id, status from pci_devices where deleted = 0;
+--------------+------------+------------------+-----------+
| address      | product_id | dev_id           | status    |
+--------------+------------+------------------+-----------+
| 0000:01:00.0 | 24b0       | pci_0000_01_00_0 | allocated |
| 0000:01:00.1 | 228b       | pci_0000_01_00_1 | available |
| 0000:45:00.0 | 24b0       | pci_0000_45_00_0 | available |
| 0000:45:00.1 | 228b       | pci_0000_45_00_1 | allocated |
+--------------+------------+------------------+-----------+
14 rows in set (0.00 sec)
</code>```

As you can see, in this machine, OpenStack has passed through the audio device of PCI 45:00, whereas it has passed through the GPU of PCI 01:00.

This configuration is problematic, as we need the audio devices and the GPUs themselves to be on the same physical PCI card.

Any thoughts or advice?

One option is to just use Libvirt and use the "multifunction=on" and skip OpenStack entirely, but I'm really curious as to if OpenStack has some similar functionality so that all slots / subfunctions are passed through into VMs form the same physical PCI device.

Thanks!

Body:
Many PCI devices (e.g. GPUs) are multifunction.

For instance, for an NVIDIA 3090:

02:00.0 VGA compatible controller: NVIDIA Corporation GA102 [GeForce RTX 3090] (rev a1)
02:00.1 Audio device: NVIDIA Corporation GA102 High Definition Audio Controller (rev a1)

However, OpenStack only supports passing through the root device (like 02:00.0). Separately, you can pass through the other sub-devices.

When passing through all devices separately on multi-GPU servers, we sometimes get this situation:

mysql> use nova;
mysql> select address, product_id, dev_id, status from pci_devices where deleted = 0;
+--------------+------------+------------------+-----------+
| address      | product_id | dev_id           | status    |
+--------------+------------+------------------+-----------+
| 0000:01:00.0 | 24b0       | pci_0000_01_00_0 | allocated |
| 0000:01:00.1 | 228b       | pci_0000_01_00_1 | available |
| 0000:45:00.0 | 24b0       | pci_0000_45_00_0 | available |
| 0000:45:00.1 | 228b       | pci_0000_45_00_1 | allocated |
+--------------+------------+------------------+-----------+
14 rows in set (0.00 sec)

As you can see, in this machine, OpenStack has passed through the audio device of PCI 45:00, whereas it has passed through the GPU of PCI 01:00.

This configuration is problematic, as we need the audio devices and the GPUs themselves to be on the same physical PCI card.

Any thoughts or advice?

One option is to just use Libvirt and use the "multifunction=on" and skip OpenStack entirely, but I'm really curious as to if OpenStack has some similar functionality so that all slots / subfunctions are passed through into VMs form the same physical PCI device.

Thanks!


问:
Will apps run on the latest version of IOS if they were developed in an older version of Xcode?
My Mac only lets met run Xcode 13.2, which is an older version of Xcode.

If I develop an app using this version of Xcode and publish it to the App store, will it be able to run on the latest version of IOS on iPhone (IOS 16 and above)?

Please let me know, thanks!


问:
How to get a Swift Package to be build with the Release Build Configuration of the current Scheme in Xcode?
I have moved some of my code from my main application to a Swift Package. But I noticed a slow down.

I have set the Build Configuration to Release in the scheme configuration, but it does not seem to be used when building the package.

So the same code in the main application will run much faster than in the package because it's optimised.

What could I be doing wrong? What configuration should I check?

I am using the Xcode 14.0.1 and I put a very small example project in github


问:
Exclusive behavior for Checkboxs in Angular Project
I am working on a angular project in which user is able to see news from different news sources. I have created a navigation pane which shows all the news sources fetched with checkbox.Navigation bar.

Behavior i am trying to achieve is like this - Behavior i am trying to achieve

Navigation.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { Observable } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';
import { NewsfetchserviceService } from '../newsfetchservice.service';
import { NewsData } from '../NewsData';
@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html',
  styleUrls: ['./navigation.component.css']
})
export class NavigationComponent implements OnInit{

  sourcesList : NewsData[] = [];
  selectAllFilter = true;
  selectSingleFilter = true;

  ngOnInit(): void {
    this.showAllSources();
  }

  isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset)
    .pipe(
      map(result => result.matches),
      shareReplay()
    );

  constructor(private breakpointObserver: BreakpointObserver,private newsfetch: NewsfetchserviceService) {}

  showAllSources():void {
    this.sourcesList = this.newsfetch.allNews;
    /* this.newsfetch.getNews().subscribe(news => this.news = news); */
  }

  updateNewsList(source : NewsData):void{
    this.newsfetch.updateNewsBlock(source);
    this.selectAllFilter = false;
    this.checkboxBehaviour(2);
  }

  updateAllNewsList(source : NewsData[]):void{
    this.newsfetch.updateAllNewsBlock(source);
    this.checkboxBehaviour(1);
  }

  checkboxBehaviour(input : number):void{
    if(this.selectSingleFilter == false && this.selectAllFilter == false && input == 1)
    {
      this.selectSingleFilter = true;
      this.selectAllFilter = true;
    }else{
      this.selectSingleFilter = false;
      this.selectAllFilter = false;
    }

    if(input == 2)
    {
      this.selectSingleFilter = false;
      this.selectAllFilter = false;
    }

  }
}

</code>```

Navigation.component.html

```<code><mat-sidenav-container class="sidenav-container">
  <mat-sidenav #drawer class="sidenav" fixedInViewport
      [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'"
      [mode]="(isHandset$ | async) ? 'over' : 'side'"
      [opened]="(isHandset$ | async) === false">
    <mat-toolbar>Menu</mat-toolbar>
    <mat-nav-list>
      <mat-expansion-panel [class.mat-elevation-z0]="true">
        <mat-expansion-panel-header>
            All Sources
        </mat-expansion-panel-header>
        <mat-checkbox [checked]="selectAllFilter" (change)="updateAllNewsList(sourcesList)">Select All</mat-checkbox>
        <mat-nav-list *ngFor="let source of sourcesList">
            <!-- <a mat-list-item (click)="updateNewsList(source)">{{source.name}}</a> -->
            <mat-checkbox [checked]="selectSingleFilter" (change)="updateNewsList(source)">{{source.name}}</mat-checkbox>
           <!--  <a mat-list-item >Hibernate</a> -->
            <!-- <a mat-list-item routerLink="#">Struts</a> -->
        </mat-nav-list>
    </mat-expansion-panel>
    </mat-nav-list>
  </mat-sidenav>
  <mat-sidenav-content>
    <mat-toolbar color="primary">
      <button
        type="button"
        aria-label="Toggle sidenav"
        mat-icon-button
        (click)="drawer.toggle()"
        *ngIf="isHandset$ | async">
        <mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
      </button>
      <span>HUKUM</span>
    </mat-toolbar>
    <!-- Add Content Here -->
    <app-newsblock></app-newsblock>
  </mat-sidenav-content>
</mat-sidenav-container>

</code>```

I am using Angular Material <mat-checkbox> for checkbox. I am using its [checked] property tied to variable to update their checked status on action. I am using two bool variables selectAllFilter for select All checkbox and selectSingleFilter for all other sources. I am failing to handle second case as i have only variable used for multiple source's checkbox. I am thinking having a unique variable tied to [checked] for each source checkbox will make this problem easy to tackle but sources list size can dynamically changed and will cause issues if i hardcode and create so many variables.

Body:
I am working on a angular project in which user is able to see news from different news sources. I have created a navigation pane which shows all the news sources fetched with checkbox.Navigation bar.

Behavior i am trying to achieve is like this - Behavior i am trying to achieve

Navigation.component.ts

import { Component, OnInit } from '@angular/core';
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { Observable } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';
import { NewsfetchserviceService } from '../newsfetchservice.service';
import { NewsData } from '../NewsData';
@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html',
  styleUrls: ['./navigation.component.css']
})
export class NavigationComponent implements OnInit{

  sourcesList : NewsData[] = [];
  selectAllFilter = true;
  selectSingleFilter = true;

  ngOnInit(): void {
    this.showAllSources();
  }

  isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset)
    .pipe(
      map(result => result.matches),
      shareReplay()
    );

  constructor(private breakpointObserver: BreakpointObserver,private newsfetch: NewsfetchserviceService) {}

  showAllSources():void {
    this.sourcesList = this.newsfetch.allNews;
    /* this.newsfetch.getNews().subscribe(news => this.news = news); */
  }

  updateNewsList(source : NewsData):void{
    this.newsfetch.updateNewsBlock(source);
    this.selectAllFilter = false;
    this.checkboxBehaviour(2);
  }

  updateAllNewsList(source : NewsData[]):void{
    this.newsfetch.updateAllNewsBlock(source);
    this.checkboxBehaviour(1);
  }

  checkboxBehaviour(input : number):void{
    if(this.selectSingleFilter == false && this.selectAllFilter == false && input == 1)
    {
      this.selectSingleFilter = true;
      this.selectAllFilter = true;
    }else{
      this.selectSingleFilter = false;
      this.selectAllFilter = false;
    }

    if(input == 2)
    {
      this.selectSingleFilter = false;
      this.selectAllFilter = false;
    }

  }
}

Navigation.component.html

<mat-sidenav-container class="sidenav-container">
  <mat-sidenav #drawer class="sidenav" fixedInViewport
      [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'"
      [mode]="(isHandset$ | async) ? 'over' : 'side'"
      [opened]="(isHandset$ | async) === false">
    <mat-toolbar>Menu</mat-toolbar>
    <mat-nav-list>
      <mat-expansion-panel [class.mat-elevation-z0]="true">
        <mat-expansion-panel-header>
            All Sources
        </mat-expansion-panel-header>
        <mat-checkbox [checked]="selectAllFilter" (change)="updateAllNewsList(sourcesList)">Select All</mat-checkbox>
        <mat-nav-list *ngFor="let source of sourcesList">

            <mat-checkbox [checked]="selectSingleFilter" (change)="updateNewsList(source)">{{source.name}}</mat-checkbox>

        </mat-nav-list>
    </mat-expansion-panel>
    </mat-nav-list>
  </mat-sidenav>
  <mat-sidenav-content>
    <mat-toolbar color="primary">
      <button
        type="button"
        aria-label="Toggle sidenav"
        mat-icon-button
        (click)="drawer.toggle()"
        *ngIf="isHandset$ | async">
        <mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
      </button>
      HUKUM
    </mat-toolbar>

    <app-newsblock></app-newsblock>
  </mat-sidenav-content>
</mat-sidenav-container>

I am using Angular Material <mat-checkbox> for checkbox. I am using its [checked] property tied to variable to update their checked status on action. I am using two bool variables selectAllFilter for select All checkbox and selectSingleFilter for all other sources. I am failing to handle second case as i have only variable used for multiple source's checkbox. I am thinking having a unique variable tied to [checked] for each source checkbox will make this problem easy to tackle but sources list size can dynamically changed and will cause issues if i hardcode and create so many variables.


问:
How to save many-to-many related entities into context in ASP.NET Core from Angular framework?
My models in ASP.NET Core are:

```<code>public class Customer
{
    public long CustomerId { get; set; }
    public string CustomerName { get; set; }

    public virtual ICollection<Invoice> Invoices { get; set; }
}

public class Invoice
{
    public long InvoiceId { get; set; }
    public DateTime InvoiceDate { get; set; }
    public long InvoicePrice { get; set; }

    // Foreign key
    [Display(Name = "Customer")]
    public virtual long CustomerId { get; set; }
    [ForeignKey("CustomerId")]
    public virtual Customer Customer { get; set; }

    public virtual ICollection<InvoiceCommodity> InvoiceCommodities { get; set; }
}

public class Commodity
{
    public long CommodityId { get; set; }
    public string CommodityName { get; set; }

    public virtual ICollection<InvoiceCommodity> InvoiceCommodities { get; set; }
}

public class InvoiceCommodity
{
    public long InvoiceCommodityId { get; set;
    public long Tonnage { get; set; }
    public long SalesPrice { get; set; }

    public long InvoiceId { get; set; }
    public virtual Invoice Invoice { get; set; }

    public long CommodityId { get; set; }
    public virtual Commodity Commodity { get; set; }
}

public class InvoiceDto
{
    public long InvoiceId { get; set; }
    public DateTime InvoiceDate { get; set; }
    public long InvoicePrice { get; set; }

    // Foreign key
    [Display(Name = "Customer")]
    public virtual long CustomerId { get; set; }

    public virtual ICollection<Models.InvoiceCommodity> InvoiceCommodities { get; set; }
}
</code>```

The same as in Angular:

```<code>export class Customer {
  public customerId?: number;
  public customerName?: string;
  public invoices?: Invoice[];
}

export class Invoice {
  public invoiceId?: number;
  public invoiceDate?: Date;
  public invoicePrice?: number;
  public customerId?: number;
  public invoiceCommodities?: InvoiceCommodity[];
}

export class Commodity {
  public commodityId?: number;
  public commodityName?: string;
  public invoiceCommodities?: InvoiceCommodity[];
}

export class InvoiceCommodity {
  public invoiceCommodityId?: number;
  public tonnage?: number;
  public salesPrice?: number;
  public invoice?: Invoice;
  public commodity?: Commodity;
}
</code>```

The DbContext class is:

```<code>public class RepositoryContext : DbContext
{
    public RepositoryContext(DbContextOptions<RepositoryContext> options)
            : base(options) { }

    protected override void OnModelCreating (ModelBuilder modelBuilder)
    {
            modelBuilder.Entity<InvoiceCommodity>().HasKey(ic => new
            {
                ic.CommodityId, ic.InvoiceId
            });
            modelBuilder.Entity<InvoiceCommodity>()
                .HasOne(ic => ic.Invoice)
                .WithMany(i => i.InvoiceCommodities)
                .HasForeignKey(c => c.InvoiceId);
            modelBuilder.Entity<InvoiceCommodity>()
                .HasOne(c => c.Commodity)
                .WithMany(ct => ct.InvoiceCommodities)
                .HasForeignKey(c => c.CommodityId);
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Invoice> Invoices { get; set; }
        public DbSet<Commodity> Commodities { get; set; }
        public DbSet<InvoiceCommodity> InvoiceCommodities { get; set; }
        public DbSet<Customer> Customers { get; set; }
}
</code>```

The invoiceController action method to add new invoice is this (it should be noted that these actions have been implemented for InvoiceCommodity and Commodity as well):

```<code>[HttpPost("addInvoice")]
public async Task<IActionResult> CreateInvoice([FromBody] InvoiceDto invoice)
{
    try
    {
        if (invoice is null)
        {
            return BadRequest("Invoice object is null");
        }

        if (!ModelState.IsValid)
        {
            return BadRequest("Invalid model object");
        }

        var invoiceEntity = _mapper.Map<Invoice>(source:invoice);
        _repository.Invoice.CreatInvoice(invoiceEntity);
        await _repository.SaveAsync();

        var invoiceResult = _mapper.Map<InvoiceDto>(source:invoiceEntity);

        return Ok(invoiceResult);
    }
    catch
    {
        return StatusCode(500, "Internal server error");
    }
}
</code>```

Getting the customer invoices by customerId action method is:

```<code>[HttpGet("customer/{id}")]
public async Task<IActionResult> GetCustomerById([FromRoute] long id)
{
    try
    {
        var customer = await _repository.Customer.GetCustomerByIdAsync(id);

        if (customer is null)
        {
            return NotFound();
        }

        var customerResult = _mapper.Map<CustomerDto>(source:customer);

        return Ok(customerResult);
    }
    catch
    {
        return StatusCode(500, "Internal server error");
    }
}

//===================== GetCustomerByIdAsync method ========
public async Task<Models.Customer> GetCustomerByIdAsync(long id)
{
    var customerFound = await FindByCondition(customer => customer.CustomerId.Equals(id))
                .Include(c => c.Invoices)
                .ThenInclude(invoice => invoice.InvoiceCommodities)
                .ThenInclude(commodity => commodity.Commodity)
                .FirstOrDefaultAsync();

    if (customerFound != null)
    {
        if (customerFound.Invoices != null)
        {
            foreach (var invoice in customerFound.Invoices)
            {
                invoice.Customer = null;

                if (invoice.InvoiceCommodities != null)
                {
                    foreach (var commodity in invoice.InvoiceCommodities)
                    {
                        commodity.Invoice.Customer = null;
                    }
                }
            }
        }
    }

    return  customerFound;
}
</code>```

We already added the commodities through a client-side modal and they are gettable through Swagger as well as client-side action: from Swagger:

```<code>[
  {
    "commodityId": 1,
    "commodityName": "C1",
  },
  {
    "commodityId": 2,
    "commodityName": "C2",
  }
]
</code>```

On the other hand, Customers are already added. so far, now when we add new invoice for a given customer in client-side as follows:

```<code>addNewInvoice(): boolean {
    if(this.invoiceDetails.length != 0) {

      this.newInvoice = new Invoice();

      this.newInvoice.customerId = this.customerSpecs.customerId;
      this.newInvoice.invoiceDate = this.invoiceDateValue;
      this.newInvoice.invoicePrice = this.invoicePrice;

      this.invoiceDetails.forEach( ids => {

        this.newCommodity = new Commodity();
        this.newInvoiceCommodity = new InvoiceCommodity();

        this.newCommodity.commodityId = ids.commodityId;
        this.newCommodity.commodityName = ids.commodityName;

        this.newInvoiceCommodity.salesPrice = ids.salesPrice;
        this.newInvoiceCommodity.tonnage = ids.tonnage;

        this.newInvoiceCommodity.invoice = this.newInvoice;
        this.newInvoiceCommodity.commodity = this.newCommodity;
        this.invoiceCommodityService.addInvoiceCommodity(this.newInvoiceCommodity);

        this.newInvoice.invoiceCommodities?.push(this.newInvoiceCommodity);
      });

      this.invoicesService.addNewInvoice(this.newInvoice).subscribe( ct => {
      // adding newInvoice is successfully
        console.log(`added invoice id: ${ct.invoiceId}`); // 1
        console.log(`added invoice customer Id: ${ct.customerId}`); // 3
        console.log(`added invoice Date: ${ct.invoiceDate}`); // 2022 ...
        console.log(`added invoice price: ${ct.invoicePrice}`); // 1000$
      });
    }
    return false
  }
</code>```

The new Invoice is added successfully, but when we try to get invoice details of the customer, we see these data fetched by swagger, because in client-side show us no details for the invoice! even, when I try to get Invoice by id from Swagger, I faced error 500 (server error). also, to get invoiceCommodities themselves, Swagger gives me empty collection ([]).

```<code>{
    "customerId": 3,
    "customerName": "Mr X",
    "invoices": [
      {
        "invoiceId": 1,
        "invoiceDate": "2022-12-18T06:56:37.642",
        "invoicePrice": 1000,
        "invoiceCommodities": [],
        "customerId": 3,
        "customer": null
      }
    ],
  },
  // other customers list ...
</code>```

As you can see in addnewInvoice method, we Post each of the invoiceCommodity and then push them in the invoiceCommodities property of newInvoice and Post it at the end.

What action or async method should I write on the backend or frontend so that an Invoice create correctly for given customer and its details can be viewed on the frontend?

This issue has become a big problem for me and I did a lot of research, but unfortunately I did not find a suitable solution. Please provide a suitable solution for this problem.

Body:
My models in ASP.NET Core are:

public class Customer
{
    public long CustomerId { get; set; }
    public string CustomerName { get; set; }

    public virtual ICollection<Invoice> Invoices { get; set; }
}

public class Invoice
{
    public long InvoiceId { get; set; }
    public DateTime InvoiceDate { get; set; }
    public long InvoicePrice { get; set; }

    // Foreign key
    [Display(Name = "Customer")]
    public virtual long CustomerId { get; set; }
    [ForeignKey("CustomerId")]
    public virtual Customer Customer { get; set; }

    public virtual ICollection<InvoiceCommodity> InvoiceCommodities { get; set; }
}

public class Commodity
{
    public long CommodityId { get; set; }
    public string CommodityName { get; set; }

    public virtual ICollection<InvoiceCommodity> InvoiceCommodities { get; set; }
}

public class InvoiceCommodity
{
    public long InvoiceCommodityId { get; set;
    public long Tonnage { get; set; }
    public long SalesPrice { get; set; }

    public long InvoiceId { get; set; }
    public virtual Invoice Invoice { get; set; }

    public long CommodityId { get; set; }
    public virtual Commodity Commodity { get; set; }
}

public class InvoiceDto
{
    public long InvoiceId { get; set; }
    public DateTime InvoiceDate { get; set; }
    public long InvoicePrice { get; set; }

    // Foreign key
    [Display(Name = "Customer")]
    public virtual long CustomerId { get; set; }

    public virtual ICollection<Models.InvoiceCommodity> InvoiceCommodities { get; set; }
}

The same as in Angular:

export class Customer {
  public customerId?: number;
  public customerName?: string;
  public invoices?: Invoice[];
}

export class Invoice {
  public invoiceId?: number;
  public invoiceDate?: Date;
  public invoicePrice?: number;
  public customerId?: number;
  public invoiceCommodities?: InvoiceCommodity[];
}

export class Commodity {
  public commodityId?: number;
  public commodityName?: string;
  public invoiceCommodities?: InvoiceCommodity[];
}

export class InvoiceCommodity {
  public invoiceCommodityId?: number;
  public tonnage?: number;
  public salesPrice?: number;
  public invoice?: Invoice;
  public commodity?: Commodity;
}

The DbContext class is:

public class RepositoryContext : DbContext
{
    public RepositoryContext(DbContextOptions<RepositoryContext> options)
            : base(options) { }

    protected override void OnModelCreating (ModelBuilder modelBuilder)
    {
            modelBuilder.Entity<InvoiceCommodity>().HasKey(ic => new
            {
                ic.CommodityId, ic.InvoiceId
            });
            modelBuilder.Entity<InvoiceCommodity>()
                .HasOne(ic => ic.Invoice)
                .WithMany(i => i.InvoiceCommodities)
                .HasForeignKey(c => c.InvoiceId);
            modelBuilder.Entity<InvoiceCommodity>()
                .HasOne(c => c.Commodity)
                .WithMany(ct => ct.InvoiceCommodities)
                .HasForeignKey(c => c.CommodityId);
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Invoice> Invoices { get; set; }
        public DbSet<Commodity> Commodities { get; set; }
        public DbSet<InvoiceCommodity> InvoiceCommodities { get; set; }
        public DbSet<Customer> Customers { get; set; }
}

The invoiceController action method to add new invoice is this (it should be noted that these actions have been implemented for InvoiceCommodity and Commodity as well):

[HttpPost("addInvoice")]
public async Task<IActionResult> CreateInvoice([FromBody] InvoiceDto invoice)
{
    try
    {
        if (invoice is null)
        {
            return BadRequest("Invoice object is null");
        }

        if (!ModelState.IsValid)
        {
            return BadRequest("Invalid model object");
        }

        var invoiceEntity = _mapper.Map<Invoice>(source:invoice);
        _repository.Invoice.CreatInvoice(invoiceEntity);
        await _repository.SaveAsync();

        var invoiceResult = _mapper.Map<InvoiceDto>(source:invoiceEntity);

        return Ok(invoiceResult);
    }
    catch
    {
        return StatusCode(500, "Internal server error");
    }
}

Getting the customer invoices by customerId action method is:

[HttpGet("customer/{id}")]
public async Task<IActionResult> GetCustomerById([FromRoute] long id)
{
    try
    {
        var customer = await _repository.Customer.GetCustomerByIdAsync(id);

        if (customer is null)
        {
            return NotFound();
        }

        var customerResult = _mapper.Map<CustomerDto>(source:customer);

        return Ok(customerResult);
    }
    catch
    {
        return StatusCode(500, "Internal server error");
    }
}

//===================== GetCustomerByIdAsync method ========
public async Task<Models.Customer> GetCustomerByIdAsync(long id)
{
    var customerFound = await FindByCondition(customer => customer.CustomerId.Equals(id))
                .Include(c => c.Invoices)
                .ThenInclude(invoice => invoice.InvoiceCommodities)
                .ThenInclude(commodity => commodity.Commodity)
                .FirstOrDefaultAsync();

    if (customerFound != null)
    {
        if (customerFound.Invoices != null)
        {
            foreach (var invoice in customerFound.Invoices)
            {
                invoice.Customer = null;

                if (invoice.InvoiceCommodities != null)
                {
                    foreach (var commodity in invoice.InvoiceCommodities)
                    {
                        commodity.Invoice.Customer = null;
                    }
                }
            }
        }
    }

    return  customerFound;
}

We already added the commodities through a client-side modal and they are gettable through Swagger as well as client-side action: from Swagger:

[
  {
    "commodityId": 1,
    "commodityName": "C1",
  },
  {
    "commodityId": 2,
    "commodityName": "C2",
  }
]

On the other hand, Customers are already added. so far, now when we add new invoice for a given customer in client-side as follows:

addNewInvoice(): boolean {
    if(this.invoiceDetails.length != 0) {

      this.newInvoice = new Invoice();

      this.newInvoice.customerId = this.customerSpecs.customerId;
      this.newInvoice.invoiceDate = this.invoiceDateValue;
      this.newInvoice.invoicePrice = this.invoicePrice;

      this.invoiceDetails.forEach( ids => {

        this.newCommodity = new Commodity();
        this.newInvoiceCommodity = new InvoiceCommodity();

        this.newCommodity.commodityId = ids.commodityId;
        this.newCommodity.commodityName = ids.commodityName;

        this.newInvoiceCommodity.salesPrice = ids.salesPrice;
        this.newInvoiceCommodity.tonnage = ids.tonnage;

        this.newInvoiceCommodity.invoice = this.newInvoice;
        this.newInvoiceCommodity.commodity = this.newCommodity;
        this.invoiceCommodityService.addInvoiceCommodity(this.newInvoiceCommodity);

        this.newInvoice.invoiceCommodities?.push(this.newInvoiceCommodity);
      });

      this.invoicesService.addNewInvoice(this.newInvoice).subscribe( ct => {
      // adding newInvoice is successfully
        console.log(`added invoice id: ${ct.invoiceId}`); // 1
        console.log(`added invoice customer Id: ${ct.customerId}`); // 3
        console.log(`added invoice Date: ${ct.invoiceDate}`); // 2022 ...
        console.log(`added invoice price: ${ct.invoicePrice}`); // 1000$
      });
    }
    return false
  }

The new Invoice is added successfully, but when we try to get invoice details of the customer, we see these data fetched by swagger, because in client-side show us no details for the invoice! even, when I try to get Invoice by id from Swagger, I faced error 500 (server error). also, to get invoiceCommodities themselves, Swagger gives me empty collection ([]).

{
    "customerId": 3,
    "customerName": "Mr X",
    "invoices": [
      {
        "invoiceId": 1,
        "invoiceDate": "2022-12-18T06:56:37.642",
        "invoicePrice": 1000,
        "invoiceCommodities": [],
        "customerId": 3,
        "customer": null
      }
    ],
  },
  // other customers list ...

As you can see in addnewInvoice method, we Post each of the invoiceCommodity and then push them in the invoiceCommodities property of newInvoice and Post it at the end.

What action or async method should I write on the backend or frontend so that an Invoice create correctly for given customer and its details can be viewed on the frontend?

This issue has become a big problem for me and I did a lot of research, but unfortunately I did not find a suitable solution. Please provide a suitable solution for this problem.


问:
How can I map moving objects using program using signal identifiers on a longitude/latitude?
I need to achieve an network based mapping program using signal identifiers to map location of moving objects. Map of physical long/lat.</p>


问:
How to get and display data on HTML when using Spring Json
I'm using Spring to get json data, and then i want to display data on HTML page.

This is my class:

```<code>  @RequestMapping(value = "/selectCountNotification.do")
  public ResponseEntity<List<EgovMap>> selectCountNotification(@RequestParam Map<String, Object> params, ModelMap model) throws Exception {

    System.out.println("########################################");
    System.out.println("####################check log####################");
    System.out.println("########################################");

    List<EgovMap> countNotification = orderDetailService.selectCountNotification(params);

    model.addAttribute("countNotification", countNotification);

    return ResponseEntity.ok(countNotification);
  }
</code>```

This is my header.jsp

```<code>    <li>
       <div class="notification" style="top: -5px;left: -40px;height: 36px;">
            <i class='far fa-bell' style='font-size:20px'>
                <div id="not">
                    <%@ include file="/WEB-INF/jsp/sales/order/countNotify.jsp"%>
                </div>
            </i>
       </div>
    </li>
</code>```

this is my countNotify.jsp

```<code><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<p>data: </p>
<c:forEach items="${countNotification}" var="comm">
    <p><c:out value="${comm.countNotify}"/></p>
</c:forEach>
</code>```

when i call by url:

```<code>http://localhost:8080/sales/order/selectCountNotification.do
</code>```

I get data value from my database following as:

```<code>12
</code>```

but when i run my jsp is countNotify.jsp, it cannot get any value, So how i can fix the problem ?

Body:
I'm using Spring to get json data, and then i want to display data on HTML page.

This is my class:

  @RequestMapping(value = "/selectCountNotification.do")
  public ResponseEntity<List<EgovMap>> selectCountNotification(@RequestParam Map<String, Object> params, ModelMap model) throws Exception {

    System.out.println("########################################");
    System.out.println("####################check log####################");
    System.out.println("########################################");

    List<EgovMap> countNotification = orderDetailService.selectCountNotification(params);

    model.addAttribute("countNotification", countNotification);

    return ResponseEntity.ok(countNotification);
  }

This is my header.jsp

                    <%@ include file="/WEB-INF/jsp/sales/order/countNotify.jsp"%>

this is my countNotify.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

data:

<c:forEach items="${countNotification}" var="comm">

<c:out value="${comm.countNotify}"/>

</c:forEach>

when i call by url:

http://localhost:8080/sales/order/selectCountNotification.do

I get data value from my database following as:

12

but when i run my jsp is countNotify.jsp, it cannot get any value, So how i can fix the problem ?


问:
Enable SSO with External IDp for web application deployed on GKE
I want to enable SSO with External IDp for an application deployed on GKE and restricting access to only user part os a specific google group/ Gsuit group

I have gone through lot of online reference and got confused with different option , Understanding I have developed till now is one option is to use google identity platform with SAML and also have to configure my application front end with SAML but couldn't find specific steps or if any better options.
Also I want to restrict access to user part of specific google group/gsuit group


问:
emacs tree-sitter doesn't highlight my *.ts Typescript files
I'm new in the emacs world and after practicing a bit with doomemacs, I'm trying to configure vanilla emacs by myself with my own init.el file.

I have installer tree-sitter for syntax highlighting and works fine for JS file but not for TS files. My configuration for tree-sitter is the next:

```<code>(use-package tree-sitter
  :ensure t
  :config
  (global-tree-sitter-mode)
  (add-hook 'tree-sitter-after-on-hook #'tree-sitter-hl-mode))

(use-package tree-sitter-langs
  :ensure t
  :after tree-sitter)
</code>```

Anyone has the same problem? or I'm missing something in my configuration? Thanks!

Body:
I'm new in the emacs world and after practicing a bit with doomemacs, I'm trying to configure vanilla emacs by myself with my own init.el file.

I have installer tree-sitter for syntax highlighting and works fine for JS file but not for TS files. My configuration for tree-sitter is the next:

(use-package tree-sitter
  :ensure t
  :config
  (global-tree-sitter-mode)
  (add-hook 'tree-sitter-after-on-hook #'tree-sitter-hl-mode))

(use-package tree-sitter-langs
  :ensure t
  :after tree-sitter)

Anyone has the same problem? or I'm missing something in my configuration? Thanks!


问:
How To Use Emit in Vue.Js?
In this code, I use Random Axios Data in getMembers function.
I wonder if I use the same Data in getMember. As far as I know in this case I can use this.$emit
but I have no idea how to use this.

I want to get exact data in getMember(idx)

```<code> methods: {
    getMembers() {
      var vm = this;
      this.axios.get('https://randomuser.me/api/?results=5')
        .then(res => {
          vm.members = res.data.results;
          console.log(vm.members);
        })
        .catch(error => {
          console.log(error);
        })
    },
    getMember(idx) {
      this.modal = true;
      var vm = this;
      console.log(idx);
      this.axios.get('https://randomuser.me/api/')
        .then(res => {
          vm.member = res.data.results;
          console.log(vm.member);
        })
        .catch(error => {
          console.log(error);
        })
    },
  },
};
</code>```

Title: How To Use Emit in Vue.Js?

Body:
In this code, I use Random Axios Data in getMembers function.
I wonder if I use the same Data in getMember. As far as I know in this case I can use this.$emit
but I have no idea how to use this.

I want to get exact data in getMember(idx)

 methods: {
    getMembers() {
      var vm = this;
      this.axios.get('https://randomuser.me/api/?results=5')
        .then(res => {
          vm.members = res.data.results;
          console.log(vm.members);
        })
        .catch(error => {
          console.log(error);
        })
    },
    getMember(idx) {
      this.modal = true;
      var vm = this;
      console.log(idx);
      this.axios.get('https://randomuser.me/api/')
        .then(res => {
          vm.member = res.data.results;
          console.log(vm.member);
        })
        .catch(error => {
          console.log(error);
        })
    },
  },
};


问:
Dual Row under the clock statusbar
I just want add day, day and month under the clock statusbar only, that is someone know how to make it on android?BTW, i am using Miui 13 android 12, you can see the picture have i include here enter image description here

I try by myself and got blank

Title: Dual Row under the clock statusbar


问:
Unauthorized Error - Connect to Config Server
We are migrating our Spring Boot application to 2.7.5 version, as part of this migration we upgraded our cloud service dependencies (BOM) to

org.springframework.cloud:spring-cloud-dependencies:2021.0.5
io.pivotal.spring.cloud:spring-cloud-services-dependencies:3.5.2

Our Config Server related depencies are as follows

implementation 'org.springframework.cloud:spring-cloud-starter-config'

implementation 'io.pivotal.spring.cloud:spring-cloud-services-starter-config-client'

With these dependencies when we deploy our application in PCF, the application is not able to connect to the Config Server and read the properties, it is always falling back to our default application.properties in the source folder, below is the error we see,

c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: 401 Unauthorized: [no body]

When we downgrade our cloud service dependencies (BOM) to

org.springframework.cloud:spring-cloud-dependencies:2021.0.5
io.pivotal.spring.cloud:spring-cloud-services-dependencies:3.1.8.RELEASE

things start to work normally without any issues. Is there anything that we are missing here? Please validate.


问:
amazon-ecs-deploy-task-definition not creating service - Error : "Service is INACTIVE"
I'm trying to deploy a dotnet service to a cluster in ECS using a git action on a pull request.

Everything works fine up to the aws-actions/amazon-ecs-deploy-task-definition@v1 step which fails giving an error of "Service is INACTIVE".

In this case there is no running service attached to the task definition.  If I create the service manually it runs fine and any subsequent deployments work, but if the service has been deleted the amazon-ecs-deploy-task-definition step appears unable to recreate the service and start it.

Any idea how I can force it to create the service and start it?


问:
How to redirect back to the single post based on the id of that post after deleting a comment
I am having an issue trying to go back to that specific page with a dynamic id. In this example, the id is 218 passed into a variable. I tried using the url encode method but it isn't still working

I have attached some screenshots about the page enter image description here

Here is the error I get because it does not display any id after hitting the delete button, However, the review gets deleted, but the page is not redirected to the specific post enter image description here

```<code>    <a href="single-property1.php?delete=<?php echo $review_id; ?>" class="mb-0 text-heading border-left border-dark hover-primary lh-1 ml-2 pl-2"><?php echo $list_id?> Delete</a>
// I had to echo the $list_id to check if i could get the value, I kept getting the value as seen in the picture which is 218, but it doesnt output anything in the headers

  // To delete
                    if (isset($_GET['delete'])) {
                        $delete_post_id = $_GET['delete'];
                        $query = "DELETE FROM reviews WHERE review_id = {$delete_post_id}";
                        $delete_query = mysqli_query($connection, $query);
                        // to check if that connection exists
                        if (!$connection) {
                            die("QUERY FAILED" . mysqli_error($connection));
                        } else {
                        header("location: single-property1.php?p_id=".urlencode($list_id));
                        }
                    }
                  ?>

//the variable $list_id is what holds the id of the post, but when redirected, I am unable to get the id value
</code>```

Body:
I am having an issue trying to go back to that specific page with a dynamic id. In this example, the id is 218 passed into a variable. I tried using the url encode method but it isn't still working

I have attached some screenshots about the page enter image description here

Here is the error I get because it does not display any id after hitting the delete button, However, the review gets deleted, but the page is not redirected to the specific post enter image description here

    <a href="single-property1.php?delete=<?php echo $review_id; ?>" class="mb-0 text-heading border-left border-dark hover-primary lh-1 ml-2 pl-2"><?php echo $list_id?> Delete
// I had to echo the $list_id to check if i could get the value, I kept getting the value as seen in the picture which is 218, but it doesnt output anything in the headers

  // To delete
                    if (isset($_GET['delete'])) {
                        $delete_post_id = $_GET['delete'];
                        $query = "DELETE FROM reviews WHERE review_id = {$delete_post_id}";
                        $delete_query = mysqli_query($connection, $query);
                        // to check if that connection exists
                        if (!$connection) {
                            die("QUERY FAILED" . mysqli_error($connection));
                        } else {
                        header("location: single-property1.php?p_id=".urlencode($list_id));
                        }
                    }
                  ?>

//the variable $list_id is what holds the id of the post, but when redirected, I am unable to get the id value


问:
Transposing and stacking data in R under unique IDs
Thank you Andrew James. Your advice was insightful!

I would like to transform my data from 'DATASET A' to 'DATASET B', using R.

```<code>        DATASET A
</code>```

country name
Series Code
2011
2014
2017
2022

AFG
ACTD
9.01
9.96
14.9
9.65

ALB
ACTD
28.3
37.9
40.2
44.2

AFG
FINTD
4.71
1.66
2.72
2.6

ALB
21.1
23.4
21.8
26.9
26.9

```<code>      DATASET B
</code>```

country name
Year
ACTD
FINTD

AFG
2011
9.01
4.71

AFG
2014
9.96
1.66

AFG
2017
14.9
2.72

AFG
2021
9.65
2.6

ALB
2011
28.3
23.4

ALB
2014
37.9
21.8

ALB
2017
40.2
26.9

ALB
2021
44.2
26.9

I have tried the following codes on my dataset named 'findat' and its transpose 'findat_t' but couldn't get results:

findat<-cbind(findat_t[1:2], stack(findat[3:6]))

findat_t<-cbind(findat_t[1:2], stack(findat_t[3:6]))

library(data.table)
dcast(data=setDT(findat),formula=ID~Series.Code, value.var="c(2011":"2021")
findat

Body:
Thank you Andrew James. Your advice was insightful!

I would like to transform my data from 'DATASET A' to 'DATASET B', using R.

        DATASET A

country name
Series Code
2011
2014
2017
2022

AFG
ACTD
9.01
9.96
14.9
9.65

ALB
ACTD
28.3
37.9
40.2
44.2

AFG
FINTD
4.71
1.66
2.72
2.6

ALB
21.1
23.4
21.8
26.9
26.9

      DATASET B

country name
Year
ACTD
FINTD

AFG
2011
9.01
4.71

AFG
2014
9.96
1.66

AFG
2017
14.9
2.72

AFG
2021
9.65
2.6

ALB
2011
28.3
23.4

ALB
2014
37.9
21.8

ALB
2017
40.2
26.9

ALB
2021
44.2
26.9

I have tried the following codes on my dataset named 'findat' and its transpose 'findat_t' but couldn't get results:

findat<-cbind(findat_t[1:2], stack(findat[3:6]))

findat_t<-cbind(findat_t[1:2], stack(findat_t[3:6]))

library(data.table)
dcast(data=setDT(findat),formula=ID~Series.Code, value.var="c(2011":"2021")
findat


问:
Why i had different results with same data but different order
im trying to find the most calibrated model using Logistic Regression for a binary question and using log loss/brier score to know what is the best, but i want to know what im doing wrong with my model, when i put the same variables X in different order i had different result

this is my code

X = df[['casaexp','k5m','side','d5m','g5']]
y = df.victory

```<code>train_perc = 0.4
val_perc = 0.3
test_perc = 0.3
rs = 1234

X_train_val, X_test, y_train_val, y_test = train_test_split(X, y, test_size=test_perc, random_state=rs)

X_train, X_val, y_train, y_val = train_test_split(X_train_val, y_train_val, test_size=val_perc, random_state=rs,stratify=y_train_val)

def shuffle_data(data, n):
    return np.hstack((data[:,n:], data[:,:n]))
</code>```

lgbm_clf = LogisticRegression(penalty='none', random_state=1234)
lgbm_clf.fit(X_train, y_train)

preds_uncalibrated_test = lgbm_clf.predict_proba(X_test)[:,1]

print('Uncalibrated log_loss = {}'.format(log_loss(y_test, preds_uncalibrated_test)))
print('Uncalibrated ROC_AUC = {}'.format(roc_auc_score(y_test, preds_uncalibrated_test)))
print(f"Uncalibrated F1 on the test set: {f1_score(y_test, lgbm_clf.predict(X_test)):.5f}")
print('Uncalibrated brier_score_loss = {}'.format(brier_score_loss(y_test, preds_uncalibrated_test)))
accuracy = accuracy_score(y_test, lgbm_clf.predict(X_test))
print(' %0.4f accuracy.' % accuracy)

and this is my result

```<code>Uncalibrated log_loss = 0.5660449696**400124**
Uncalibrated ROC_AUC = 0.7710594315245478
Uncalibrated F1 on the test set: 0.69663
Uncalibrated brier_score_loss = 0.19366689455**770922**
 0.6932 accuracy.
</code>```

but if i change the order i had a little bit different result

X = df[['k5m','side','d5m','casaexp','g5']]
y = df.victory

```<code>Uncalibrated log_loss = 0.5660449696**409053**
Uncalibrated ROC_AUC = 0.7710594315245478
Uncalibrated F1 on the test set: 0.69663
Uncalibrated brier_score_loss = 0.19366689455**804897**
 0.6932 accuracy.
</code>```

using the same code but with different order in variables on X, why this happen and what i need to do to stop doing this?

i tried to use random state and i tried to remove train/test training but still happen the same "error" and i want to do the same result even with different order

Body:
im trying to find the most calibrated model using Logistic Regression for a binary question and using log loss/brier score to know what is the best, but i want to know what im doing wrong with my model, when i put the same variables X in different order i had different result

this is my code

X = df[['casaexp','k5m','side','d5m','g5']]
y = df.victory

train_perc = 0.4
val_perc = 0.3
test_perc = 0.3
rs = 1234

X_train_val, X_test, y_train_val, y_test = train_test_split(X, y, test_size=test_perc, random_state=rs)

X_train, X_val, y_train, y_val = train_test_split(X_train_val, y_train_val, test_size=val_perc, random_state=rs,stratify=y_train_val)

def shuffle_data(data, n):
    return np.hstack((data[:,n:], data[:,:n]))

lgbm_clf = LogisticRegression(penalty='none', random_state=1234)
lgbm_clf.fit(X_train, y_train)

preds_uncalibrated_test = lgbm_clf.predict_proba(X_test)[:,1]

print('Uncalibrated log_loss = {}'.format(log_loss(y_test, preds_uncalibrated_test)))
print('Uncalibrated ROC_AUC = {}'.format(roc_auc_score(y_test, preds_uncalibrated_test)))
print(f"Uncalibrated F1 on the test set: {f1_score(y_test, lgbm_clf.predict(X_test)):.5f}")
print('Uncalibrated brier_score_loss = {}'.format(brier_score_loss(y_test, preds_uncalibrated_test)))
accuracy = accuracy_score(y_test, lgbm_clf.predict(X_test))
print(' %0.4f accuracy.' % accuracy)

and this is my result

Uncalibrated log_loss = 0.5660449696**400124**
Uncalibrated ROC_AUC = 0.7710594315245478
Uncalibrated F1 on the test set: 0.69663
Uncalibrated brier_score_loss = 0.19366689455**770922**
 0.6932 accuracy.

but if i change the order i had a little bit different result

X = df[['k5m','side','d5m','casaexp','g5']]
y = df.victory

Uncalibrated log_loss = 0.5660449696**409053**
Uncalibrated ROC_AUC = 0.7710594315245478
Uncalibrated F1 on the test set: 0.69663
Uncalibrated brier_score_loss = 0.19366689455**804897**
 0.6932 accuracy.

using the same code but with different order in variables on X, why this happen and what i need to do to stop doing this?

i tried to use random state and i tried to remove train/test training but still happen the same "error" and i want to do the same result even with different order


问:
graph shows up blank when trying to filter data out from variable on rmarkdown
Having these packages already loaded:

```<code>library(unvotes)
library(dplyr)
library(tidyr)
library(readr)
library(ggplot2)
library(stringr)
library(readxl)
library(countrycode)
</code>```

And this previous code actually working:

```<code>DDdata <- read_xls("dd.xls") %>%
  filter(year > 1945) %>%
  mutate(iso2c = countrycode(uncode, "un", "iso2c")) %>%
  select(iso2c, country = ctryname, year, democracy, un_continent_name)
</code>```
```<code>un_year_mean <- un_roll_calls %>%
  separate(date, "year", extra = "drop") %>%
  inner_join(un_votes) %>%
  mutate(year = as.numeric(year),
         vote = if_else(vote == "yes", 1, 0)) %>%
  group_by(year, country, country_code) %>%
  summarize(mean = mean(vote))
</code>```
```<code>un_dd_year <- un_year_mean %>%
  inner_join(DDdata, by = c("country_code" = "iso2c", "year" = "year")) %>%
  select(country = country.x, country_code, year, mean, democracy,
         continent = un_continent_name) %>%
  mutate(democracy = if_else(democracy == 1, "Democracy", "No democracy"))
</code>```

I am trying to create this jitter points graph, however although no error text pops up there is definetly an issue with the filter since the graph shows up blank when i try to filter data out for years 2007 and 2008.

```<code>un_dd_year %>%
filter(year == 2007 & year == 2008) %>%
ggplot(aes(x = democracy, y = mean)) +
geom_jitter(aes(col = continent), alpha = 0.3, width = 0.3) +
stat_summary(fun.data = mean_se,
fun.args = list(mult = 1.96),
size = 0.5,
col = "dark blue") +
scale_color_brewer(type = "qual", palette = 6) +
theme_test()
</code>```

Body:
Having these packages already loaded:

library(unvotes)
library(dplyr)
library(tidyr)
library(readr)
library(ggplot2)
library(stringr)
library(readxl)
library(countrycode)

And this previous code actually working:

DDdata <- read_xls("dd.xls") %>%
  filter(year > 1945) %>%
  mutate(iso2c = countrycode(uncode, "un", "iso2c")) %>%
  select(iso2c, country = ctryname, year, democracy, un_continent_name)

un_year_mean <- un_roll_calls %>%
  separate(date, "year", extra = "drop") %>%
  inner_join(un_votes) %>%
  mutate(year = as.numeric(year),
         vote = if_else(vote == "yes", 1, 0)) %>%
  group_by(year, country, country_code) %>%
  summarize(mean = mean(vote))

un_dd_year <- un_year_mean %>%
  inner_join(DDdata, by = c("country_code" = "iso2c", "year" = "year")) %>%
  select(country = country.x, country_code, year, mean, democracy,
         continent = un_continent_name) %>%
  mutate(democracy = if_else(democracy == 1, "Democracy", "No democracy"))

I am trying to create this jitter points graph, however although no error text pops up there is definetly an issue with the filter since the graph shows up blank when i try to filter data out for years 2007 and 2008.

un_dd_year %>%
filter(year == 2007 & year == 2008) %>%
ggplot(aes(x = democracy, y = mean)) +
geom_jitter(aes(col = continent), alpha = 0.3, width = 0.3) +
stat_summary(fun.data = mean_se,
fun.args = list(mult = 1.96),
size = 0.5,
col = "dark blue") +
scale_color_brewer(type = "qual", palette = 6) +
theme_test()


问:
Unable to create a sketch plugin due to terminal errors
**I see the error below when I use the command npm run start **

```<code>node:internal/crypto/hash:71
  this[kHandle] = new _Hash(algorithm, xofLen);
                  ^

Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:71:19)
    at Object.createHash (node:crypto:133:10)
    at module.exports (/Users/pavannandan/Desktop/Angle/node_modules/webpack/lib/util/createHash.js:135:53)
    at NormalModule._initBuildHash (/Users/pavannandan/Desktop/Angle/node_modules/webpack/lib/NormalModule.js:417:16)
    at handleParseError (/Users/pavannandan/Desktop/Angle/node_modules/webpack/lib/NormalModule.js:471:10)
    at /Users/pavannandan/Desktop/Angle/node_modules/webpack/lib/NormalModule.js:503:5
    at /Users/pavannandan/Desktop/Angle/node_modules/webpack/lib/NormalModule.js:358:12
    at /Users/pavannandan/Desktop/Angle/node_modules/loader-runner/lib/LoaderRunner.js:373:3
    at iterateNormalLoaders (/Users/pavannandan/Desktop/Angle/node_modules/loader-runner/lib/LoaderRunner.js:214:10)
    at iterateNormalLoaders (/Users/pavannandan/Desktop/Angle/node_modules/loader-runner/lib/LoaderRunner.js:221:10)
    at /Users/pavannandan/Desktop/Angle/node_modules/loader-runner/lib/LoaderRunner.js:236:3
    at context.callback (/Users/pavannandan/Desktop/Angle/node_modules/loader-runner/lib/LoaderRunner.js:111:13)
    at /Users/pavannandan/Desktop/Angle/node_modules/babel-loader/lib/index.js:44:71 {
  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}

Node.js v18.12.1
</code>```

Tried quick troubleshooting but still see the same error.

Body:
**I see the error below when I use the command npm run start **

node:internal/crypto/hash:71
  this[kHandle] = new _Hash(algorithm, xofLen);
                  ^

Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:71:19)
    at Object.createHash (node:crypto:133:10)
    at module.exports (/Users/pavannandan/Desktop/Angle/node_modules/webpack/lib/util/createHash.js:135:53)
    at NormalModule._initBuildHash (/Users/pavannandan/Desktop/Angle/node_modules/webpack/lib/NormalModule.js:417:16)
    at handleParseError (/Users/pavannandan/Desktop/Angle/node_modules/webpack/lib/NormalModule.js:471:10)
    at /Users/pavannandan/Desktop/Angle/node_modules/webpack/lib/NormalModule.js:503:5
    at /Users/pavannandan/Desktop/Angle/node_modules/webpack/lib/NormalModule.js:358:12
    at /Users/pavannandan/Desktop/Angle/node_modules/loader-runner/lib/LoaderRunner.js:373:3
    at iterateNormalLoaders (/Users/pavannandan/Desktop/Angle/node_modules/loader-runner/lib/LoaderRunner.js:214:10)
    at iterateNormalLoaders (/Users/pavannandan/Desktop/Angle/node_modules/loader-runner/lib/LoaderRunner.js:221:10)
    at /Users/pavannandan/Desktop/Angle/node_modules/loader-runner/lib/LoaderRunner.js:236:3
    at context.callback (/Users/pavannandan/Desktop/Angle/node_modules/loader-runner/lib/LoaderRunner.js:111:13)
    at /Users/pavannandan/Desktop/Angle/node_modules/babel-loader/lib/index.js:44:71 {
  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}

Node.js v18.12.1

Tried quick troubleshooting but still see the same error.


问:
JQL (JIRA): How to trigger a webhook event for *anything* changed in an issue
I created a webhook for "Jira / Microsoft Teams" integration.

We need to get updates on anything happening on "bug" issues (creation, updates) into a Teams channel.

We created this JQL:

project = General AND issuetype = bug AND status changed

But this is just for the status and does not support anything else (creation, updates in other fields etc.)

Unfortunately I cannot use the checkbox options either because I have no way to choose the equivalent of issuetype = bug there.

I assume that the only way is JQL but I cannot find a way to describe "report all changes in the bug", plus I did not see it working even for the status change I reported above.

Is there a solution to this?

Thank you.

UPDATE: If I combine both like that, it seems to partially work. Partially because changes in the Description are not triggered, etc. How can these be triggered too? (i.e. EDITS in Description, etc.).


问:
Use INVALID_HANDLE_VALUE as a compile-time constant
INVALID_HANDLE_VALUE is defined in WinAPI as follows:

```<code>#define INVALID_HANDLE_VALUE ((HANDLE)(LONG_PTR)-1)
</code>```

On my system that results in:

```<code>#define INVALID_HANDLE_VALUE ((void*)(long long)-1)
</code>```

So I can't use this as a constexpr:

constexpr auto c = INVALID_HANDLE_VALUE gives me an error:

cast that performs the conversions of a reinterpret_cast is not allowed in a constant expression

Of course I can use directly -1 as a value, but is there a way to lean on constant from WinAPI?

The actual code I'm trying to port to different compilers was something with non-type template parameter like this:

```<code>#define INVALID_HANDLE_VALUE ((void*)(long long)-1)

template <void* value>
class C{};

C<INVALID_HANDLE_VALUE> c;
</code>```

This gives me error on clang trunk and gcc 12.2, but compiled well on msvc19 latest and clang 15 (link to godbolt).

Error message for clang says about "constant expression":

error: non-type template argument is not a constant expression

I used std::intptr_t now instead of void* as a template parameter, but maybe there some other solutions.

Body:
INVALID_HANDLE_VALUE is defined in WinAPI as follows:

#define INVALID_HANDLE_VALUE ((HANDLE)(LONG_PTR)-1)

On my system that results in:

#define INVALID_HANDLE_VALUE ((void*)(long long)-1)

So I can't use this as a constexpr:

constexpr auto c = INVALID_HANDLE_VALUE gives me an error:

cast that performs the conversions of a reinterpret_cast is not allowed in a constant expression

Of course I can use directly -1 as a value, but is there a way to lean on constant from WinAPI?

The actual code I'm trying to port to different compilers was something with non-type template parameter like this:

#define INVALID_HANDLE_VALUE ((void*)(long long)-1)

template <void* value>
class C{};

C<INVALID_HANDLE_VALUE> c;

This gives me error on clang trunk and gcc 12.2, but compiled well on msvc19 latest and clang 15 (link to godbolt).

Error message for clang says about "constant expression":

error: non-type template argument is not a constant expression

I used std::intptr_t now instead of void* as a template parameter, but maybe there some other solutions.