问:
How to implement group by with sum of multiple fields in java
Controller class:

```<code>@RestController
@RequestMapping(value = "/api/v1/")
public class TestController {

@Autowired
TestService testService;

@GetMapping(value = "test")
public List<Bean> getDetails() {
return testService.getDetails();
}
}
</code>```

Service class:

```<code>@Service
public class TestService {

@Autowired
BeanRepository beanRepository;

public List<Bean> getDetails() {
List<Bean> res = new ArrayList<>();
try{
List<BeanEntity> beans = beanRepository.findAllApplications();
for(BeanEntity beanEntity : beans) {
Bean bean = new Bean();
BeanUtils.copyProperties(beanEntity, bean);
if(beanEntity.getDesc().contains("Motor") || beanEntity.getDesc().contains("Nut")){
bean.setName("A");
} else if (beanEntity.getDesc().contains("Bolt") || beanEntity.getDesc().contains("Engine")) {
bean.setName("B");
} else {
bean.setName("C");
}
res.add()
}
} catch(Exception e) {
throw new e;
}
}
}
</code>```

Entity class:

```<code>@Getter
@Setter
@NoArgConstructor
@AllArgConstructor
@Entity
public class BeanEntity implements Serializable {

private static final long serialVersionID = 3269743987697633760L;

@Id
@Column(name = "ApplicationID", nullable = false, unique = true)
public String application_id;

@Column(name= "Description")
public String desc;

@Column(name = "Status")
public String status;

@Column(name ="Approved")
public int approved;

@Column(name ="Declined")
public int declined;

}
</code>```

Bean class:

```<code>@Getter
@Setter
@NoArgConstructor
@AllArgConstructor
public class Bean {
public String application_id;
public String desc;
public String status;
public int approved;
public int declined;
public String name;
}

</code>```

Repository class:

```<code>@Repository
public interface BeanRepository extends JpaRepository<BeanEntity, String> {

@Query(name = "select * from abc", nativeQuery = true)
List<BeanEntity> findAllApplications();
}
</code>```

Below is the Current Response i am getting from above code:

```<code>[
{
"application_id" : "12345",
"desc": "Motor",
"status": "active",
"approved": 1,
"declined": 0,
"name": "A"
},
{
"application_id" : "14785",
"desc": "Nut",
"status": "active",
"approved": 0,
"declined": 1,
"name": "A"
},
{
"application_id" : "15974",
"desc": "Bolt",
"status": "not-active",
"approved": 1,
"declined": 0,
"name": "B"
},
{
"application_id" : "36985",
"desc": "Engine",
"status": "active",
"approved": 1,
"declined": 0,
"name": "B"
},
{
"application_id" : "78945",
"desc": "Filter",
"status": "active",
"approved": 1,
"declined": 0,
"name": "C"
},
{
"application_id" : "45612",
"desc": "AC",
"status": "active",
"approved": 0,
"declined": 1,
"name": "C"
}
]
</code>```

Expected Response i am looking for:

```<code>[
{
"name": "A",
"approved": 1,
"declined": 1
},
{
"name": "B",
"approved": 2,
"declined": 0
},
{
"name": "C",
"approved": 1,
"declined": 1
}
]
</code>```

I am in beginner phase of learning java, How to implement group by with sum of multiple fields in java.
Can someone help me how i can achieve the expected response.

Body:
Controller class:

@RestController
@RequestMapping(value = "/api/v1/")
public class TestController {

@Autowired
TestService testService;

@GetMapping(value = "test")
public List<Bean> getDetails() {
return testService.getDetails();
}
}

Service class:

@Service
public class TestService {

@Autowired
BeanRepository beanRepository;

public List<Bean> getDetails() {
List<Bean> res = new ArrayList<>();
try{
List<BeanEntity> beans = beanRepository.findAllApplications();
for(BeanEntity beanEntity : beans) {
Bean bean = new Bean();
BeanUtils.copyProperties(beanEntity, bean);
if(beanEntity.getDesc().contains("Motor") || beanEntity.getDesc().contains("Nut")){
bean.setName("A");
} else if (beanEntity.getDesc().contains("Bolt") || beanEntity.getDesc().contains("Engine")) {
bean.setName("B");
} else {
bean.setName("C");
}
res.add()
}
} catch(Exception e) {
throw new e;
}
}
}

Entity class:

@Getter
@Setter
@NoArgConstructor
@AllArgConstructor
@Entity
public class BeanEntity implements Serializable {

private static final long serialVersionID = 3269743987697633760L;

@Id
@Column(name = "ApplicationID", nullable = false, unique = true)
public String application_id;

@Column(name= "Description")
public String desc;

@Column(name = "Status")
public String status;

@Column(name ="Approved")
public int approved;

@Column(name ="Declined")
public int declined;

}

Bean class:

@Getter
@Setter
@NoArgConstructor
@AllArgConstructor
public class Bean {
public String application_id;
public String desc;
public String status;
public int approved;
public int declined;
public String name;
}

Repository class:

@Repository
public interface BeanRepository extends JpaRepository<BeanEntity, String> {

@Query(name = "select * from abc", nativeQuery = true)
List<BeanEntity> findAllApplications();
}

Below is the Current Response i am getting from above code:

[
{
"application_id" : "12345",
"desc": "Motor",
"status": "active",
"approved": 1,
"declined": 0,
"name": "A"
},
{
"application_id" : "14785",
"desc": "Nut",
"status": "active",
"approved": 0,
"declined": 1,
"name": "A"
},
{
"application_id" : "15974",
"desc": "Bolt",
"status": "not-active",
"approved": 1,
"declined": 0,
"name": "B"
},
{
"application_id" : "36985",
"desc": "Engine",
"status": "active",
"approved": 1,
"declined": 0,
"name": "B"
},
{
"application_id" : "78945",
"desc": "Filter",
"status": "active",
"approved": 1,
"declined": 0,
"name": "C"
},
{
"application_id" : "45612",
"desc": "AC",
"status": "active",
"approved": 0,
"declined": 1,
"name": "C"
}
]

Expected Response i am looking for:

[
{
"name": "A",
"approved": 1,
"declined": 1
},
{
"name": "B",
"approved": 2,
"declined": 0
},
{
"name": "C",
"approved": 1,
"declined": 1
}
]

I am in beginner phase of learning java, How to implement group by with sum of multiple fields in java.
Can someone help me how i can achieve the expected response.


来源: stackexchange

问:
how to obtain django csrf token in react forms?
I'm developing an app using django rest framework and react. I need to implement csrf token for some of my forms and also jwt refresh token. So these are options that exist for django csrf token handling:

Using {% csrf_token %} before forms in django template.

Adding csrf decorator @ensure_csrf_cookie to a view, to set csrf token as a cookie in response, and then get value of that cookie in react, and add it to my form or request header.

The first option is not possible in my case, because I'm using react instead of django templates.

And second option is not a good idea, because I should request to this specific view (API) to obtain a csrf token, before submitting every form. And also I don't know, in this case, how is gonna django validate csrf tokens properly. I mean, how should django recognize that the passed csrf token has made by the user whose data is being modified! I mean maybe a malicious user request to that view, obtain a valid token, and use that token to modify information of someone else!

So my question is, What is the best way of utilizing csrf tokens in django + react projects?

ContentLicense: CC BY-SA 4.0


问:
Sequelize - include column and getting string instead of object
I have an problem which I can't resolve in any way, I'm including user -> avatar models in PostTip model and when I want to add column with OBJECT avatar (id + src) I can't make it.
Name, email works because I'm pointing to single value not object.
Where is the problem?

```<code>PostTip.findAndCountAll({
      attributes: {
        include: [
        **  [db.sequelize.col(`"user"->"avatar"`), "avatar"],**
          [db.sequelize.col(`"user"."name"`), "name"],
          [db.sequelize.col(`"user"."email"`), "email"],
        ],
      },
      offset: offset,
      limit: limit,
      order: order,
      where: {
        postId: req.params.id,
      },
      include: [
        {
          model: User,
          as: "user",
          attributes: [],
          include: [{ model: AwsAvatar, as: "avatar" }],
        },
      ],
    }).then((result) => {
      console.log(JSON.stringify(result.rows, null, 2));
      const data = getPagingData(result.rows, result.count, query.page, limit);
      return res.send(data);
    });
  };
</code>```

and results are:

```<code>{
    "id": 1,
    "userId": 1,
    "postId": 1,
    "tipAmount": 100,
    "createdAt": "2023-01-11T22:10:26.440Z",
    "updatedAt": "2023-01-11T22:10:26.440Z",
   ** "avatar": "(1,1,https://dh7ieyc6s2dxm.cloudfront.net/avatars/1673514260216_0e69489d-fc95-4ed8-b615-2a76ce43385.webp,\"2023-01-12 09:04:21.223+00\",\"2023-01-12 09:04:21.223+00\")",**
    "name": "Test User",
    "email": "test@test"
  }
</code>```

Im expecting to have output like that:

```<code>{
    "id": 1,
    "userId": 1,
    "postId": 1,
    "tipAmount": 100,
    "createdAt": "2023-01-11T22:10:26.440Z",
    "updatedAt": "2023-01-11T22:10:26.440Z",
 ** "avatar": {
       "id": 1,
       "userId": 1,
       "src": "https://dh7ieyc6s2dxm.cloudfront.net/avatars/1673514260216_0e69489d-fc95-4ed8-b615-2a76ce5ff385.webp",
       "createdAt": "2023-01-12T09:04:21.223Z",
       "updatedAt": "2023-01-12T09:04:21.223Z"

    },**
    "name": "Test User",
    "email": "test@test"
  }
</code>```

User model:

```<code>import { Optional } from "sequelize";
import {
  Column,
  Table,
  Model,
  DataType,
  ForeignKey,
  BelongsTo,
  Default,
  HasMany,
  HasOne,
} from "sequelize-typescript";
import UserRole from "../../enums/user-role.enum";
import AwsAvatar from "../aws/aws-avatar.model";
import PostComment from "../post/post-comment.model";
import PostLike from "../post/post-like.model";
import PostTip from "../post/post-tip.model";
import Card from "./card.model";
import Role from "./role.model";

interface UserAttributes {
  id: number;
  avatar: AwsAvatar;
  name: string;
  setName: string;
  description: string;
  hashtag: string;
  email: string;
  password: string;
  isVip: boolean;
  lastUsedCardNum: string;
  sendNotifications: boolean;
  cards: Card[];
}

interface UserCreationAttributes
  extends Optional<
    UserAttributes,
    | "id"
    | "avatar"
    | "setName"
    | "description"
    | "hashtag"
    | "cards"
    | "isVip"
    | "lastUsedCardNum"
    | "sendNotifications"
  > {}

@Table({ tableName: "users" })
export default class User extends Model<
  UserAttributes,
  UserCreationAttributes
> {
  @Column(DataType.STRING)
  public name!: string;

  @Column(DataType.STRING)
  public setName!: string;

  @Column(DataType.STRING)
  public email!: string;

  @Column(DataType.STRING)
  public password!: string;

  @HasOne(() => AwsAvatar)
  public avatar!: AwsAvatar;

  @Column(DataType.STRING)
  public description!: string;

  @Column(DataType.STRING)
  public hashtag!: string;

  @Default(false)
  @Column(DataType.BOOLEAN)
  public isVip!: boolean;

  @Default(false)
  @Column(DataType.BOOLEAN)
  public subscriptionActive!: boolean;

  @Column(DataType.DATE)
  public subscriptionExpireDate!: Date;

  @Default(false)
  @Column(DataType.BOOLEAN)
  public emailConfirmed!: boolean;

  @Default(false)
  @Column(DataType.BOOLEAN)
  public invalidEmail!: boolean;

  @Column
  public buyedContent!: string;

  @Default(0)
  @Column(DataType.INTEGER)
  public wallet!: number;

  @Default(0)
  @Column(DataType.INTEGER)
  public spent!: number;

  @Default(false)
  @Column(DataType.BOOLEAN)
  public isMessageReaded!: boolean;

  @Default(false)
  @Column(DataType.BOOLEAN)
  public sendNotifications!: boolean;

  //
  @Column
  public messageContainerDto!: string;

  @Column(DataType.STRING)
  public lastUsedCardNum!: string;

  @HasMany(() => Card)
  public cards!: Card[];

  @ForeignKey(() => Role)
  @Default(UserRole.User)
  @Column(DataType.INTEGER)
  public roleId!: number;

  @BelongsTo(() => Role)
  public role!: Role;

  @HasMany(() => PostTip)
  public tips!: PostTip[];

  @HasMany(() => PostComment)
  public comments!: PostComment[];

  @HasMany(() => PostLike)
  public likes!: PostLike[];
}
</code>```

Avatar model:

```<code>import { Optional } from "sequelize";
import {
  Column,
  Table,
  Model,
  DataType,
  ForeignKey,
  BelongsTo,
} from "sequelize-typescript";
import User from "../user/user.model";

interface AwsAvatarAttributes {
  id: number;
  src: string;
}

interface AwsAvatarCreationAttributes
  extends Optional<AwsAvatarAttributes, "id"> {}

@Table({ tableName: "aws_avatars" })
export default class AwsAvatar extends Model<
  AwsAvatarAttributes,
  AwsAvatarCreationAttributes
> {
  @ForeignKey(() => User)
  @Column(DataType.INTEGER)
  public userId!: number;

  @BelongsTo(() => User, { onDelete: "CASCADE" })
  public user!: User;

  @Column(DataType.STRING)
  public src!: string;
}
</code>```

I know it can be done smth like that, but cmon, I believe that there is any way to join avatar table and not for each loop every time when fetching data:

```<code>private getPostTips = (req: Request, res: Response, next: NextFunction) => {
    const query = req.query as unknown as { name: string } & PaginationDto;

    const { limit, offset } = getPagination(query.page, query.size);

    const condition = query.name
      ? {
          name: {
            [Op.iLike]: "%" + query.name + "%",
          },
        }
      : {};

    const order: any[string] = [[query.sort, query.order]];

    PostTip.findAndCountAll({
      raw: true,
      nest: true,
      attributes: {
        include: [
          [db.sequelize.col(`"user"."name"`), "name"],
          [db.sequelize.col(`"user"."email"`), "email"],
        ],
      },
      offset: offset,
      limit: limit,
      order: order,
      where: { postId: req.params.id },
      include: [
        {
          model: User,
          as: "user",
          attributes: [],
          where: condition,
          include: [{ model: AwsAvatar, as: "avatar" }],
        },
      ],
    }).then((result) => {
      **const sorted: any[] = [];
      for (let i = 0; i < result.rows.length; i++) {
        let item = {
          avatar: result.rows[i].user.avatar,
          ...result.rows[i],
          user: undefined,
        };
        sorted.push(item);
      }**
      const data = getPagingData(sorted, result.count, query.page, limit);
      return res.send(data);
    });
  };
</code>```

Body:
I have an problem which I can't resolve in any way, I'm including user -> avatar models in PostTip model and when I want to add column with OBJECT avatar (id + src) I can't make it.
Name, email works because I'm pointing to single value not object.
Where is the problem?

PostTip.findAndCountAll({
      attributes: {
        include: [
        **  [db.sequelize.col(`"user"->"avatar"`), "avatar"],**
          [db.sequelize.col(`"user"."name"`), "name"],
          [db.sequelize.col(`"user"."email"`), "email"],
        ],
      },
      offset: offset,
      limit: limit,
      order: order,
      where: {
        postId: req.params.id,
      },
      include: [
        {
          model: User,
          as: "user",
          attributes: [],
          include: [{ model: AwsAvatar, as: "avatar" }],
        },
      ],
    }).then((result) => {
      console.log(JSON.stringify(result.rows, null, 2));
      const data = getPagingData(result.rows, result.count, query.page, limit);
      return res.send(data);
    });
  };

and results are:

{
    "id": 1,
    "userId": 1,
    "postId": 1,
    "tipAmount": 100,
    "createdAt": "2023-01-11T22:10:26.440Z",
    "updatedAt": "2023-01-11T22:10:26.440Z",
   ** "avatar": "(1,1,https://dh7ieyc6s2dxm.cloudfront.net/avatars/1673514260216_0e69489d-fc95-4ed8-b615-2a76ce43385.webp,\"2023-01-12 09:04:21.223+00\",\"2023-01-12 09:04:21.223+00\")",**
    "name": "Test User",
    "email": "test@test"
  }

Im expecting to have output like that:

{
    "id": 1,
    "userId": 1,
    "postId": 1,
    "tipAmount": 100,
    "createdAt": "2023-01-11T22:10:26.440Z",
    "updatedAt": "2023-01-11T22:10:26.440Z",
 ** "avatar": {
       "id": 1,
       "userId": 1,
       "src": "https://dh7ieyc6s2dxm.cloudfront.net/avatars/1673514260216_0e69489d-fc95-4ed8-b615-2a76ce5ff385.webp",
       "createdAt": "2023-01-12T09:04:21.223Z",
       "updatedAt": "2023-01-12T09:04:21.223Z"

    },**
    "name": "Test User",
    "email": "test@test"
  }

User model:

import { Optional } from "sequelize";
import {
  Column,
  Table,
  Model,
  DataType,
  ForeignKey,
  BelongsTo,
  Default,
  HasMany,
  HasOne,
} from "sequelize-typescript";
import UserRole from "../../enums/user-role.enum";
import AwsAvatar from "../aws/aws-avatar.model";
import PostComment from "../post/post-comment.model";
import PostLike from "../post/post-like.model";
import PostTip from "../post/post-tip.model";
import Card from "./card.model";
import Role from "./role.model";

interface UserAttributes {
  id: number;
  avatar: AwsAvatar;
  name: string;
  setName: string;
  description: string;
  hashtag: string;
  email: string;
  password: string;
  isVip: boolean;
  lastUsedCardNum: string;
  sendNotifications: boolean;
  cards: Card[];
}

interface UserCreationAttributes
  extends Optional<
    UserAttributes,
    | "id"
    | "avatar"
    | "setName"
    | "description"
    | "hashtag"
    | "cards"
    | "isVip"
    | "lastUsedCardNum"
    | "sendNotifications"
  > {}

@Table({ tableName: "users" })
export default class User extends Model<
  UserAttributes,
  UserCreationAttributes
> {
  @Column(DataType.STRING)
  public name!: string;

  @Column(DataType.STRING)
  public setName!: string;

  @Column(DataType.STRING)
  public email!: string;

  @Column(DataType.STRING)
  public password!: string;

  @HasOne(() => AwsAvatar)
  public avatar!: AwsAvatar;

  @Column(DataType.STRING)
  public description!: string;

  @Column(DataType.STRING)
  public hashtag!: string;

  @Default(false)
  @Column(DataType.BOOLEAN)
  public isVip!: boolean;

  @Default(false)
  @Column(DataType.BOOLEAN)
  public subscriptionActive!: boolean;

  @Column(DataType.DATE)
  public subscriptionExpireDate!: Date;

  @Default(false)
  @Column(DataType.BOOLEAN)
  public emailConfirmed!: boolean;

  @Default(false)
  @Column(DataType.BOOLEAN)
  public invalidEmail!: boolean;

  @Column
  public buyedContent!: string;

  @Default(0)
  @Column(DataType.INTEGER)
  public wallet!: number;

  @Default(0)
  @Column(DataType.INTEGER)
  public spent!: number;

  @Default(false)
  @Column(DataType.BOOLEAN)
  public isMessageReaded!: boolean;

  @Default(false)
  @Column(DataType.BOOLEAN)
  public sendNotifications!: boolean;

  //
  @Column
  public messageContainerDto!: string;

  @Column(DataType.STRING)
  public lastUsedCardNum!: string;

  @HasMany(() => Card)
  public cards!: Card[];

  @ForeignKey(() => Role)
  @Default(UserRole.User)
  @Column(DataType.INTEGER)
  public roleId!: number;

  @BelongsTo(() => Role)
  public role!: Role;

  @HasMany(() => PostTip)
  public tips!: PostTip[];

  @HasMany(() => PostComment)
  public comments!: PostComment[];

  @HasMany(() => PostLike)
  public likes!: PostLike[];
}

Avatar model:

import { Optional } from "sequelize";
import {
  Column,
  Table,
  Model,
  DataType,
  ForeignKey,
  BelongsTo,
} from "sequelize-typescript";
import User from "../user/user.model";

interface AwsAvatarAttributes {
  id: number;
  src: string;
}

interface AwsAvatarCreationAttributes
  extends Optional<AwsAvatarAttributes, "id"> {}

@Table({ tableName: "aws_avatars" })
export default class AwsAvatar extends Model<
  AwsAvatarAttributes,
  AwsAvatarCreationAttributes
> {
  @ForeignKey(() => User)
  @Column(DataType.INTEGER)
  public userId!: number;

  @BelongsTo(() => User, { onDelete: "CASCADE" })
  public user!: User;

  @Column(DataType.STRING)
  public src!: string;
}

I know it can be done smth like that, but cmon, I believe that there is any way to join avatar table and not for each loop every time when fetching data:

private getPostTips = (req: Request, res: Response, next: NextFunction) => {
    const query = req.query as unknown as { name: string } & PaginationDto;

    const { limit, offset } = getPagination(query.page, query.size);

    const condition = query.name
      ? {
          name: {
            [Op.iLike]: "%" + query.name + "%",
          },
        }
      : {};

    const order: any[string] = [[query.sort, query.order]];

    PostTip.findAndCountAll({
      raw: true,
      nest: true,
      attributes: {
        include: [
          [db.sequelize.col(`"user"."name"`), "name"],
          [db.sequelize.col(`"user"."email"`), "email"],
        ],
      },
      offset: offset,
      limit: limit,
      order: order,
      where: { postId: req.params.id },
      include: [
        {
          model: User,
          as: "user",
          attributes: [],
          where: condition,
          include: [{ model: AwsAvatar, as: "avatar" }],
        },
      ],
    }).then((result) => {
      **const sorted: any[] = [];
      for (let i = 0; i < result.rows.length; i++) {
        let item = {
          avatar: result.rows[i].user.avatar,
          ...result.rows[i],
          user: undefined,
        };
        sorted.push(item);
      }**
      const data = getPagingData(sorted, result.count, query.page, limit);
      return res.send(data);
    });
  };


问:
How to check value of attributes in array?
Please tell me how to assign values to tags by their attributes:

if the attribute is empty - the background is red

if there is something in the attribute - the background is blue

Gives error all the time - Uncaught TypeError: elems.getAttribute is not a function

Is it possible to replace getAttribute with something else?

Thank you in advance!

function ifImgIsEmpty() {
    let elems = document.querySelectorAll('.card');
    let value = elems.dataset.databackgroundImage;

    for (let elem of elems) {
        if (elem.value === null && elem.value === '') {
            elem.style.background = "red";
        } else {
            elem.style.background = "blue";
        }
    }

};
ifImgIsEmpty();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.card {
  display: flex:
  border: solid;
  padding: 2rem;
  background: #eee;
}</code>```

01
02
03
04```

Body:
Please tell me how to assign values to tags by their attributes:

if the attribute is empty - the background is red

if there is something in the attribute - the background is blue

Gives error all the time - Uncaught TypeError: elems.getAttribute is not a function

Is it possible to replace getAttribute with something else?

Thank you in advance!

function ifImgIsEmpty() {
    let elems = document.querySelectorAll('.card');
    let value = elems.dataset.databackgroundImage;

    for (let elem of elems) {
        if (elem.value === null && elem.value === '') {
            elem.style.background = "red";
        } else {
            elem.style.background = "blue";
        }
    }

};
ifImgIsEmpty();

.card {
  display: flex:
  border: solid;
  padding: 2rem;
  background: #eee;
}

01
02
03
04


问:
How are chrome driver performance logs modified?
I would expect the chrome driver performance log to grow with new requests over time.

However, the contents of driver.get_log('performance') change with almost every request.

Are old requests cleared after they are viewed using this method?

If the log isn't inspected often enough, can requests be cleared before they are accessed/processed?

```<code>import seleniumwire.undetected_chromedriver as uc

driver = uc.Chrome()

driver.get("{URL}")

while(True):
    logs = driver.get_log('performance')

    print(len(logs))
</code>```

Body:
I would expect the chrome driver performance log to grow with new requests over time.

However, the contents of driver.get_log('performance') change with almost every request.

Are old requests cleared after they are viewed using this method?

If the log isn't inspected often enough, can requests be cleared before they are accessed/processed?

import seleniumwire.undetected_chromedriver as uc

driver = uc.Chrome()

driver.get("{URL}")

while(True):
    logs = driver.get_log('performance')

    print(len(logs))


问:
Login data is not being saved in the realtime database when I add window.location.replace
I'm still new to programming and especially Firebase so there probably will some obvious stuff I missed.

This is supposed to be login/register page. When the user type's in the needed info and click one of the buttons that corresponds to there field. Tt's supposed to load another page. Save that data in a Firebase realtime database and also in authentication.

It's doing the ladder and first but not the second. So I'm stuck with the code I have displayed under this. I read something about needing to give sometime for the data to be send out.

```<code>import { firebaseConfig } from "./database.mjs";
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
import { getAuth, createUserWithEmailAndPassword,
    signInWithEmailAndPassword,  onAuthStateChanged,
    signOut } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js";
import {getDatabase, ref, get, set, child, update, remove, push} from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";

const app = initializeApp(firebaseConfig);
const auth = getAuth();
const db = getDatabase();

const UserRegistration = () => {

    const Username = document.getElementById('username').value
    const Email = document.getElementById("email-signup").value;
    const Passwd = document.getElementById("passwd-signup").value;

    createUserWithEmailAndPassword(auth, Email, Passwd)
        .then((userCredential) => {
            const user = userCredential.user;

            const loginTime = new Date()
            set(ref(db, 'users/' + user.uid),{
                user_email: Email,
                user_username: Username,
                last_login: `${loginTime}`
            })

            console.log(user, "User Created");
        }).then(StatusMonitor())
        .catch((error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            console.log(error.message)
        });
}

const UserLogIn = () => {

    const Email = document.getElementById("email-signup").value;
    const Passwd = document.getElementById("passwd-signup").value;

    const auth = getAuth();
    signInWithEmailAndPassword(auth, Email, Passwd)
    .then((userCredential) => {
    const user = userCredential.user;
    const loginTime = new Date()
    update(ref(db, 'users/' + user.uid), {
        last_login: loginTime
    });
    console.log(user, "Login Successfull");
    })
    .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        console.log(error.message);
    });
    StatusMonitor()
}

//Login checker
const StatusMonitor = () => {  //This part specifically

    onAuthStateChanged(auth, (user) => {
        if (user) {
            const uid = user.uid;
            console.log("User is active");
            window.location.replace("./product.html")
          }
          else {
            console.log("User is inactive");
          }

    })
}

document.getElementById("signup").addEventListener("click", UserRegistration);
document.getElementById('login').addEventListener("click", UserLogIn);
</code>```

I was able to get it to work with setTimeout but this created it's own problems such as small freezes whenever the thing got triggered and of course the extra time needed for it to load as I can't set to it change based on latency.

Tried to do it with async/await but personally couldn't get it to work.

Any help would be appreciated!

Body:
I'm still new to programming and especially Firebase so there probably will some obvious stuff I missed.

This is supposed to be login/register page. When the user type's in the needed info and click one of the buttons that corresponds to there field. Tt's supposed to load another page. Save that data in a Firebase realtime database and also in authentication.

It's doing the ladder and first but not the second. So I'm stuck with the code I have displayed under this. I read something about needing to give sometime for the data to be send out.

import { firebaseConfig } from "./database.mjs";
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
import { getAuth, createUserWithEmailAndPassword,
    signInWithEmailAndPassword,  onAuthStateChanged,
    signOut } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js";
import {getDatabase, ref, get, set, child, update, remove, push} from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";

const app = initializeApp(firebaseConfig);
const auth = getAuth();
const db = getDatabase();

const UserRegistration = () => {

    const Username = document.getElementById('username').value
    const Email = document.getElementById("email-signup").value;
    const Passwd = document.getElementById("passwd-signup").value;

    createUserWithEmailAndPassword(auth, Email, Passwd)
        .then((userCredential) => {
            const user = userCredential.user;

            const loginTime = new Date()
            set(ref(db, 'users/' + user.uid),{
                user_email: Email,
                user_username: Username,
                last_login: `${loginTime}`
            })

            console.log(user, "User Created");
        }).then(StatusMonitor())
        .catch((error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            console.log(error.message)
        });
}

const UserLogIn = () => {

    const Email = document.getElementById("email-signup").value;
    const Passwd = document.getElementById("passwd-signup").value;

    const auth = getAuth();
    signInWithEmailAndPassword(auth, Email, Passwd)
    .then((userCredential) => {
    const user = userCredential.user;
    const loginTime = new Date()
    update(ref(db, 'users/' + user.uid), {
        last_login: loginTime
    });
    console.log(user, "Login Successfull");
    })
    .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        console.log(error.message);
    });
    StatusMonitor()
}

//Login checker
const StatusMonitor = () => {  //This part specifically

    onAuthStateChanged(auth, (user) => {
        if (user) {
            const uid = user.uid;
            console.log("User is active");
            window.location.replace("./product.html")
          }
          else {
            console.log("User is inactive");
          }

    })
}

document.getElementById("signup").addEventListener("click", UserRegistration);
document.getElementById('login').addEventListener("click", UserLogIn);

I was able to get it to work with setTimeout but this created it's own problems such as small freezes whenever the thing got triggered and of course the extra time needed for it to load as I can't set to it change based on latency.

Tried to do it with async/await but personally couldn't get it to work.

Any help would be appreciated!


问:
dict(zip()) function compressing two lists in Python
These two lists imported from json file and I can't use dict(zip() properly.

```<code>l1 = ['grant_type', 'scope', 'client_id', 'client_id', 'grant_type', 'scope', 'code', 'redirect_uri']

l2 = ['client_credentials', 'AIS', '{{client_id}}', '{{client_id}}', 'authorization_code', '{{scope}}:{{consents_id}}', '{{response}}', '{{redirect_url}}']

lists = dict(zip(l1, l2))

print(lists)
</code>```

Output:

```<code>{'grant_type': 'authorization_code', 'scope': '{{scope}}:{{consents_id}}', 'client_id': '{{client_id}}', 'code': '{{response}}', 'redirect_uri': '{{redirect_url}}'}
</code>```

I guess there is something with double curly brackets "{{ }}", but I didn't find any information about them and how I can solve this problem.

Thank you for the response!

Body:
These two lists imported from json file and I can't use dict(zip() properly.

l1 = ['grant_type', 'scope', 'client_id', 'client_id', 'grant_type', 'scope', 'code', 'redirect_uri']

l2 = ['client_credentials', 'AIS', '{{client_id}}', '{{client_id}}', 'authorization_code', '{{scope}}:{{consents_id}}', '{{response}}', '{{redirect_url}}']

lists = dict(zip(l1, l2))

print(lists)

Output:

{'grant_type': 'authorization_code', 'scope': '{{scope}}:{{consents_id}}', 'client_id': '{{client_id}}', 'code': '{{response}}', 'redirect_uri': '{{redirect_url}}'}

I guess there is something with double curly brackets "{{ }}", but I didn't find any information about them and how I can solve this problem.

Thank you for the response!


问:
Abstraction in Typescript Indexed Access Types
I have a type generated for me by a generator I cannot control, that is, I can't edit the source where Foo is defined:

```<code>type Foo = {
  foo1: { bar : { quux : string }},
  foo2: { bar: { quux: number }}
}
</code>```

Then I use it in my code (which I can control):

```<code>function aaa(x: Foo["foo1"]["bar"]["quux"]) {
   ...
}

function bbb(x: Foo["foo2"]["bar"]["quux"]) {
   ...
}
</code>```

There is a repetition of ["bar"]["quux"]. How can I avoid it?

One option would be to declare a mapped type:

```<code>type FooShort = {
  [p in keyof Foo]: Foo[p]["bar"]["quux"]
}

function aaa(x: FooShort["foo1"]) {
   ...
}

function bbb(x: FooShort["foo2"]) {
   ...
}

</code>```

But it doesn't work. Any ideas?

Upd: thanks to the comments, it turned out that my minimal example did work. But in my full code Foo is non-uniform:

```<code>type Foo = {
  foo1: { bar : { quux : string }},
  foo2: { bar: { quux: number }}
  foo3: number
}
</code>```

Fortunately the extends trick proposed by @vera works as a conditional type (as described in https://www.typescriptlang.org/docs/handbook/2/conditional-types.html after "However, what if we wanted MessageOf to take any type").

So if @vera adapts the code to use the conditional, so that BQ["foo1"] works with the Foo above, I'll accept that as the answer. If not, I'll have to answer my own question and mention @vera's contribution that let me find the solution myself.

Body:
I have a type generated for me by a generator I cannot control, that is, I can't edit the source where Foo is defined:

type Foo = {
  foo1: { bar : { quux : string }},
  foo2: { bar: { quux: number }}
}

Then I use it in my code (which I can control):

function aaa(x: Foo["foo1"]["bar"]["quux"]) {
   ...
}

function bbb(x: Foo["foo2"]["bar"]["quux"]) {
   ...
}

There is a repetition of ["bar"]["quux"]. How can I avoid it?

One option would be to declare a mapped type:

type FooShort = {
  [p in keyof Foo]: Foo[p]["bar"]["quux"]
}

function aaa(x: FooShort["foo1"]) {
   ...
}

function bbb(x: FooShort["foo2"]) {
   ...
}

But it doesn't work. Any ideas?

Upd: thanks to the comments, it turned out that my minimal example did work. But in my full code Foo is non-uniform:

type Foo = {
  foo1: { bar : { quux : string }},
  foo2: { bar: { quux: number }}
  foo3: number
}

Fortunately the extends trick proposed by @vera works as a conditional type (as described in https://www.typescriptlang.org/docs/handbook/2/conditional-types.html after "However, what if we wanted MessageOf to take any type").

So if @vera adapts the code to use the conditional, so that BQ["foo1"] works with the Foo above, I'll accept that as the answer. If not, I'll have to answer my own question and mention @vera's contribution that let me find the solution myself.


问:
tkinter and Pylance: argument of type tuple cannot be assigned to parameter "command" of type none
I use VS Code as my IDE and I have Pylance extension to help debugging the code.

Pylance keeps underlining command=self.get_inputs as error even thought the code runs just fine. Here is an example:

self.button1 = ctk.CTkButton(self, text="Calculate", command=self.get_inputs) self.button1.grid(row=5, column=0, pady=10, padx=10, sticky="W")

def get_inputs(self):
    H1 = self.entry2.get()
    d1 = self.entry3.get()
    T = self.entry4.get()
    alpha1 = self.entry5.get()
    s = self.entry6.get()
    z = self.entry7.get()
    d2 = self.entry8.get()

    return H1, d1, T, alpha1, s, z, d2
```

Here is the full error:
full error

I don't understand why this is happening. what can I do avoid getting this?

I don't know how I can avoid getting this type of error

Body:
I use VS Code as my IDE and I have Pylance extension to help debugging the code.

Pylance keeps underlining command=self.get_inputs as error even thought the code runs just fine. Here is an example:

self.button1 = ctk.CTkButton(self, text="Calculate", command=self.get_inputs) self.button1.grid(row=5, column=0, pady=10, padx=10, sticky="W")

def get_inputs(self):
    H1 = self.entry2.get()
    d1 = self.entry3.get()
    T = self.entry4.get()
    alpha1 = self.entry5.get()
    s = self.entry6.get()
    z = self.entry7.get()
    d2 = self.entry8.get()

    return H1, d1, T, alpha1, s, z, d2

Here is the full error:
full error

I don't understand why this is happening. what can I do avoid getting this?

I don't know how I can avoid getting this type of error


问:
Uncaught (in promise) SweetAlert: 2nd argument ('undefined') is invalid
I'm trying to create a login/logout with React and Sweet Alert, but the it keeps saying that the 2nd argument is invalid and I'm not sure where.
Below the code for the login.
Can anyone spot any error in these functions?
If yes, please let me know.
Cheers</p>
```<code>import React, {
    useState
} from 'react';
import swal from 'sweetalert';

async function loginUser(credentials) {
    let BaseUrl = 'process.env.MYCREDENTIALS';
        fetch(BaseUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(credentials)
            })
            .then(data => data.json())
           }

export default function Signin() {
    const classes = useStyles();
    const [username, setUserName] = useState();
    const [password, setPassword] = useState();

    const handleSubmit = async e => {
        e.preventDefault();
        const response = await loginUser({
            username,
            password
        });

        if ('accessToken') {
            swal("Success", {
                    buttons: false,
                    timer: 1000,
                })
                .then((value) => {
                    localStorage.setItem('accessToken', response['accessToken']);
                    localStorage.setItem('user', JSON.stringify(response['user']));
                    window.location.href = "/profile";
                });
        } else {
            swal("Failed", response.message, "error");
        }
    }
</code>```

Body:
I'm trying to create a login/logout with React and Sweet Alert, but the it keeps saying that the 2nd argument is invalid and I'm not sure where.
Below the code for the login.
Can anyone spot any error in these functions?
If yes, please let me know.
Cheers

import React, {
    useState
} from 'react';
import swal from 'sweetalert';

async function loginUser(credentials) {
    let BaseUrl = 'process.env.MYCREDENTIALS';
        fetch(BaseUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(credentials)
            })
            .then(data => data.json())
           }

export default function Signin() {
    const classes = useStyles();
    const [username, setUserName] = useState();
    const [password, setPassword] = useState();

    const handleSubmit = async e => {
        e.preventDefault();
        const response = await loginUser({
            username,
            password
        });

        if ('accessToken') {
            swal("Success", {
                    buttons: false,
                    timer: 1000,
                })
                .then((value) => {
                    localStorage.setItem('accessToken', response['accessToken']);
                    localStorage.setItem('user', JSON.stringify(response['user']));
                    window.location.href = "/profile";
                });
        } else {
            swal("Failed", response.message, "error");
        }
    }


问:
Prettier splits 1 60-character line of JS into 11 lines with printWidth at 2500 and singleAttributePerLine disabled?
Before Prettier:

```<code>console.log(countSubTrees(4, [[0, 1],[1, 2],[0, 3]], "bbbb"));
</code>```

After Prettier:

```<code>console.log(
    countSubTrees(
        4,
        [
            [0, 1],
            [1, 2],
            [0, 3],
        ],
        "bbbb"
    )
);
</code>```

Does anyone understand why it does this? Is it because it contains a 2-dimensional array? I thought this extension was pretty ubiquitous, but I have a hard time imagining this is what anyone would want their code to look like. Usually it's okayish but situations like these make it really hard to want to leave the extension enabled.

The only things my Googling has returned to change this is to increase printWidth and, for certain languages, disable singleAttributePerLine, but neither fixes what you see here. Am I missing something here? This is just bizarre to me.

Body:
Before Prettier:

console.log(countSubTrees(4, [[0, 1],[1, 2],[0, 3]], "bbbb"));

After Prettier:

console.log(
    countSubTrees(
        4,
        [
            [0, 1],
            [1, 2],
            [0, 3],
        ],
        "bbbb"
    )
);

Does anyone understand why it does this? Is it because it contains a 2-dimensional array? I thought this extension was pretty ubiquitous, but I have a hard time imagining this is what anyone would want their code to look like. Usually it's okayish but situations like these make it really hard to want to leave the extension enabled.

The only things my Googling has returned to change this is to increase printWidth and, for certain languages, disable singleAttributePerLine, but neither fixes what you see here. Am I missing something here? This is just bizarre to me.


问:
Net::Async::WebSocket::Server in a separate main loop
I am trying to achieve a fairly simple thing: I want to run a websocket server which is controlled by a main loop instead of the Async::Loop, like this:

```<code>my $sslSocket = IO::Socket::SSL->new(
    Listen             => 5,
    LocalPort          => XXX,
    Proto              => 'tcp',
    SSL_startHandshake => 0,
    SSL_cert_file      => 'XXX',
    SSL_key_file       => 'XXX',
  ) or die "failed to listen: $!";

  my $server = Net::Async::WebSocket::Server->new(
    on_client => sub {
      my ( undef, $client ) = @_;

      $client->configure(
        on_text_frame => sub {
          my ( $self, $frame ) = @_;

          $self->send_text_frame( $frame );
        },
      );
    },
    on_handshake => sub {
      my ( $self, $client, $hs, $continue ) = @_;

      $continue->( 1 );
    }
  );

  my $loop = IO::Async::Loop->new;
  $loop->add( $server );

  $server->listen(
    handle => $sslSocket
  )->get;
</code>```

In the main loop I am calling "$loop->loop_once" whenever the listening socket "$sslSocket" has data available, like this:

```<code>while(1){
  // something before
  if (//data to read) {
    $loop->loop_once;
  }
  // something after
}
</code>```

Unfortunately the websocket connection is never established. None of the callbacks is called. I think I am getting the purpose of "loop_once" wrong but I don't know what the exact issue is.

I already tried to use $loop->run", then the connection can be established correctly. But this is not what I require.

Thanks for help!

Bye

Expectation is that the websocket server is processing outstanding requests when "loop_once" is called.

Body:
I am trying to achieve a fairly simple thing: I want to run a websocket server which is controlled by a main loop instead of the Async::Loop, like this:

my $sslSocket = IO::Socket::SSL->new(
    Listen             => 5,
    LocalPort          => XXX,
    Proto              => 'tcp',
    SSL_startHandshake => 0,
    SSL_cert_file      => 'XXX',
    SSL_key_file       => 'XXX',
  ) or die "failed to listen: $!";

  my $server = Net::Async::WebSocket::Server->new(
    on_client => sub {
      my ( undef, $client ) = @_;

      $client->configure(
        on_text_frame => sub {
          my ( $self, $frame ) = @_;

          $self->send_text_frame( $frame );
        },
      );
    },
    on_handshake => sub {
      my ( $self, $client, $hs, $continue ) = @_;

      $continue->( 1 );
    }
  );

  my $loop = IO::Async::Loop->new;
  $loop->add( $server );

  $server->listen(
    handle => $sslSocket
  )->get;

In the main loop I am calling "$loop->loop_once" whenever the listening socket "$sslSocket" has data available, like this:

while(1){
  // something before
  if (//data to read) {
    $loop->loop_once;
  }
  // something after
}

Unfortunately the websocket connection is never established. None of the callbacks is called. I think I am getting the purpose of "loop_once" wrong but I don't know what the exact issue is.

I already tried to use $loop->run", then the connection can be established correctly. But this is not what I require.

Thanks for help!

Bye

Expectation is that the websocket server is processing outstanding requests when "loop_once" is called.


问:
my query is incorrect. convert_tz is causing incorrect values
I use convert_tz for many queries that I use daily. Yesterday, it began yielding incorrect values.

I seperated these lines from my query, and ran them separately.

```<code>SELECT
CURDATE() - interval 1 day as yesterday,
CURDATE() as today,
CONVERT_TZ(CURDATE(), @@session.time_zone, 'America/New_York') as Today_CTZ;
</code>```

This will return 3 columns, and it should show yestderday's date, todays date, and todays date.
This is what is returned instead.

yesterday
today
Today_CTZ

2023-01-11
2023-01-12
2023-01-11 19:00:00

It has returned yesterdays date, todays date, and yesterdays date.

This query was run on 1/12/23 at 9:20 AM

This is what it should produce

yesterday
today
Today_CTZ

2023-01-11
2023-01-12
2023-01-12 19:00:00

Why is it doing this?

Body:
I use convert_tz for many queries that I use daily. Yesterday, it began yielding incorrect values.

I seperated these lines from my query, and ran them separately.

SELECT
CURDATE() - interval 1 day as yesterday,
CURDATE() as today,
CONVERT_TZ(CURDATE(), @@session.time_zone, 'America/New_York') as Today_CTZ;

This will return 3 columns, and it should show yestderday's date, todays date, and todays date.
This is what is returned instead.

yesterday
today
Today_CTZ

2023-01-11
2023-01-12
2023-01-11 19:00:00

It has returned yesterdays date, todays date, and yesterdays date.

This query was run on 1/12/23 at 9:20 AM

This is what it should produce

yesterday
today
Today_CTZ

2023-01-11
2023-01-12
2023-01-12 19:00:00

Why is it doing this?


问:
Shell.Current.GoToAsync($"{nameof(NotesApiPage)}") throw error System.NullReferenceException: 'Object reference not set to an instance of an object.'
I am using viewmodel to navigate to a page upon successful login:
I am getting null reference error when navigating to a different page.
The same line of code that navigates to Login page in cse of no authentication works pretty well.

ViewModel

```<code>using Notas.Helpers;
using Notas.Model;
using Notas.View;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Notas.ViewModel
{
    public partial class LoadingPageViewModel : BaseViewModel
    {
        public LoadingPageViewModel()
        {
            CheckUserLoginDetails();
        }

        private async void CheckUserLoginDetails()
        {
            // retrieve token from internal storage
            var token = await SecureStorage.GetAsync("Token");
            if (string.IsNullOrEmpty(token))
                await GoToLoginPage();
            else
            {
                var jsonToken = new JwtSecurityTokenHandler().ReadJwtToken(token);
                if (jsonToken.ValidTo < DateTime.UtcNow)
                {
                    SecureStorage.Remove("Token");
                    await GoToLoginPage();
                }
                else
                {
                    var role = jsonToken.Claims.FirstOrDefault(j => j.Type.Equals(ClaimTypes.Role))?.Value;
                    App.UserInfo = new UserInfo()
                    {
                        username = jsonToken.Claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Name))?.Value,
                        role = role
                    };
                    MenuBuilder.BuildMenu();
                    await GoToMainPage();
                }

            }
        }

        private async Task GoToLoginPage()
        {
            await Shell.Current.GoToAsync($"{nameof(LoginPage)}");
        }
        private async Task GoToMainPage()
        {
            await Shell.Current.GoToAsync($"{nameof(NotesApiPage)}"); //GETTING ERROR HERE...
        }
    }
}
</code>```

XAML Page

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Notas.View.NotesApiPage"
             xmlns:model="clr-namespace:Notas.Model"
             xmlns:viewmodel="clr-namespace:Notas.ViewModel"
             x:DataType="viewmodel:NotesApiViewModel"
             Title="{Binding Title}">
    <VerticalStackLayout HorizontalOptions="Start" Padding="5" Spacing="10" Margin="5">
        <Label Text="My Notes" FontAttributes="Bold" FontSize="Subtitle"/>
        <RefreshView
            IsRefreshing="{Binding Isrefreshing}"
            Command="{Binding GetNotesCommand}">
            <CollectionView ItemsSource="{Binding Notes}">
                <CollectionView.ItemTemplate>
                    <DataTemplate x:DataType="model:Note">
                        <Grid Padding="3" ColumnSpacing="2" ColumnDefinitions="*,Auto">
                            <Frame Grid.Column="0">
                                <Frame.GestureRecognizers>
                                    <TapGestureRecognizer
                                    Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:NotesViewModel}}, Path=GetNoteDetailsCommand}"
                                    CommandParameter="{Binding Id}"/>
                                </Frame.GestureRecognizers>
                                <Label Text="{Binding NoteDescription}"/>
                            </Frame>
                            <Button Grid.Column="1" Text="Delete"
                                Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:NotesViewModel}}, Path=DeleteNoteCommand}"
                                CommandParameter="{Binding Id}"/>
                        </Grid>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </RefreshView>
    </VerticalStackLayout>
</ContentPage>
</code>```

AppShell

```<code><?xml version="1.0" encoding="UTF-8" ?>
<Shell
    x:Class="Notas.AppShell"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:Notas.View"
    Shell.FlyoutBehavior="Flyout">

    <ShellContent
        Title="Home" Icon="icons_home.png"
        ContentTemplate="{DataTemplate local:LoadingPage}"
        Route="LoadingPage" />

</Shell>
</code>```

AppShel.xaml.cs

```<code>using Notas.View;

namespace Notas;

public partial class AppShell : Shell
{
    public AppShell()
    {
        InitializeComponent();
        Routing.RegisterRoute(nameof(NotesApiPage), typeof(NotesApiPage));
        Routing.RegisterRoute(nameof(NoteDetailPage), typeof(NoteDetailPage));
        Routing.RegisterRoute(nameof(LoginPage), typeof(LoginPage));
        Routing.RegisterRoute(nameof(MainPage), typeof(MainPage));
    }
}
</code>```

Getting the below error as shown in screenshot

My project structure is as below

Body:
I am using viewmodel to navigate to a page upon successful login:
I am getting null reference error when navigating to a different page.
The same line of code that navigates to Login page in cse of no authentication works pretty well.

ViewModel

using Notas.Helpers;
using Notas.Model;
using Notas.View;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Notas.ViewModel
{
    public partial class LoadingPageViewModel : BaseViewModel
    {
        public LoadingPageViewModel()
        {
            CheckUserLoginDetails();
        }

        private async void CheckUserLoginDetails()
        {
            // retrieve token from internal storage
            var token = await SecureStorage.GetAsync("Token");
            if (string.IsNullOrEmpty(token))
                await GoToLoginPage();
            else
            {
                var jsonToken = new JwtSecurityTokenHandler().ReadJwtToken(token);
                if (jsonToken.ValidTo < DateTime.UtcNow)
                {
                    SecureStorage.Remove("Token");
                    await GoToLoginPage();
                }
                else
                {
                    var role = jsonToken.Claims.FirstOrDefault(j => j.Type.Equals(ClaimTypes.Role))?.Value;
                    App.UserInfo = new UserInfo()
                    {
                        username = jsonToken.Claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Name))?.Value,
                        role = role
                    };
                    MenuBuilder.BuildMenu();
                    await GoToMainPage();
                }

            }
        }

        private async Task GoToLoginPage()
        {
            await Shell.Current.GoToAsync($"{nameof(LoginPage)}");
        }
        private async Task GoToMainPage()
        {
            await Shell.Current.GoToAsync($"{nameof(NotesApiPage)}"); //GETTING ERROR HERE...
        }
    }
}

XAML Page

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Notas.View.NotesApiPage"
             xmlns:model="clr-namespace:Notas.Model"
             xmlns:viewmodel="clr-namespace:Notas.ViewModel"
             x:DataType="viewmodel:NotesApiViewModel"
             Title="{Binding Title}">
    <VerticalStackLayout HorizontalOptions="Start" Padding="5" Spacing="10" Margin="5">

        <RefreshView
            IsRefreshing="{Binding Isrefreshing}"
            Command="{Binding GetNotesCommand}">
            <CollectionView ItemsSource="{Binding Notes}">
                <CollectionView.ItemTemplate>
                    <DataTemplate x:DataType="model:Note">
                        <Grid Padding="3" ColumnSpacing="2" ColumnDefinitions="*,Auto">
                            <Frame Grid.Column="0">
                                <Frame.GestureRecognizers>
                                    <TapGestureRecognizer
                                    Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:NotesViewModel}}, Path=GetNoteDetailsCommand}"
                                    CommandParameter="{Binding Id}"/>
                                </Frame.GestureRecognizers>

                            </Frame>
                            <Button Grid.Column="1" Text="Delete"
                                Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:NotesViewModel}}, Path=DeleteNoteCommand}"
                                CommandParameter="{Binding Id}"/>
                        </Grid>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </RefreshView>
    </VerticalStackLayout>
</ContentPage>

AppShell

<?xml version="1.0" encoding="UTF-8" ?>
<Shell
    x:Class="Notas.AppShell"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:Notas.View"
    Shell.FlyoutBehavior="Flyout">

    <ShellContent
        Title="Home" Icon="icons_home.png"
        ContentTemplate="{DataTemplate local:LoadingPage}"
        Route="LoadingPage" />

</Shell>

AppShel.xaml.cs

using Notas.View;

namespace Notas;

public partial class AppShell : Shell
{
    public AppShell()
    {
        InitializeComponent();
        Routing.RegisterRoute(nameof(NotesApiPage), typeof(NotesApiPage));
        Routing.RegisterRoute(nameof(NoteDetailPage), typeof(NoteDetailPage));
        Routing.RegisterRoute(nameof(LoginPage), typeof(LoginPage));
        Routing.RegisterRoute(nameof(MainPage), typeof(MainPage));
    }
}

Getting the below error as shown in screenshot

My project structure is as below


问:
Laravel Cashier Call to a member function stripe() on null
I have created a product and trying to subscribe user using laravel Cashier. Below the subscriptionProcess method that I have tried. I also share laravel log below.

```<code>public function subscriptionProcess(Request $request)
{

        //dd($request->user()->newSubscription('Author', 'price_1MPP8WSCmMZAfVWiwJlCbVym'));
        $subscription = $request->user()->newSubscription('Author', 'price_1MPP8WSCmMZAfVWiwJlCbVym')->create($request->token);

        return view("pages.subscription_success");
}
</code>```

After send the below request

I have used the card number

```<code>https://stripe.com/docs/testing
</code>```

Always getting response

```<code>Laravel Cashier  Call to a member function stripe() on null
</code>```

After dd($request->user()->newSubscription('Author', 'price_1MPP8WSCmMZAfVWiwJlCbVym'));

I have got below object

Laravel Error log has updated below.

```<code>    [2023-01-12 21:56:53] local.ERROR: Call to a member function stripe() on null {"userId":51,"exception":"[object] (Error(code: 0): Call to a member function stripe() on null at /var/www/html/vendor/laravel/cashier/src/Subscription.php:1371)
[stacktrace]
#0 /var/www/html/vendor/laravel/cashier/src/Subscription.php(1271): Laravel\\Cashier\\Subscription->asStripeSubscription(Array)
#1 /var/www/html/vendor/laravel/cashier/src/Concerns/HandlesPaymentFailures.php(28): Laravel\\Cashier\\Subscription->latestPayment()
#2 /var/www/html/vendor/laravel/cashier/src/SubscriptionBuilder.php(263): Laravel\\Cashier\\SubscriptionBuilder->handlePaymentFailure(Object(Laravel\\Cashier\\Subscription), 'pm_1MPT92SCmMZA...')
#3 /var/www/html/app/Http/Controllers/AuthorController.php(72): Laravel\\Cashier\\SubscriptionBuilder->create('pm_1MPT92SCmMZA...')
#4 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): App\\Http\\Controllers\\AuthorController->subscriptionProcess(Object(Illuminate\\Http\\Request))
#5 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(43): Illuminate\\Routing\\Controller->callAction('subscriptionPro...', Array)
#6 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Route.php(260): Illuminate\\Routing\\ControllerDispatcher->dispatch(Object(Illuminate\\Routing\\Route), Object(App\\Http\\Controllers\\AuthorController), 'subscriptionPro...')
#7 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Route.php(205): Illuminate\\Routing\\Route->runController()
#8 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php(727): Illuminate\\Routing\\Route->run()
#9 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): Illuminate\\Routing\\Router->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#10 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#11 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#12 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(50): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#13 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Routing\\Middleware\\SubstituteBindings->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#14 /var/www/html/vendor/laravel/framework/src/Illuminate/Session/Middleware/AuthenticateSession.php(59): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#15 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Session\\Middleware\\AuthenticateSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#16 /var/www/html/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php(44): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#17 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Auth\\Middleware\\Authenticate->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#18 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(78): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#19 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#20 /var/www/html/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#21 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\View\\Middleware\\ShareErrorsFromSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#22 /var/www/html/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(121): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#23 /var/www/html/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(64): Illuminate\\Session\\Middleware\\StartSession->handleStatefulRequest(Object(Illuminate\\Http\\Request), Object(Illuminate\\Session\\Store), Object(Closure))
#24 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Session\\Middleware\\StartSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#25 /var/www/html/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#26 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#27 /var/www/html/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(67): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#28 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Cookie\\Middleware\\EncryptCookies->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#29 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#30 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php(728): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#31 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php(705): Illuminate\\Routing\\Router->runRouteWithinStack(Object(Illuminate\\Routing\\Route), Object(Illuminate\\Http\\Request))
#32 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php(669): Illuminate\\Routing\\Router->runRoute(Object(Illuminate\\Http\\Request), Object(Illuminate\\Routing\\Route))
#33 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php(658): Illuminate\\Routing\\Router->dispatchToRoute(Object(Illuminate\\Http\\Request))
#34 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(190): Illuminate\\Routing\\Router->dispatch(Object(Illuminate\\Http\\Request))
#35 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): Illuminate\\Foundation\\Http\\Kernel->Illuminate\\Foundation\\Http\\{closure}(Object(Illuminate\\Http\\Request))
#36 /var/www/html/vendor/barryvdh/laravel-debugbar/src/Middleware/InjectDebugbar.php(66): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#37 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Barryvdh\\Debugbar\\Middleware\\InjectDebugbar->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#38 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#39 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php(31): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#40 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\ConvertEmptyStringsToNull->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#41 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#42 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php(40): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#43 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\TrimStrings->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#44 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php(86): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#45 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\PreventRequestsDuringMaintenance->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#46 /var/www/html/vendor/laravel/framework/src/Illuminate/Http/Middleware/HandleCors.php(49): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#47 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Http\\Middleware\\HandleCors->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#48 /var/www/html/vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustProxies.php(39): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#49 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Http\\Middleware\\TrustProxies->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#50 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#51 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(165): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#52 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(134): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))
#53 /var/www/html/public/index.php(52): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))
#54 {main}
"}
</code>```

Body:
I have created a product and trying to subscribe user using laravel Cashier. Below the subscriptionProcess method that I have tried. I also share laravel log below.

public function subscriptionProcess(Request $request)
{

        //dd($request->user()->newSubscription('Author', 'price_1MPP8WSCmMZAfVWiwJlCbVym'));
        $subscription = $request->user()->newSubscription('Author', 'price_1MPP8WSCmMZAfVWiwJlCbVym')->create($request->token);

        return view("pages.subscription_success");
}

After send the below request

I have used the card number

https://stripe.com/docs/testing

Always getting response

Laravel Cashier  Call to a member function stripe() on null

After dd($request->user()->newSubscription('Author', 'price_1MPP8WSCmMZAfVWiwJlCbVym'));

I have got below object

Laravel Error log has updated below.

    [2023-01-12 21:56:53] local.ERROR: Call to a member function stripe() on null {"userId":51,"exception":"[object] (Error(code: 0): Call to a member function stripe() on null at /var/www/html/vendor/laravel/cashier/src/Subscription.php:1371)
[stacktrace]
#0 /var/www/html/vendor/laravel/cashier/src/Subscription.php(1271): Laravel\\Cashier\\Subscription->asStripeSubscription(Array)
#1 /var/www/html/vendor/laravel/cashier/src/Concerns/HandlesPaymentFailures.php(28): Laravel\\Cashier\\Subscription->latestPayment()
#2 /var/www/html/vendor/laravel/cashier/src/SubscriptionBuilder.php(263): Laravel\\Cashier\\SubscriptionBuilder->handlePaymentFailure(Object(Laravel\\Cashier\\Subscription), 'pm_1MPT92SCmMZA...')
#3 /var/www/html/app/Http/Controllers/AuthorController.php(72): Laravel\\Cashier\\SubscriptionBuilder->create('pm_1MPT92SCmMZA...')
#4 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): App\\Http\\Controllers\\AuthorController->subscriptionProcess(Object(Illuminate\\Http\\Request))
#5 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(43): Illuminate\\Routing\\Controller->callAction('subscriptionPro...', Array)
#6 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Route.php(260): Illuminate\\Routing\\ControllerDispatcher->dispatch(Object(Illuminate\\Routing\\Route), Object(App\\Http\\Controllers\\AuthorController), 'subscriptionPro...')
#7 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Route.php(205): Illuminate\\Routing\\Route->runController()
#8 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php(727): Illuminate\\Routing\\Route->run()
#9 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): Illuminate\\Routing\\Router->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#10 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#11 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#12 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(50): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#13 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Routing\\Middleware\\SubstituteBindings->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#14 /var/www/html/vendor/laravel/framework/src/Illuminate/Session/Middleware/AuthenticateSession.php(59): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#15 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Session\\Middleware\\AuthenticateSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#16 /var/www/html/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php(44): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#17 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Auth\\Middleware\\Authenticate->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#18 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(78): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#19 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#20 /var/www/html/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#21 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\View\\Middleware\\ShareErrorsFromSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#22 /var/www/html/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(121): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#23 /var/www/html/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(64): Illuminate\\Session\\Middleware\\StartSession->handleStatefulRequest(Object(Illuminate\\Http\\Request), Object(Illuminate\\Session\\Store), Object(Closure))
#24 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Session\\Middleware\\StartSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#25 /var/www/html/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#26 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#27 /var/www/html/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(67): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#28 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Cookie\\Middleware\\EncryptCookies->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#29 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#30 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php(728): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#31 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php(705): Illuminate\\Routing\\Router->runRouteWithinStack(Object(Illuminate\\Routing\\Route), Object(Illuminate\\Http\\Request))
#32 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php(669): Illuminate\\Routing\\Router->runRoute(Object(Illuminate\\Http\\Request), Object(Illuminate\\Routing\\Route))
#33 /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php(658): Illuminate\\Routing\\Router->dispatchToRoute(Object(Illuminate\\Http\\Request))
#34 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(190): Illuminate\\Routing\\Router->dispatch(Object(Illuminate\\Http\\Request))
#35 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): Illuminate\\Foundation\\Http\\Kernel->Illuminate\\Foundation\\Http\\{closure}(Object(Illuminate\\Http\\Request))
#36 /var/www/html/vendor/barryvdh/laravel-debugbar/src/Middleware/InjectDebugbar.php(66): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#37 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Barryvdh\\Debugbar\\Middleware\\InjectDebugbar->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#38 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#39 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php(31): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#40 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\ConvertEmptyStringsToNull->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#41 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#42 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php(40): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#43 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\TrimStrings->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#44 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php(86): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#45 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\PreventRequestsDuringMaintenance->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#46 /var/www/html/vendor/laravel/framework/src/Illuminate/Http/Middleware/HandleCors.php(49): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#47 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Http\\Middleware\\HandleCors->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#48 /var/www/html/vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustProxies.php(39): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#49 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Http\\Middleware\\TrustProxies->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#50 /var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#51 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(165): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#52 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(134): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))
#53 /var/www/html/public/index.php(52): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))
#54 {main}
"}


问:
Install apk file via code forcibly
I have a scenario where I have to install an apk file through code and I dont want the user to have option either install or cancel it. For ex, I want to create an app similar to the android market. In that app, I will display list of my applications and display an install button for each app. When the user clicks the install button, the app should be installed directly without asking the user to install or not. I found a link which have a method installPackage in PackageManager. I am getting compilation error when I use it. It seems that it is remove from the android framework.

Is there nay possibility to do this ?

thanks,

Senthil

ContentLicense: CC BY-SA 3.0

Title: Install apk file via code forcibly


问:
npm info [pkg] succeeds but yarn info [pkg] fails - No package matched your request
I'm using yarn 3 (yarn berry)..

NPM:

```<code>npm info lincd-jsonld
</code>```

works

This URL works: https://registry.yarnpkg.com/lincd-jsonld

so the package exists in the yarn registry..

But

```<code>yarn info lincd-jsonld
</code>```

gives me

```<code>Usage Error: No package matched your request
</code>```

Why?

Body:
I'm using yarn 3 (yarn berry)..

NPM:

npm info lincd-jsonld

works

This URL works: https://registry.yarnpkg.com/lincd-jsonld

so the package exists in the yarn registry..

But

yarn info lincd-jsonld

gives me

Usage Error: No package matched your request

Why?


问:
Postrgres CASE expression
The following script written in Management Studio converts an ID field from

```<code>     AB0002264-11012023 to 23-02264
     AB1117300-10012023 to 23-117300
</code>```

I need to write this in PostrgeSQL but struggling to get close, could someone help please?

```<code>  CASE WHEN LEFT (Field,3) in ('AB1','AC1','AD1','AD1') THEN
       RIGHT(RTRIM(Field),2)
       +
       '-'
       +
       (RIGHT(LEFT(Field,8),6))

       WHEN LEFT(Field,1) = 'A' THEN
       RIGHT(RTRIM(Field),2)
       +
       '-'
       +
       (RIGHT(LEFT(Field,8),5))

       ELSE RIGHT(RTRIM(Field),2)
       +
       '-'
       +
       (RIGHT(LEFT(Field,6),5))

       End as Field
</code>```

Title: Postrgres CASE expression

Body:
The following script written in Management Studio converts an ID field from

     AB0002264-11012023 to 23-02264
     AB1117300-10012023 to 23-117300

I need to write this in PostrgeSQL but struggling to get close, could someone help please?

  CASE WHEN LEFT (Field,3) in ('AB1','AC1','AD1','AD1') THEN
       RIGHT(RTRIM(Field),2)
       +
       '-'
       +
       (RIGHT(LEFT(Field,8),6))

       WHEN LEFT(Field,1) = 'A' THEN
       RIGHT(RTRIM(Field),2)
       +
       '-'
       +
       (RIGHT(LEFT(Field,8),5))

       ELSE RIGHT(RTRIM(Field),2)
       +
       '-'
       +
       (RIGHT(LEFT(Field,6),5))

       End as Field