问:
Is there a way to simplify very long typescript errors when dealing with large, complex types?
I'm working on a typescript project, and I have a quite complicated and nested type system. I'm also working with mobx-state-tree, which makes the types even more complicated, and the errors are unbearably long and cumbersome, since it specifies the type all the way through with all the nested fields.

I mean It looks like this:

```<code>TS2345: Argument of type 'ModelSnapshotType<{ serial: IMaybe<ISimpleType<string>>; vehicle_id: IMaybeNull<IReferenceType<IModelType<{ name: ISimpleType<string>; registration_number: IMaybeNull<ISimpleType<string>>; center_id: ISimpleType<number>; checklists: IArrayType<IReferenceType<IModelType<{ checklist_type: ISimpleType<ChecklistKind>; name: ISimpleType<string>; instructions: IArrayType<IModelType<{ caption: ISimpleType<string>; }, { setCaption(caption: string): void; }, _NotCustomized, _NotCustomized>>; } & { id: ISimpleType<number>; }, { readonly snapshot: ModelSnapshotType<{}>; } & { isEditing: boolean; initialSnapshot: ModelSnapshotType<{}>; } & { setIsEditing(isEditing: boolean): void; } & { readonly isDirty: boolean; } & { discardChanges(): void; } & { readonly checklistKind: ChecklistKind; } & { readonly checklistKindDisplayName: string; } & { setName(name: string): void; setChecklistKind(kind: ChecklistKind): void; addStep(): void; deleteStep(stepIndex: number): void; }, _NotCustomized, _NotCustomized>>>; } & { id: ISimpleType<number>; }, { readonly registrationNumber: string | null; } & { readonly launchpadOpenChecklist: ({ checklist_type: ChecklistKind; name: string; instructions: IMSTArray<IModelType<{ caption: ISimpleType<string>; }, { setCaption(caption: string): void; }, _NotCustomized, _NotCustomized>> & IStateTreeNode<IArrayType<IModelType<{ caption: ISimpleType<string>; }, { setCaption(caption: string): void; }, _NotCustomized, _NotCustomized>>>; id: number; } & NonEmptyObject & { readonly snapshot: ModelSnapshotType<{}>; } & { isEditing: boolean; initialSnapshot: ModelSnapshotType<{}>; } & { setIsEditing(isEditing: boolean): void; } & { readonly isDirty: boolean; } & { discardChanges(): void; } & { readonly checklistKind: ChecklistKind; } & { readonly checklistKindDisplayName: string; } & { setName(name: string): void; setChecklistKind(kind: ChecklistKind): void; addStep(): void; deleteStep(stepIndex: number): void; } & IStateTreeNode<IModelType<{ checklist_type: ISimpleType<ChecklistKind>; name: ISimpleType<string>; instructions: IArrayType<IModelType<{ caption: ISimpleType<string>; }, { setCaption(caption: string): void; }, _NotCustomized, _NotCustomized>>; } & { id: ISimpleType<number>; }, { readonly snapshot: ModelSnapshotType<{}>; } & { isEditing: boolean; initialSnapshot: ModelSnapshotType<{}>; } & { setIsEditing(isEditing: boolean): void; } & { readonly isDirty: boolean; } & { discardChanges(): void; } & { readonly checklistKind: ChecklistKind; } & { readonly checklistKindDisplayName: string; } & { setName(name: string): void; setChecklistKind(kind: ChecklistKind): void; addStep(): void; .....
</code>```

Is there a way to make typescript not to expand the types in the error all the way, but just focus on the problematic part? Or maybe just use my types from the code, and not to expand the nested types recursively  ?

Body:
I'm working on a typescript project, and I have a quite complicated and nested type system. I'm also working with mobx-state-tree, which makes the types even more complicated, and the errors are unbearably long and cumbersome, since it specifies the type all the way through with all the nested fields.

I mean It looks like this:

TS2345: Argument of type 'ModelSnapshotType<{ serial: IMaybe<ISimpleType<string>>; vehicle_id: IMaybeNull<IReferenceType<IModelType<{ name: ISimpleType<string>; registration_number: IMaybeNull<ISimpleType<string>>; center_id: ISimpleType<number>; checklists: IArrayType<IReferenceType<IModelType<{ checklist_type: ISimpleType<ChecklistKind>; name: ISimpleType<string>; instructions: IArrayType<IModelType<{ caption: ISimpleType<string>; }, { setCaption(caption: string): void; }, _NotCustomized, _NotCustomized>>; } & { id: ISimpleType<number>; }, { readonly snapshot: ModelSnapshotType<{}>; } & { isEditing: boolean; initialSnapshot: ModelSnapshotType<{}>; } & { setIsEditing(isEditing: boolean): void; } & { readonly isDirty: boolean; } & { discardChanges(): void; } & { readonly checklistKind: ChecklistKind; } & { readonly checklistKindDisplayName: string; } & { setName(name: string): void; setChecklistKind(kind: ChecklistKind): void; addStep(): void; deleteStep(stepIndex: number): void; }, _NotCustomized, _NotCustomized>>>; } & { id: ISimpleType<number>; }, { readonly registrationNumber: string | null; } & { readonly launchpadOpenChecklist: ({ checklist_type: ChecklistKind; name: string; instructions: IMSTArray<IModelType<{ caption: ISimpleType<string>; }, { setCaption(caption: string): void; }, _NotCustomized, _NotCustomized>> & IStateTreeNode<IArrayType<IModelType<{ caption: ISimpleType<string>; }, { setCaption(caption: string): void; }, _NotCustomized, _NotCustomized>>>; id: number; } & NonEmptyObject & { readonly snapshot: ModelSnapshotType<{}>; } & { isEditing: boolean; initialSnapshot: ModelSnapshotType<{}>; } & { setIsEditing(isEditing: boolean): void; } & { readonly isDirty: boolean; } & { discardChanges(): void; } & { readonly checklistKind: ChecklistKind; } & { readonly checklistKindDisplayName: string; } & { setName(name: string): void; setChecklistKind(kind: ChecklistKind): void; addStep(): void; deleteStep(stepIndex: number): void; } & IStateTreeNode<IModelType<{ checklist_type: ISimpleType<ChecklistKind>; name: ISimpleType<string>; instructions: IArrayType<IModelType<{ caption: ISimpleType<string>; }, { setCaption(caption: string): void; }, _NotCustomized, _NotCustomized>>; } & { id: ISimpleType<number>; }, { readonly snapshot: ModelSnapshotType<{}>; } & { isEditing: boolean; initialSnapshot: ModelSnapshotType<{}>; } & { setIsEditing(isEditing: boolean): void; } & { readonly isDirty: boolean; } & { discardChanges(): void; } & { readonly checklistKind: ChecklistKind; } & { readonly checklistKindDisplayName: string; } & { setName(name: string): void; setChecklistKind(kind: ChecklistKind): void; addStep(): void; .....

Is there a way to make typescript not to expand the types in the error all the way, but just focus on the problematic part? Or maybe just use my types from the code, and not to expand the nested types recursively  ?


来源: stackexchange

问:
Can’t get NSSharingServicePicker to work for sharing a CKShare
I’m trying to share CKRecords from my app’s CloudKit database using a CKShare from an NSSharingServicePicker, but the picker doesn’t show any sharing services. I’m pretty much doing exactly what the code samples in the WWDC22 video Enhance collaboration experiences with Messages show:

```<code>let itemProvider = NSItemProvider()
if let existingShare {
    itemProvider.registerCKShare(existingShare, container: container)
} else {
    itemProvider.registerCKShare(container: container, preparationHandler: {
        return try await createAndSaveNewCKShare()
    })
}
</code>```

Then, I add some metadata as described in the video:

```<code>let activityItem = NSPreviewRepresentingActivityItem(
    item: itemProvider,
    title: "The title",
    imageProvider: nil, // TODO: Quick Look preview image
    iconProvider: .init(object: NSApp.applicationIconImage)
)
</code>```

Finally, I create the picker and show it:

```<code>let picker = NSSharingServicePicker(items: [activityItem])
picker.show(relativeTo: .zero, of: view, preferredEdge: .minY))
</code>```

What I then get is a sharing service picker that only shows my recent contacts, but not a single sharing service below that. The metadata is there, i.e. the title and app icon show up:

What am I doing wrong here?

I’m pretty confident that most of the code is correct because it works fine on iOS. There, I use the same itemProvider as above, but present the share UI like this, which is pretty much the same:

```<code>let configuration = UIActivityItemsConfiguration(itemProviders: [itemProvider])
configuration.perItemMetadataProvider = { _, key in
    switch key {
    case .linkPresentationMetadata:
        let metadata = LPLinkMetadata()
        metadata.title = title
        metadata.imageProvider = nil // TODO: Quick Look preview image
        metadata.iconProvider = nil // TODO: App icon?
    default:
        return nil
    }
}

let viewController = UIActivityViewController(activityItemsConfiguration: configuration)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I’m trying to share CKRecords from my app’s CloudKit database using a CKShare from an NSSharingServicePicker, but the picker doesn’t show any sharing services. I’m pretty much doing exactly what the code samples in the WWDC22 video Enhance collaboration experiences with Messages show:

let itemProvider = NSItemProvider()
if let existingShare {
    itemProvider.registerCKShare(existingShare, container: container)
} else {
    itemProvider.registerCKShare(container: container, preparationHandler: {
        return try await createAndSaveNewCKShare()
    })
}

Then, I add some metadata as described in the video:

let activityItem = NSPreviewRepresentingActivityItem(
    item: itemProvider,
    title: "The title",
    imageProvider: nil, // TODO: Quick Look preview image
    iconProvider: .init(object: NSApp.applicationIconImage)
)

Finally, I create the picker and show it:

let picker = NSSharingServicePicker(items: [activityItem])
picker.show(relativeTo: .zero, of: view, preferredEdge: .minY))

What I then get is a sharing service picker that only shows my recent contacts, but not a single sharing service below that. The metadata is there, i.e. the title and app icon show up:

What am I doing wrong here?

I’m pretty confident that most of the code is correct because it works fine on iOS. There, I use the same itemProvider as above, but present the share UI like this, which is pretty much the same:

let configuration = UIActivityItemsConfiguration(itemProviders: [itemProvider])
configuration.perItemMetadataProvider = { _, key in
    switch key {
    case .linkPresentationMetadata:
        let metadata = LPLinkMetadata()
        metadata.title = title
        metadata.imageProvider = nil // TODO: Quick Look preview image
        metadata.iconProvider = nil // TODO: App icon?
    default:
        return nil
    }
}

let viewController = UIActivityViewController(activityItemsConfiguration: configuration)


问:
GGplot2 not drawing trendline in R
All,

I have a fairly simple data frame organized with year and temperature in the first two columns:

A snippet:

```<code>>atemp_sum
   year     mean        anom
2  2007 20.39830  0.17591432
3  2008 19.89493 -0.32744991
4  2009 19.43331 -0.78907475
5  2010 19.07625 -1.14613367
6  2011 20.07615 -0.14623128
7  2012 20.00268 -0.21970282
</code>```

I am trying to create a ggplot of the data with a trend line. I have tried this several different ways: running the lm separately and using geom_abline() and doing it directly in ggplot using geom_smooth. The results are the same. It draws the points, but no line and does not give me any error.

The code I'm running is here:

```<code>ggplot(atemp_sum, aes(x = year, y = mean)) + labs(x = "Year", y = "Temperature C") + geom_point()+ geom_smooth(method=lm, se=FALSE, col='red', size=2)
</code>```

The results I am getting in the plot:

plot image

I clearly am expecting a trend line in red to show the positive trend in temperatures.

Any help is appreciated!

Title: GGplot2 not drawing trendline in R

Body:
All,

I have a fairly simple data frame organized with year and temperature in the first two columns:

A snippet:

>atemp_sum
   year     mean        anom
2  2007 20.39830  0.17591432
3  2008 19.89493 -0.32744991
4  2009 19.43331 -0.78907475
5  2010 19.07625 -1.14613367
6  2011 20.07615 -0.14623128
7  2012 20.00268 -0.21970282

I am trying to create a ggplot of the data with a trend line. I have tried this several different ways: running the lm separately and using geom_abline() and doing it directly in ggplot using geom_smooth. The results are the same. It draws the points, but no line and does not give me any error.

The code I'm running is here:

ggplot(atemp_sum, aes(x = year, y = mean)) + labs(x = "Year", y = "Temperature C") + geom_point()+ geom_smooth(method=lm, se=FALSE, col='red', size=2)

The results I am getting in the plot:

plot image

I clearly am expecting a trend line in red to show the positive trend in temperatures.

Any help is appreciated!


问:
Using Spring Statemachine we have difficulty changing some statuses
Using Spring Statemachine I encountered a problem when changing the status:
PENDING is the initial status and we have a problem when changing from ARRIVED -> IN_PROGRESS and IN_PROGRESS -> COMPLETED.

It changes from ARRIVED to IN_PROGRESS only when it changes from PENDING to IN_PROGRESS.
We can change from IN_PROGRESS to COMPLETED, only if it changes from PENDING to COMPLETED.

```<code>/**
 * allow only the following transitions:
 *
 * PENDING -> WAITING or ARRIVED or NO_SHOW or USER_CANCELLED or TEAM_CANCELLED
 * WAITING -> ARRIVED or NO_SHOW
 * ARRIVED -> IN_PROGRESS or USER_CANCELLED or TEAM_CANCELLED
 * IN_PROGRESS ->  COMPLETED or USER_CANCELLED or TEAM_CANCELLED
 * COMPLETED -> no transition
 * USER_CANCELLED -> no transition
 * TEAM_CANCELLED -> no transition
 * NO_SHOW -> no transition
 */
</code>```

possibly the configuration is not written correctly, can someone help us?

```<code>public void configure(final StateMachineStateConfigurer<Appointment.Status, Appointment.Status> states) throws Exception {
    states
            .withStates()
            .initial(Appointment.Status.PENDING)
            .states(EnumSet.allOf(Appointment.Status.class))
            .end(Appointment.Status.COMPLETED)
            .end(Appointment.Status.USER_CANCELLED)
            .end(Appointment.Status.TEAM_CANCELLED)
            .end(Appointment.Status.NO_SHOW);
}
</code>```
```<code>public void configure(final StateMachineTransitionConfigurer<Appointment.Status, Appointment.Status> transitions) throws Exception {
    transitions
            .withExternal()
            .source(Appointment.Status.PENDING)
            .target(Appointment.Status.WAITING)
            .event(Appointment.Status.WAITING)
            .and()

            .withExternal()
            .source(Appointment.Status.PENDING)
            .target(Appointment.Status.ARRIVED)
            .event(Appointment.Status.ARRIVED)
            .and()

            .withExternal()
            .source(Appointment.Status.PENDING)
            .target(Appointment.Status.NO_SHOW)
            .event(Appointment.Status.NO_SHOW)
            .and()

            .withExternal()
            .source(Appointment.Status.PENDING)
            .target(Appointment.Status.USER_CANCELLED)
            .event(Appointment.Status.USER_CANCELLED)
            .and()

            .withExternal()
            .source(Appointment.Status.PENDING)
            .target(Appointment.Status.TEAM_CANCELLED)
            .event(Appointment.Status.TEAM_CANCELLED)
            .and()

            .withExternal()
            .source(Appointment.Status.WAITING)
            .target(Appointment.Status.ARRIVED)
            .event(Appointment.Status.ARRIVED)
            .and()

            .withExternal()
            .source(Appointment.Status.WAITING)
            .target(Appointment.Status.NO_SHOW)
            .event(Appointment.Status.NO_SHOW)
            .and()

            .withExternal()
            .source(Appointment.Status.ARRIVED)
            .target(Appointment.Status.IN_PROGRESS)
            .event(Appointment.Status.IN_PROGRESS)
            .and()

            .withExternal()
            .source(Appointment.Status.ARRIVED)
            .target(Appointment.Status.USER_CANCELLED)
            .event(Appointment.Status.USER_CANCELLED)
            .and()

            .withExternal()
            .source(Appointment.Status.ARRIVED)
            .target(Appointment.Status.TEAM_CANCELLED)
            .event(Appointment.Status.TEAM_CANCELLED)
            .and()

            .withExternal()
            .source(Appointment.Status.IN_PROGRESS)
            .target(Appointment.Status.COMPLETED)
            .event(Appointment.Status.COMPLETED)
            .and()

            .withExternal()
            .source(Appointment.Status.IN_PROGRESS)
            .target(Appointment.Status.USER_CANCELLED)
            .event(Appointment.Status.USER_CANCELLED)
            .and()

            .withExternal()
            .source(Appointment.Status.IN_PROGRESS)
            .target(Appointment.Status.TEAM_CANCELLED)
            .event(Appointment.Status.TEAM_CANCELLED);
}
</code>```

Body:
Using Spring Statemachine I encountered a problem when changing the status:
PENDING is the initial status and we have a problem when changing from ARRIVED -> IN_PROGRESS and IN_PROGRESS -> COMPLETED.

It changes from ARRIVED to IN_PROGRESS only when it changes from PENDING to IN_PROGRESS.
We can change from IN_PROGRESS to COMPLETED, only if it changes from PENDING to COMPLETED.

/**
 * allow only the following transitions:
 *
 * PENDING -> WAITING or ARRIVED or NO_SHOW or USER_CANCELLED or TEAM_CANCELLED
 * WAITING -> ARRIVED or NO_SHOW
 * ARRIVED -> IN_PROGRESS or USER_CANCELLED or TEAM_CANCELLED
 * IN_PROGRESS ->  COMPLETED or USER_CANCELLED or TEAM_CANCELLED
 * COMPLETED -> no transition
 * USER_CANCELLED -> no transition
 * TEAM_CANCELLED -> no transition
 * NO_SHOW -> no transition
 */

possibly the configuration is not written correctly, can someone help us?

public void configure(final StateMachineStateConfigurer<Appointment.Status, Appointment.Status> states) throws Exception {
    states
            .withStates()
            .initial(Appointment.Status.PENDING)
            .states(EnumSet.allOf(Appointment.Status.class))
            .end(Appointment.Status.COMPLETED)
            .end(Appointment.Status.USER_CANCELLED)
            .end(Appointment.Status.TEAM_CANCELLED)
            .end(Appointment.Status.NO_SHOW);
}

public void configure(final StateMachineTransitionConfigurer<Appointment.Status, Appointment.Status> transitions) throws Exception {
    transitions
            .withExternal()
            .source(Appointment.Status.PENDING)
            .target(Appointment.Status.WAITING)
            .event(Appointment.Status.WAITING)
            .and()

            .withExternal()
            .source(Appointment.Status.PENDING)
            .target(Appointment.Status.ARRIVED)
            .event(Appointment.Status.ARRIVED)
            .and()

            .withExternal()
            .source(Appointment.Status.PENDING)
            .target(Appointment.Status.NO_SHOW)
            .event(Appointment.Status.NO_SHOW)
            .and()

            .withExternal()
            .source(Appointment.Status.PENDING)
            .target(Appointment.Status.USER_CANCELLED)
            .event(Appointment.Status.USER_CANCELLED)
            .and()

            .withExternal()
            .source(Appointment.Status.PENDING)
            .target(Appointment.Status.TEAM_CANCELLED)
            .event(Appointment.Status.TEAM_CANCELLED)
            .and()

            .withExternal()
            .source(Appointment.Status.WAITING)
            .target(Appointment.Status.ARRIVED)
            .event(Appointment.Status.ARRIVED)
            .and()

            .withExternal()
            .source(Appointment.Status.WAITING)
            .target(Appointment.Status.NO_SHOW)
            .event(Appointment.Status.NO_SHOW)
            .and()

            .withExternal()
            .source(Appointment.Status.ARRIVED)
            .target(Appointment.Status.IN_PROGRESS)
            .event(Appointment.Status.IN_PROGRESS)
            .and()

            .withExternal()
            .source(Appointment.Status.ARRIVED)
            .target(Appointment.Status.USER_CANCELLED)
            .event(Appointment.Status.USER_CANCELLED)
            .and()

            .withExternal()
            .source(Appointment.Status.ARRIVED)
            .target(Appointment.Status.TEAM_CANCELLED)
            .event(Appointment.Status.TEAM_CANCELLED)
            .and()

            .withExternal()
            .source(Appointment.Status.IN_PROGRESS)
            .target(Appointment.Status.COMPLETED)
            .event(Appointment.Status.COMPLETED)
            .and()

            .withExternal()
            .source(Appointment.Status.IN_PROGRESS)
            .target(Appointment.Status.USER_CANCELLED)
            .event(Appointment.Status.USER_CANCELLED)
            .and()

            .withExternal()
            .source(Appointment.Status.IN_PROGRESS)
            .target(Appointment.Status.TEAM_CANCELLED)
            .event(Appointment.Status.TEAM_CANCELLED);
}


问:
Kibana 8.5.3: Unable to download CSV from dashboard / visualizations on
None of my Kibana dashboard or viz have a "Download to CVS" option showing up in 8.5.3. What am I missing? Below is my setup:

I've installed the 8.5.3 stack of elasticsearch and kibana from this official doc.

My kibana has the following config:

```<code># Default Kibana configuration for docker target
server.host: "0.0.0.0"
monitoring.ui.container.elasticsearch.enabled: true

xpack.security.authc.providers:
    basic.basic1:
        order: 0
    anonymous.anonymous1:
        order: 1
        credentials:
            username: "${KIBANA_ANON_USERNAME}"
            password: "${KIBANA_ANON_PASSWORD}"

xpack.reporting.roles.enabled: false

</code>```

I've set up a the target user as per this doc:

User Role:

```<code>curl -s -X PUT --cacert config/certs/ca/ca.crt -u "${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}" -H "Content-Type: application/json" http://elasticsearch-1:9200/_security/user/"${KIBANA_ANON_USERNAME}"
-d '{
      "password" : "${KIBANA_ANON_PASSWORD}",
      "roles" : [ "reporting_user_role" ]
}'
</code>```

User Profile:

```<code>curl -s -X PUT --cacert config/certs/ca/ca.crt -u "${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}" -H "kbn-xsrf: reporting" -H "Content-Type: application/json" http://kibana:5601/api/security/role/anon_user_role -d '{
    "name": "custom_reporting_role",
    "metadata": {},
    "transient_metadata": {
        "enabled": true
    },
    "elasticsearch": {
        "cluster": [],
        "indices": [
            {
                "names": ["why*"],
                "privileges": ["read", "view_index_metadata", "all"],
                "allow_restricted_indices": false
            }
        ],
        "run_as": []
    },
    "kibana": [
        {
            "base": [],
            "feature": {
                "dashboard": ["minimal_read", "generate_report", "download_csv_report"],
                "discover": ["minimal_read", "generate_report"],
                "canvas": ["minimal_read", "generate_report"],
                "visualize": ["minimal_read", "generate_report"]
            },
            "spaces": ["*"]
        }
    ]
}'

</code>```

I'm unable to view a "Download to CSV" in any of my viz / dashboards. What am I missing?

Body:
None of my Kibana dashboard or viz have a "Download to CVS" option showing up in 8.5.3. What am I missing? Below is my setup:

I've installed the 8.5.3 stack of elasticsearch and kibana from this official doc.

My kibana has the following config:

# Default Kibana configuration for docker target
server.host: "0.0.0.0"
monitoring.ui.container.elasticsearch.enabled: true

xpack.security.authc.providers:
    basic.basic1:
        order: 0
    anonymous.anonymous1:
        order: 1
        credentials:
            username: "${KIBANA_ANON_USERNAME}"
            password: "${KIBANA_ANON_PASSWORD}"

xpack.reporting.roles.enabled: false

I've set up a the target user as per this doc:

User Role:

curl -s -X PUT --cacert config/certs/ca/ca.crt -u "${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}" -H "Content-Type: application/json" http://elasticsearch-1:9200/_security/user/"${KIBANA_ANON_USERNAME}"
-d '{
      "password" : "${KIBANA_ANON_PASSWORD}",
      "roles" : [ "reporting_user_role" ]
}'

User Profile:

curl -s -X PUT --cacert config/certs/ca/ca.crt -u "${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}" -H "kbn-xsrf: reporting" -H "Content-Type: application/json" http://kibana:5601/api/security/role/anon_user_role -d '{
    "name": "custom_reporting_role",
    "metadata": {},
    "transient_metadata": {
        "enabled": true
    },
    "elasticsearch": {
        "cluster": [],
        "indices": [
            {
                "names": ["why*"],
                "privileges": ["read", "view_index_metadata", "all"],
                "allow_restricted_indices": false
            }
        ],
        "run_as": []
    },
    "kibana": [
        {
            "base": [],
            "feature": {
                "dashboard": ["minimal_read", "generate_report", "download_csv_report"],
                "discover": ["minimal_read", "generate_report"],
                "canvas": ["minimal_read", "generate_report"],
                "visualize": ["minimal_read", "generate_report"]
            },
            "spaces": ["*"]
        }
    ]
}'

I'm unable to view a "Download to CSV" in any of my viz / dashboards. What am I missing?


问:
@BelongsTo (or any others associations) to a foreign Model in another database
I'm using @nestjs/sequelize and i'm looking to achieve a simple request to retrieve datas from a foreign Model like this :
Game.findAll({include: Gamemode});

So i have 2 databases :

board schema with Game Model

queue schema with Gamemode Model

So this is my code :

I've been able to create a @ForeignKey between theses 2 remotes tables :
So my games table from board schema has an id_gamemode based on id from gamemodes table of my queue schema.

The model for my table games look like this :

```<code>@Table({ tableName: 'games', timestamps: false })
export class Game extends Model<Game> {
    @Column({
        allowNull: false,
        type: UUID,
        defaultValue: UUIDV4,
        primaryKey: false,
        autoIncrement: false,
        get() {
            const rawValue = this.getDataValue('gamemode_id');
            return rawValue ? rawValue.toString() : null;
        },
        references: {
            model: {
                tableName: "gamesmodes",
                schema: "queue"
            },
            key: 'id'
        }
    })
    @ForeignKey(() => Gamemode)
    gamemode_id: string;

}
</code>```

Now i'm trying to get a reference to my Gamemode Model to create an easy sequelize association

```<code>    @BelongsTo(() => Gamemode, { foreignKey: 'my_ibfk_1', targetKey: 'id' } )
    gamemode: Gamemode;
</code>```

But on compilation, i have this error :
Error: Gamemode has not been defined

I think it's logic : my Gamemode is not defined in my board database ; it's defined on my secondary database queue.

But with NestJS & Sequelize, can i create this relation between theses 2 "remote" models ?

Someone has an idea please ?

Regards

Body:
I'm using @nestjs/sequelize and i'm looking to achieve a simple request to retrieve datas from a foreign Model like this :
Game.findAll({include: Gamemode});

So i have 2 databases :

board schema with Game Model

queue schema with Gamemode Model

So this is my code :

I've been able to create a @ForeignKey between theses 2 remotes tables :
So my games table from board schema has an id_gamemode based on id from gamemodes table of my queue schema.

The model for my table games look like this :

@Table({ tableName: 'games', timestamps: false })
export class Game extends Model<Game> {
    @Column({
        allowNull: false,
        type: UUID,
        defaultValue: UUIDV4,
        primaryKey: false,
        autoIncrement: false,
        get() {
            const rawValue = this.getDataValue('gamemode_id');
            return rawValue ? rawValue.toString() : null;
        },
        references: {
            model: {
                tableName: "gamesmodes",
                schema: "queue"
            },
            key: 'id'
        }
    })
    @ForeignKey(() => Gamemode)
    gamemode_id: string;

}

Now i'm trying to get a reference to my Gamemode Model to create an easy sequelize association

    @BelongsTo(() => Gamemode, { foreignKey: 'my_ibfk_1', targetKey: 'id' } )
    gamemode: Gamemode;

But on compilation, i have this error :
Error: Gamemode has not been defined

I think it's logic : my Gamemode is not defined in my board database ; it's defined on my secondary database queue.

But with NestJS & Sequelize, can i create this relation between theses 2 "remote" models ?

Someone has an idea please ?

Regards


问:
Fetching form input values from .ts file
I want to create a form with input -username and password with a  button. The next page will load only if the user has given the correct username and password which I want to mention in .ts file in my angular project. How can I do it? I am trying to use ngModel but I don't know where I'm going wrong.

I wanted an admin login page which will allow to load admin dashboard only when right username and password are given in the input fields of login page validated by the values given in .ts file of that component.


问:
Prevent unauthenticated access to Laravel Nova
I've installed Laravel Nova and have it working 100%, however I can login in to production without having to authenticate?

if I go to mydomain.com/admin/login (I have 'path' => '/admin/login'; set in my config/nova.php) it takes me straight to the dashboard and I see 'Nova User' in the top right hand corner, it doesn't ask me for the username and password. However, if I go to mydomain/admin/login/login I'm asked for U and P, I login with my user credentiails, it takes me to the dashboard and shows my name in the top right hand corner correctly.

How do I prevent the non-authenticated access? This is what I have in the gate() method of my NovaServiceProvider (this is just a test email, I have my real email address in the live code): -

```<code>Gate::define('viewNova', function ($user) {
    return in_array($user->email, [
        'myemail@domain.com'
    ]);
});
</code>```

I have updated the gate, cleared the cache and config.

Body:
I've installed Laravel Nova and have it working 100%, however I can login in to production without having to authenticate?

if I go to mydomain.com/admin/login (I have 'path' => '/admin/login'; set in my config/nova.php) it takes me straight to the dashboard and I see 'Nova User' in the top right hand corner, it doesn't ask me for the username and password. However, if I go to mydomain/admin/login/login I'm asked for U and P, I login with my user credentiails, it takes me to the dashboard and shows my name in the top right hand corner correctly.

How do I prevent the non-authenticated access? This is what I have in the gate() method of my NovaServiceProvider (this is just a test email, I have my real email address in the live code): -

Gate::define('viewNova', function ($user) {
    return in_array($user->email, [
        'myemail@domain.com'
    ]);
});

I have updated the gate, cleared the cache and config.


问:
linkedin media upload using curl command as binary data
I am trying to post media to linkedin using curl command, how can i pass media as binary data instead of passing filepath?</p>
```<code> let header = '';
        if (fileType === 'image') {
          header = `Authorization: Bearer ${token}`;
        } else if (fileType === 'video') {
          header = 'Content-Type:application/octet-stream';
        }
const curlCommand = `curl -i --upload-file ${media.filepath} -H '${header}' '${url}'`;
    child.exec(curlCommand, (error, stdout, stderr) => {
          if (error) {
            console.log(`error: ${error.message}`);
            return false;
          }
          if (stderr) {
            return true;
          }
    });
</code>```

Body:
I am trying to post media to linkedin using curl command, how can i pass media as binary data instead of passing filepath?

 let header = '';
        if (fileType === 'image') {
          header = `Authorization: Bearer ${token}`;
        } else if (fileType === 'video') {
          header = 'Content-Type:application/octet-stream';
        }
const curlCommand = `curl -i --upload-file ${media.filepath} -H '${header}' '${url}'`;
    child.exec(curlCommand, (error, stdout, stderr) => {
          if (error) {
            console.log(`error: ${error.message}`);
            return false;
          }
          if (stderr) {
            return true;
          }
    });


问:
How to markForCheck() all components after language changed?
In an application with several components using OnPush strategy, I need to detect changes in all components after language is changed on runtime (using ngx-translate library).

Is there a way to force change detection on all children components of the root component?

Other working solutions I have used:

Listen to language changes on each component that uses OnPush and markForCheck() the component. Requires boilerplate in each affected component.

Use an async like pipe for translations which markForCheck() on translation change. Each component can have many literals, so markForCheck() is called multiple times for same component (but I assume detection cycle is run once). I think TranslatePipe works this way.

If forcing change detection for all components is not possible, is it more advisable using solution 1, 2 or is there another option?


问:
java GUI. keep getting loadImage(): Error: Image at images/f.png could not be found
i am working on hangman game project and i think im done with the code but everytime i load the game it gives me this error which i wrote when it cannot load the images file. im not sure if im doing something wrong to load the directory for the images file. here is the code...
this is ofcourse one of 5 classes but i want to be sure if im making a mistake loading the directory or is it something else. Also if u have any suggestions on how to improve this code im open to that..

```<code>import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JLabel;

/**
 * A tile representing a letter to be guessed during a game.
 * @author Jeff A.
 */
public class letterBlocks extends JLabel
{
    /**
     * Add a TileListener
     * @param l The MouseListener to attach as a TileListener
     */
    public void addTileListener(MouseListener l)
    {
        tileListener = l;
        addMouseListener(tileListener);
    }
    /**
     * The directory containing the letter images.
     */
    private final String IMAGE_DIRECTORY;

    /**
     * The type of image (.jpg, .png, etc. to include the period).
     */
    private final String IMAGE_TYPE;

    /**
     * The images of the letters in the window.
     */
    private final char IMAGE_LETTER;
    /**
     * The preferred width of the tiles.
     */
    private final int PREFERRED_WIDTH;

    /**
     * The preferred height of the tiles.
     */
    private final int PREFERRED_HEIGHT;

    /**
     * The current path of the current image.
     */
    private String path;

    /**
     * The current image being displayed.
     */
    private BufferedImage image;

    /**
     * A custom MouseListener from the GameBoard class to change the tiles on
     * a click.
     */
    private MouseListener tileListener;

    /**
     * The default constructor.
     */
    public letterBlocks() { this('A', "C:\\Users\\omare\\Dropbox\\My PC (LAPTOP-AGJUFI2M)\\Desktop\\Images", ".png"); }

    /**
     * Creates a new LetterTile given the letter to be displayed, the directory
     * of the letter image series, and the image type.
     * @param imageLetter The letter to be displayed on the tile.
     * @param imageDirectory The directory holding the letter images.
     * @param imageType The type of the letter images.
     */
    public letterBlocks(char imageLetter, String imageDirectory, String imageType)
    {
        IMAGE_LETTER = imageLetter;
        IMAGE_DIRECTORY = imageDirectory;
        IMAGE_TYPE = imageType;

        PREFERRED_WIDTH = PREFERRED_HEIGHT = 50;

        setPreferredSize(new Dimension(PREFERRED_WIDTH, PREFERRED_HEIGHT));
        path = IMAGE_DIRECTORY + IMAGE_LETTER + IMAGE_TYPE;
        image = loadImage(path);
    }

    /**
     * Changes the tile's appearance and removes the mouse listener to prevent
     * the tile from being clicked again.
     * @return The tile's letter.
     */
    public char guess()
    {
        loadNewImage("guessed");
        removeTileListener();
        return IMAGE_LETTER;
    }

    /**
     * Loads a new image in the hangman image series.
     * @param suffix The suffix of the image name.
     */
    private void loadNewImage(String suffix)
    {
        path = IMAGE_DIRECTORY + IMAGE_LETTER + "_" + suffix + IMAGE_TYPE;
        image = loadImage(path);
        repaint();
    }

    /**
     * Remove the tile's TileListener.
     */
    public void removeTileListener() { removeMouseListener(tileListener); }

    /**
     * Loads an image from a file.
     * @param imagePath The path to load an image from.
     * @return A BufferedImage object on success, exits on failure.
     */
    private BufferedImage loadImage(String imagePath)
    {
        BufferedImage img = null;

        try
        {
            img = ImageIO.read(new File(imagePath));
        }

        catch (IOException ex)
        {
            System.err.println("loadImage(): Error: Image at "
                    + imagePath + " could not be found");
            System.exit(1);
        }
        return img;
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawImage(image,
                0,
                0,
                PREFERRED_WIDTH,
                PREFERRED_HEIGHT,
                null);
    }
}
</code>```

i tried to put the images in different files and that didnt work

Body:
i am working on hangman game project and i think im done with the code but everytime i load the game it gives me this error which i wrote when it cannot load the images file. im not sure if im doing something wrong to load the directory for the images file. here is the code...
this is ofcourse one of 5 classes but i want to be sure if im making a mistake loading the directory or is it something else. Also if u have any suggestions on how to improve this code im open to that..

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JLabel;

/**
 * A tile representing a letter to be guessed during a game.
 * @author Jeff A.
 */
public class letterBlocks extends JLabel
{
    /**
     * Add a TileListener
     * @param l The MouseListener to attach as a TileListener
     */
    public void addTileListener(MouseListener l)
    {
        tileListener = l;
        addMouseListener(tileListener);
    }
    /**
     * The directory containing the letter images.
     */
    private final String IMAGE_DIRECTORY;

    /**
     * The type of image (.jpg, .png, etc. to include the period).
     */
    private final String IMAGE_TYPE;

    /**
     * The images of the letters in the window.
     */
    private final char IMAGE_LETTER;
    /**
     * The preferred width of the tiles.
     */
    private final int PREFERRED_WIDTH;

    /**
     * The preferred height of the tiles.
     */
    private final int PREFERRED_HEIGHT;

    /**
     * The current path of the current image.
     */
    private String path;

    /**
     * The current image being displayed.
     */
    private BufferedImage image;

    /**
     * A custom MouseListener from the GameBoard class to change the tiles on
     * a click.
     */
    private MouseListener tileListener;

    /**
     * The default constructor.
     */
    public letterBlocks() { this('A', "C:\\Users\\omare\\Dropbox\\My PC (LAPTOP-AGJUFI2M)\\Desktop\\Images", ".png"); }

    /**
     * Creates a new LetterTile given the letter to be displayed, the directory
     * of the letter image series, and the image type.
     * @param imageLetter The letter to be displayed on the tile.
     * @param imageDirectory The directory holding the letter images.
     * @param imageType The type of the letter images.
     */
    public letterBlocks(char imageLetter, String imageDirectory, String imageType)
    {
        IMAGE_LETTER = imageLetter;
        IMAGE_DIRECTORY = imageDirectory;
        IMAGE_TYPE = imageType;

        PREFERRED_WIDTH = PREFERRED_HEIGHT = 50;

        setPreferredSize(new Dimension(PREFERRED_WIDTH, PREFERRED_HEIGHT));
        path = IMAGE_DIRECTORY + IMAGE_LETTER + IMAGE_TYPE;
        image = loadImage(path);
    }

    /**
     * Changes the tile's appearance and removes the mouse listener to prevent
     * the tile from being clicked again.
     * @return The tile's letter.
     */
    public char guess()
    {
        loadNewImage("guessed");
        removeTileListener();
        return IMAGE_LETTER;
    }

    /**
     * Loads a new image in the hangman image series.
     * @param suffix The suffix of the image name.
     */
    private void loadNewImage(String suffix)
    {
        path = IMAGE_DIRECTORY + IMAGE_LETTER + "_" + suffix + IMAGE_TYPE;
        image = loadImage(path);
        repaint();
    }

    /**
     * Remove the tile's TileListener.
     */
    public void removeTileListener() { removeMouseListener(tileListener); }

    /**
     * Loads an image from a file.
     * @param imagePath The path to load an image from.
     * @return A BufferedImage object on success, exits on failure.
     */
    private BufferedImage loadImage(String imagePath)
    {
        BufferedImage img = null;

        try
        {
            img = ImageIO.read(new File(imagePath));
        }

        catch (IOException ex)
        {
            System.err.println("loadImage(): Error: Image at "
                    + imagePath + " could not be found");
            System.exit(1);
        }
        return img;
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawImage(image,
                0,
                0,
                PREFERRED_WIDTH,
                PREFERRED_HEIGHT,
                null);
    }
}

i tried to put the images in different files and that didnt work


问:
Is there a way to detect if my app is cloned in sandbox mode?
Im trying to add additional checks for detecting if the app is cloned.

So far so good, im testing if the package name is the same, if the dot count is the same and some apps like dualspace create a user 999.

But some apps like "Island" sandbox the app and isolate it.

My question is, is there any way to detect if the app is cloned in a sandbox environment?
I searched on the internet but couldnt find much info on this topic.


问:
how to use api-platform serialization in custom symfony code
I have a standard symonfy(6) app and api-platform(3) configured for some vue apps that are embedded on specific pages of my symfony app.

I want to use the json-ld serialization used by api-platform in non api code.

I can use the symfony serializer, and this works:

```<code>$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizer = new ObjectNormalizer();
$serializer = new Serializer([$normalizer], ['json' => new JsonEncoder()]);

$output = $serializer->serialize($entity, 'json', ['groups' => 'read'])

</code>```

but that lacks some useful features, like the iri's of relatet entities ..
i would like to have the same serialization output, that apiPlatform generates.

How can i call the serializer to get exact the same result as i get from a configured url/endpoint?

Why do i want this: i have an vue app that needs to collect data from many endpoints for initialization. i want to prepare and give that data via the symfony-template that holds the entrypoint for the vue app.

Update:
I figured out a partial solution after some debugging the normal api process, but i'm sure i didnt see all consequences. you can use the api-platform serializer service in your services.
I build a wrapper service around the api-platform serializer, so i can autowire it in my controller:

```<code>    App\Utils\Api\OfflineApi:
        arguments: ['@api_platform.serializer']
</code>```

controller:

```<code>public function action(EntityClass $entity, OfflineApi $offlineApi): Response {
   $offlineApi->serialize($entity, ['groups' => 'read']),
</code>```

Body:
I have a standard symonfy(6) app and api-platform(3) configured for some vue apps that are embedded on specific pages of my symfony app.

I want to use the json-ld serialization used by api-platform in non api code.

I can use the symfony serializer, and this works:

$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizer = new ObjectNormalizer();
$serializer = new Serializer([$normalizer], ['json' => new JsonEncoder()]);

$output = $serializer->serialize($entity, 'json', ['groups' => 'read'])

but that lacks some useful features, like the iri's of relatet entities ..
i would like to have the same serialization output, that apiPlatform generates.

How can i call the serializer to get exact the same result as i get from a configured url/endpoint?

Why do i want this: i have an vue app that needs to collect data from many endpoints for initialization. i want to prepare and give that data via the symfony-template that holds the entrypoint for the vue app.

Update:
I figured out a partial solution after some debugging the normal api process, but i'm sure i didnt see all consequences. you can use the api-platform serializer service in your services.
I build a wrapper service around the api-platform serializer, so i can autowire it in my controller:

    App\Utils\Api\OfflineApi:
        arguments: ['@api_platform.serializer']

controller:

public function action(EntityClass $entity, OfflineApi $offlineApi): Response {
   $offlineApi->serialize($entity, ['groups' => 'read']),


问:
Flutter throws Instance of 'minified:ad<dynamic>'
Flutter is throwing Instance of 'minified:ad' for api response on web when deployed only. And this issue is not happening on android

I tried adding few statements on web.dart and checked if some null values were there but could not find the issue.


问:
How to read Mac's shell env variable in Swift
I try to read a password saved in .zshrc file as env variable of Mac in Swift code. I tried things like this, but it only show the environment variables related to Xcode.

ProcessInfo.processInfo.environment["myPassword"]

So how should I read the Mac's env variables in Swift code?


问:
Express.JS (Cluster) - Puppeteer - How can I increase the performance of MediaRecorder? (Debian Remote Machine)
I'm running a WebGL on same pages. (Some Unity games) Also I'm recording them with Puppeteer and some native Javascript.

Here is the native Javascript code to record my WebGL games;

```<code>var canvas = document.getElementById("unity-canvas");
const canvasStream = canvas.captureStream(60);
const recordedChunks = [];
const mediaRecorder = new MediaRecorder(canvasStream, {
  mimeType: "video/webm; codecs=vp9",
});

mediaRecorder.ondataavailable = (event) => recordedChunks.push(event.data);

mediaRecorder.onstop = () => {
  let recordedBlob = new Blob(recordedChunks, {
    type: "video/webm"
  }
});
</code>```

It is just a simple MediaRecorder code to record a canvas.

Also there is a puppeteer script to open these pages in my remote linux server; (The script is quite long so I'll just put puppeteer settings)

```<code>const browser = await puppeteer.launch({
  args: [
    "--no-sandbox",
    "--use-gl=egl",
    "--enable-webgl",
    "--hide-scrollbars",
    "--mute-audio",
    "--disable-infobars",
    "--disable-breakpad",
    "--use-fake-ui-for-media-stream",
  ],
  headless: true,
  executablePath:
    "/usr/bin/google-chrome",
});
</code>```

And I run this Puppeteer function with an Express JS backend. Here is my cluster - express.js settings;

```<code>const express = require('express')
const app = express()
const port = 8006
const cors = require('cors');
const cluster = require('cluster');
const cCPUs = require('os').cpus().length;

if (cluster.isMaster) {
    // Create a worker for each CPU
    for (let i = 0; i < cCPUs; i++) {
        cluster.fork();
    }
    cluster.on('online', function (worker) {
        console.log('Worker ' + worker.process.pid + ' is online.');
    });
    cluster.on('exit', function (worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died.');
    });
} else {
    const puppeteer_router = require("./router/puppeteer");
    app.use(cors({
        origin: '*'
    }));
    app.use(express.json());

    app.get('/', (req, res) => {
        res.send({
            detail: "Hello World!"
        })
    })
    app.post('/puppeteer/play', puppeteer_router.play_game)
    app.listen(port, () => {
        console.log(`Example app listening on port ${port}`)
    })
}
</code>```

The problem is I'm running this code in a strong server but it is still freezing sometimes. The same code & game runs like 60+ fps on my local macbook.

System usages are like below;

15% of total Cpus while recording

10% of total memory while recording

10% usage of nvidia t4 gpu (I see that by typing nvidia-smi)

Server specs are like below;

Debian 10

48 gb memory

20 cores (40 vcpus)

150 gb SSD

Nvidia T4

I don't really expect the same result as my local machine, but records are like 15-20 fps and I feel like there is a mistake in my setup. This machine should run those light games easily. Am i wrong?

I'm wondering your answers and tips.

Body:
I'm running a WebGL on same pages. (Some Unity games) Also I'm recording them with Puppeteer and some native Javascript.

Here is the native Javascript code to record my WebGL games;

var canvas = document.getElementById("unity-canvas");
const canvasStream = canvas.captureStream(60);
const recordedChunks = [];
const mediaRecorder = new MediaRecorder(canvasStream, {
  mimeType: "video/webm; codecs=vp9",
});

mediaRecorder.ondataavailable = (event) => recordedChunks.push(event.data);

mediaRecorder.onstop = () => {
  let recordedBlob = new Blob(recordedChunks, {
    type: "video/webm"
  }
});

It is just a simple MediaRecorder code to record a canvas.

Also there is a puppeteer script to open these pages in my remote linux server; (The script is quite long so I'll just put puppeteer settings)

const browser = await puppeteer.launch({
  args: [
    "--no-sandbox",
    "--use-gl=egl",
    "--enable-webgl",
    "--hide-scrollbars",
    "--mute-audio",
    "--disable-infobars",
    "--disable-breakpad",
    "--use-fake-ui-for-media-stream",
  ],
  headless: true,
  executablePath:
    "/usr/bin/google-chrome",
});

And I run this Puppeteer function with an Express JS backend. Here is my cluster - express.js settings;

const express = require('express')
const app = express()
const port = 8006
const cors = require('cors');
const cluster = require('cluster');
const cCPUs = require('os').cpus().length;

if (cluster.isMaster) {
    // Create a worker for each CPU
    for (let i = 0; i < cCPUs; i++) {
        cluster.fork();
    }
    cluster.on('online', function (worker) {
        console.log('Worker ' + worker.process.pid + ' is online.');
    });
    cluster.on('exit', function (worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died.');
    });
} else {
    const puppeteer_router = require("./router/puppeteer");
    app.use(cors({
        origin: '*'
    }));
    app.use(express.json());

    app.get('/', (req, res) => {
        res.send({
            detail: "Hello World!"
        })
    })
    app.post('/puppeteer/play', puppeteer_router.play_game)
    app.listen(port, () => {
        console.log(`Example app listening on port ${port}`)
    })
}

The problem is I'm running this code in a strong server but it is still freezing sometimes. The same code & game runs like 60+ fps on my local macbook.

System usages are like below;

15% of total Cpus while recording

10% of total memory while recording

10% usage of nvidia t4 gpu (I see that by typing nvidia-smi)

Server specs are like below;

Debian 10

48 gb memory

20 cores (40 vcpus)

150 gb SSD

Nvidia T4

I don't really expect the same result as my local machine, but records are like 15-20 fps and I feel like there is a mistake in my setup. This machine should run those light games easily. Am i wrong?

I'm wondering your answers and tips.


问:
The pgAdmin 4 server could not be contacted
I found somebody asking the same question almost 6 years ago, versions are changed and i can't make it work

This are the versions im working with:

Windows 11

pgAdmin 4 v6.17

postgresql 14.6.1

I changed PC and i had to reinstall evrything...
So basically i installed pgAdmin with the installer you can find on their web site (here https://www.pgadmin.org/download/pgadmin-4-windows/), and postgresql with the installer you can find following the steps from pgadmin website (this is the link: https://www.enterprisedb.com/downloads/postgres-postgresql-downloads)

If i manually shutdown postgresql pgAdmin will work but obviously i can't use a local DB
If i keep postgres active locally pgAdmin wont open due to Fatal Error:The pgAdmin 4 server could not be contacted , i got no more info

The problem is that i need to work with DB both locally and in remote

i tried reinstalling both pgAdmin and postgres, and executing pgadmin as administrator made no difference

I think is related to the port usage, like they are both tring to use port 5432, but i don t know

Anything i can try?


问:
PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 12500: , null, null)
I am using google console for login with email. its works properly before I add my project to firebase.
I want to send notification to user so I added my project to firebase for notification and its work good. but the problem is when I login with google it gives this error "PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 12500: , null, null)".
I saw the SHA1 key in both the platform (google console and firebase) are different different SHA1 key for the same app. I tried to put same key in both the platform so its gives me error "The request failed because the Android package name and fingerprint are already in use"

Another problem is when i try to creat new SHA1 key so it will genrate same key asper last.
I am stuck in this problem please help me.

I am using real android device for testing.


问:
Obtaining css property's value using javascript returns unknown character
As you can see in the code snippet below, I want to extract the content css property of a pseudo-element :before. In this example content with value \e917 is not rendered as something meaningful on view, but on my real example, it does, so the value I want to extract is \e917, and instead I get the questionmark character, as you can see in the js console of the code snippet.

Given that I cannot change html or css, is there a way to somehow obtain the original value of \e917 in this case?

When I inspect the element in browser, I can see the exact value that I want to extract using js here.

var content = window.getComputedStyle(document.querySelector('#my_p'), ':before').getPropertyValue('content');

console.log(content);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p::before{
  content:'\e917'
}</code>```

Lorem ipsum
```

Body:
As you can see in the code snippet below, I want to extract the content css property of a pseudo-element :before. In this example content with value \e917 is not rendered as something meaningful on view, but on my real example, it does, so the value I want to extract is \e917, and instead I get the questionmark character, as you can see in the js console of the code snippet.

Given that I cannot change html or css, is there a way to somehow obtain the original value of \e917 in this case?

When I inspect the element in browser, I can see the exact value that I want to extract using js here.

var content = window.getComputedStyle(document.querySelector('#my_p'), ':before').getPropertyValue('content');

console.log(content);

p::before{
  content:'\e917'
}

Lorem ipsum


问:
How can I convert EofSensorInputStream (InputStream) to String?
My code tries to call restTemplate.exchange() and handles error through a custom response error handler and explained here https://www.baeldung.com/spring-rest-template-error-handling

The problem is when I try to read httpResponse.getBody() which returns an InputStream and convert it to String, I get 'Attempted to read from a closed stream' error.

Not sure what other ways could be. I've tried a lot of way including InputStreamReader, Scanner, IOUtils etc but all of them through the same error.

```<code>@Component
public class RestTemplateResponseErrorHandler
  implements ResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse httpResponse)
      throws IOException {

        return ...
    }

    @Override
    public void handleError(ClientHttpResponse httpResponse)
      throws IOException {

        if (httpResponse.getStatusCode()
          .series() == HttpStatus.Series.SERVER_ERROR) {

              //error
              log.error(httpResponse.getBody);

        }
    }
}
</code>```

Body:
My code tries to call restTemplate.exchange() and handles error through a custom response error handler and explained here https://www.baeldung.com/spring-rest-template-error-handling

The problem is when I try to read httpResponse.getBody() which returns an InputStream and convert it to String, I get 'Attempted to read from a closed stream' error.

Not sure what other ways could be. I've tried a lot of way including InputStreamReader, Scanner, IOUtils etc but all of them through the same error.

@Component
public class RestTemplateResponseErrorHandler
  implements ResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse httpResponse)
      throws IOException {

        return ...
    }

    @Override
    public void handleError(ClientHttpResponse httpResponse)
      throws IOException {

        if (httpResponse.getStatusCode()
          .series() == HttpStatus.Series.SERVER_ERROR) {

              //error
              log.error(httpResponse.getBody);

        }
    }
}


问:
How to create PDF file using Wordpress Rest API
I am trying to create a PDF file using WP Rest API. I wrote this small code on function.php. But when I call the API from the postman, it shows - Internal Server Error.

Here is my code:

add_action(
    'rest_api_init',
    function () {
        register_rest_route(
            'api',
            '/get_location',
            array(
                'methods'  => WP_REST_Server::READABLE,
                'callback' => 'get_location',
            )
        );
    }
);

function get_location() {
    global $wpdb;
    $results = array();

    require get_stylesheet_directory() . '/dompdf/autoload.inc.php';
    use Dompdf\Dompdf;
    use Dompdf\Options;
    $options = new Options();

    $options->set( 'isRemoteEnabled', true );
    // Instantiate and use the dompdf class
    $dompdf = new Dompdf( $options );
    $dompdf->loadHtml( 'hello world
TEST' );
    $dompdf->setPaper( 'A4', 'landscape' );

    // Render the HTML as PDF
    $dompdf->render();
    $output = $dompdf->output();
    $now    = strtotime( 'now' );
    // file_put_contents($now.".pdf", $output);
    file_put_contents( get_stylesheet_directory() . '/dompdf/' . $now . '.pdf', $output );

    return $results;
```

The above code show internal server error in postman

Body:
I am trying to create a PDF file using WP Rest API. I wrote this small code on function.php. But when I call the API from the postman, it shows - Internal Server Error.

Here is my code:

add_action(
    'rest_api_init',
    function () {
        register_rest_route(
            'api',
            '/get_location',
            array(
                'methods'  => WP_REST_Server::READABLE,
                'callback' => 'get_location',
            )
        );
    }
);

function get_location() {
    global $wpdb;
    $results = array();

    require get_stylesheet_directory() . '/dompdf/autoload.inc.php';
    use Dompdf\Dompdf;
    use Dompdf\Options;
    $options = new Options();

    $options->set( 'isRemoteEnabled', true );
    // Instantiate and use the dompdf class
    $dompdf = new Dompdf( $options );
    $dompdf->loadHtml( 'hello world
TEST' );
    $dompdf->setPaper( 'A4', 'landscape' );

    // Render the HTML as PDF
    $dompdf->render();
    $output = $dompdf->output();
    $now    = strtotime( 'now' );
    // file_put_contents($now.".pdf", $output);
    file_put_contents( get_stylesheet_directory() . '/dompdf/' . $now . '.pdf', $output );

    return $results;

The above code show internal server error in postman


问:
CreateToolhelp32Snapshot isn't detecting all the modules for a certain process
My code is only outputting a few modules in the process, when there are much more. The procID is correct as i've checked in task manager. I would like it to return every single module in the process.

I'm using a C compiler for this. Is this a problem?

```<code>uintptr_t findModuleAddress (char* name, DWORD procID){
    MODULEENTRY32 entry;
    entry.dwSize = sizeof(MODULEENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, procID);
    uintptr_t cModuleAddress = 0;
    Module32First(snapshot,&entry);
    while (Module32Next(snapshot, &entry)){
        printf("%s\n",entry.szModule);
        if (!strcmp(name,entry.szModule)){
            printf("Found module\n");
            cModuleAddress = (uintptr_t)entry.modBaseAddr;
            break;
        }
    }
    CloseHandle(snapshot);

    return cModuleAddress;
}
</code>```

The output:

Body:
My code is only outputting a few modules in the process, when there are much more. The procID is correct as i've checked in task manager. I would like it to return every single module in the process.

I'm using a C compiler for this. Is this a problem?

uintptr_t findModuleAddress (char* name, DWORD procID){
    MODULEENTRY32 entry;
    entry.dwSize = sizeof(MODULEENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, procID);
    uintptr_t cModuleAddress = 0;
    Module32First(snapshot,&entry);
    while (Module32Next(snapshot, &entry)){
        printf("%s\n",entry.szModule);
        if (!strcmp(name,entry.szModule)){
            printf("Found module\n");
            cModuleAddress = (uintptr_t)entry.modBaseAddr;
            break;
        }
    }
    CloseHandle(snapshot);

    return cModuleAddress;
}

The output:


问:
How can I check if my PDF file is "broken" with javascript(React)?
I'm trying to validate my PDF file with a input file, I want some kind of validation, if I send a broken or corrupted PDF, the input file will throw a error or something. How can I do it?
I'm using Next JS.

I checked the object from the broken PDF to see if there's something different and I can't see anything wrong with it, I installed some libs like "is-pdf-valid", but it doesn't work.


问:
TypeError: Cannot read property 'startDeviceScan' of null "React-Native"
I need to get the detailed bluetooth data of the surrounding devices when I press the button. I use the react-native-ble-plx library for this, but this library does not integrate with android 12. I made some necessary permisson adjustments for this. On manifest.xml file and app.js files. When I run the code, I get the following error about the "scanDeviceStart" method.

```<code>TypeError: Cannot read property 'startDeviceScan' of null
</code>```

What would you suggest me to solve this error? my codes are below

React-Native-ble-plx = https://dotintent.github.io/react-native-ble-plx/#blemanager

```<code>import React, { useState, useEffect } from 'react';
    import {
    SafeAreaView,
    View,
    Text,
    Button,
    StyleSheet,
    PermissionsAndroid ,
    FlatList,
    } from 'react-native';
    import BleManager from 'react-native-ble-plx';
    import { PERMISSIONS, requestMultiple } from 'react-native-permissions';
    import DeviceInfo from 'react-native-device-info';

    const requestPermissions = async () => {
    if (Platform.OS === 'android') {
    const apiLevel = await DeviceInfo.getApiLevel();

    if (apiLevel < 31) {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          title: 'Location Permission',
          message: 'Bluetooth Low Energy requires Location',
          buttonNeutral: 'Ask Later',
          buttonNegative: 'Cancel',
          buttonPositive: 'OK',
        },
      );
    } else {
      const result = await requestMultiple([
        PERMISSIONS.ANDROID.BLUETOOTH_SCAN,
        PERMISSIONS.ANDROID.BLUETOOTH_CONNECT,
        PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
      ]);

      const isGranted =
        result['android.permission.BLUETOOTH_CONNECT'] ===
        PermissionsAndroid.RESULTS.GRANTED &&
        result['android.permission.BLUETOOTH_SCAN'] ===
        PermissionsAndroid.RESULTS.GRANTED &&
        result['android.permission.ACCESS_FINE_LOCATION'] ===
        PermissionsAndroid.RESULTS.GRANTED;
    }

    }
    };

    const App = () => {
    const [devices, setDevices] = useState([]);
    const [scanning, setScanning] = useState(false);
    const [bleManager, setBleManager] = useState(null);

    function requestBluetoothPermissions(cb) {
    if (Platform.OS === 'android') {
    DeviceInfo.getApiLevel().then((apiLevel) => {
    if (apiLevel < 31) {
    PermissionsAndroid.request(
    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
    {
    title: 'Location Permission',
    message: 'Bluetooth Low Energy requires Location',
    buttonNeutral: 'Ask Later',
    buttonNegative: 'Cancel',
    buttonPositive: 'OK',
    },
    ).then((granted) => {
    cb(granted === PermissionsAndroid.RESULTS.GRANTED);
    });
    } else {
    requestMultiple([
    PERMISSIONS.ANDROID.BLUETOOTH_SCAN,
    PERMISSIONS.ANDROID.BLUETOOTH_CONNECT,
    PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
    ]).then((result) => {
    const isGranted =
    result['android.permission.BLUETOOTH_CONNECT'] === PermissionsAndroid.RESULTS.GRANTED &&
    result['android.permission.BLUETOOTH_SCAN'] === PermissionsAndroid.RESULTS.GRANTED &&
    result['android.permission.ACCESS_FINE_LOCATION'] === PermissionsAndroid.RESULTS.GRANTED;
    cb(isGranted);
    });
    }
    });
    } else {
    cb(true);
    }
    }

    useEffect(() => {
        if (!bleManager) {
        requestBluetoothPermissions((isGranted) => {
        if (isGranted) {
        const manager = new BleManager();
        setBleManager(manager);
        manager.startDeviceScan(  [serialUUIDs.serviceUUID],
          {scanMode: ScanMode.LowLatency}, (error, device) => {
        if (error) {
        console.log(error.message);
        return;
        }

        console.log(device.name);
        console.log(device.id);

        if (device.name) {
          setDevices((prevDevices) => [...prevDevices, device]);
        }
        });
        setScanning(true);
        }
        });
        }
    }, []);

    return (
    <SafeAreaView>
      <View>
          {scanning ? (
          <Button
          title="Stop Scanning"
          onPress={() => {
          bleManager.stopDeviceScan();
          setScanning(false);
          }}
          />
          ) : (
          <Button
          title="Start Scanning"
          onPress={() => {
          requestBluetoothPermissions((isGranted) => {
          if (isGranted) {
          setDevices([]);
          bleManager.startDeviceScan([serialUUIDs.serviceUUID],
            {scanMode: ScanMode.LowLatency},(error, device) => {
          if (error) {
          console.log(error.message);
          return;
          }
          console.log(device.name);
          console.log(device.id);

          if (device.name) {
            setDevices((prevDevices) => [...prevDevices, device]);
          }
          });
          setScanning(true);
          }
          });
          }}
          />
          )}
      </View>
        <FlatList
        data={devices}
        renderItem={({ item }) => (
        <Text>
        {item.name} ({item.id})
        </Text>
        )}
        keyExtractor={(item) => item.id}
        />
    </SafeAreaView>
    );
    };

    export default App;
</code>```

Body:
I need to get the detailed bluetooth data of the surrounding devices when I press the button. I use the react-native-ble-plx library for this, but this library does not integrate with android 12. I made some necessary permisson adjustments for this. On manifest.xml file and app.js files. When I run the code, I get the following error about the "scanDeviceStart" method.

TypeError: Cannot read property 'startDeviceScan' of null

What would you suggest me to solve this error? my codes are below

React-Native-ble-plx = https://dotintent.github.io/react-native-ble-plx/#blemanager

import React, { useState, useEffect } from 'react';
    import {
    SafeAreaView,
    View,
    Text,
    Button,
    StyleSheet,
    PermissionsAndroid ,
    FlatList,
    } from 'react-native';
    import BleManager from 'react-native-ble-plx';
    import { PERMISSIONS, requestMultiple } from 'react-native-permissions';
    import DeviceInfo from 'react-native-device-info';

    const requestPermissions = async () => {
    if (Platform.OS === 'android') {
    const apiLevel = await DeviceInfo.getApiLevel();

    if (apiLevel < 31) {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          title: 'Location Permission',
          message: 'Bluetooth Low Energy requires Location',
          buttonNeutral: 'Ask Later',
          buttonNegative: 'Cancel',
          buttonPositive: 'OK',
        },
      );
    } else {
      const result = await requestMultiple([
        PERMISSIONS.ANDROID.BLUETOOTH_SCAN,
        PERMISSIONS.ANDROID.BLUETOOTH_CONNECT,
        PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
      ]);

      const isGranted =
        result['android.permission.BLUETOOTH_CONNECT'] ===
        PermissionsAndroid.RESULTS.GRANTED &&
        result['android.permission.BLUETOOTH_SCAN'] ===
        PermissionsAndroid.RESULTS.GRANTED &&
        result['android.permission.ACCESS_FINE_LOCATION'] ===
        PermissionsAndroid.RESULTS.GRANTED;
    }

    }
    };

    const App = () => {
    const [devices, setDevices] = useState([]);
    const [scanning, setScanning] = useState(false);
    const [bleManager, setBleManager] = useState(null);

    function requestBluetoothPermissions(cb) {
    if (Platform.OS === 'android') {
    DeviceInfo.getApiLevel().then((apiLevel) => {
    if (apiLevel < 31) {
    PermissionsAndroid.request(
    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
    {
    title: 'Location Permission',
    message: 'Bluetooth Low Energy requires Location',
    buttonNeutral: 'Ask Later',
    buttonNegative: 'Cancel',
    buttonPositive: 'OK',
    },
    ).then((granted) => {
    cb(granted === PermissionsAndroid.RESULTS.GRANTED);
    });
    } else {
    requestMultiple([
    PERMISSIONS.ANDROID.BLUETOOTH_SCAN,
    PERMISSIONS.ANDROID.BLUETOOTH_CONNECT,
    PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
    ]).then((result) => {
    const isGranted =
    result['android.permission.BLUETOOTH_CONNECT'] === PermissionsAndroid.RESULTS.GRANTED &&
    result['android.permission.BLUETOOTH_SCAN'] === PermissionsAndroid.RESULTS.GRANTED &&
    result['android.permission.ACCESS_FINE_LOCATION'] === PermissionsAndroid.RESULTS.GRANTED;
    cb(isGranted);
    });
    }
    });
    } else {
    cb(true);
    }
    }

    useEffect(() => {
        if (!bleManager) {
        requestBluetoothPermissions((isGranted) => {
        if (isGranted) {
        const manager = new BleManager();
        setBleManager(manager);
        manager.startDeviceScan(  [serialUUIDs.serviceUUID],
          {scanMode: ScanMode.LowLatency}, (error, device) => {
        if (error) {
        console.log(error.message);
        return;
        }

        console.log(device.name);
        console.log(device.id);

        if (device.name) {
          setDevices((prevDevices) => [...prevDevices, device]);
        }
        });
        setScanning(true);
        }
        });
        }
    }, []);

    return (
    <SafeAreaView>
      <View>
          {scanning ? (
          <Button
          title="Stop Scanning"
          onPress={() => {
          bleManager.stopDeviceScan();
          setScanning(false);
          }}
          />
          ) : (
          <Button
          title="Start Scanning"
          onPress={() => {
          requestBluetoothPermissions((isGranted) => {
          if (isGranted) {
          setDevices([]);
          bleManager.startDeviceScan([serialUUIDs.serviceUUID],
            {scanMode: ScanMode.LowLatency},(error, device) => {
          if (error) {
          console.log(error.message);
          return;
          }
          console.log(device.name);
          console.log(device.id);

          if (device.name) {
            setDevices((prevDevices) => [...prevDevices, device]);
          }
          });
          setScanning(true);
          }
          });
          }}
          />
          )}
      </View>
        <FlatList
        data={devices}
        renderItem={({ item }) => (
        <Text>
        {item.name} ({item.id})
        </Text>
        )}
        keyExtractor={(item) => item.id}
        />
    </SafeAreaView>
    );
    };

    export default App;


问:
Problems with GStreamer compiled from sources in RHEL8 + GCC12
I'm getting strange results with GStreamer 1.20.3 compiled from sources.

Target platform is RHEL8 with GCC12 (official Docker image was used as the base one).
Python 3.8, Meson and Ninja were installed so compilation/linking passes without any errors.

But when I'm trying to check if all is Ok, I see this:

```<code># ./gst-inspect-1.0

staticelements:  bin: Generic bin
staticelements:  pipeline: Pipeline object

Total count: 4 plugins (1 blacklist entry not shown), 2 features
</code>```

So the tool does not see any plugins.

GStreamer is compiled like this (I plan to use static library):

```<code>...
ENV INSTALL_DIR_GSTREAMER=/app/install/gstreamer

RUN meson setup --prefix=$INSTALL_DIR_GSTREAMER --default-library=static ./build
RUN ninja -C ./build
RUN ninja -C ./build install
...
</code>```

I saved full log and see only one fatal in it. Not sure that it's a reason of the problem but still:

```<code>#29 345.7 Cloning into 'pygobject'...
#29 349.9 HEAD is now at 63825d8e release
#29 350.0 Cloning into 'gobject-introspection'...
#29 351.0 warning: Could not find remote branch master to clone.
#29 351.0 fatal: Remote branch master not found in upstream origin
</code>```

On checking https://gitlab.gnome.org/GNOME/gobject-introspection I found the main branch which is probably just the new name of master.

But this error is strange enough because I found only one dependency on gobject-introspection in pango and in the .wrap file the branch name for gobject-introspection is specified properly as revision=main.

Also I tried to stream WAV file from Docker with gst-launch-1.0 and it also fails with unable to create pipeline and multifile plugin not found.

On checking configuration summary in the log I see all base, good, bad plugins:

```<code>...
#29 356.1 gst-plugins-good 1.20.3
#29 356.1
#29 356.1     Plugins: alpha, alphacolor, apetag, audiofx, audioparsers, auparse,
#29 356.1              autodetect, avi, cutter, navigationtest, debug, deinterlace, dtmf,
#29 356.1              effectv, equalizer, flv, flxdec, goom, goom2k1, icydemux,
#29 356.1              id3demux, imagefreeze, interleave, isomp4, alaw, mulaw, level,
#29 356.1              matroska, monoscope, multifile, multipart, replaygain, rtp,
#29 356.1              rtpmanager, rtsp, shapewipe, smpte, spectrum, udp, videobox,
#29 367.6              videocrop, videofilter, videomixer, wavenc, wavparse, y4menc,
#29 367.6              ossaudio, oss4, video4linux2, ximagesrc, cairo, jpeg, lame, dv,
#29 367.6              png, soup
...
</code>```

So there are 2 main questions:

How to fix the gobject-introspection problem (I suspect somewhere in the sub-project there's a .wrap file with revision=master, but where it is)?

What else to check to understand why GStreamer tools are not working?

Any help is appreciated.

Body:
I'm getting strange results with GStreamer 1.20.3 compiled from sources.

Target platform is RHEL8 with GCC12 (official Docker image was used as the base one).
Python 3.8, Meson and Ninja were installed so compilation/linking passes without any errors.

But when I'm trying to check if all is Ok, I see this:

# ./gst-inspect-1.0

staticelements:  bin: Generic bin
staticelements:  pipeline: Pipeline object

Total count: 4 plugins (1 blacklist entry not shown), 2 features

So the tool does not see any plugins.

GStreamer is compiled like this (I plan to use static library):

...
ENV INSTALL_DIR_GSTREAMER=/app/install/gstreamer

RUN meson setup --prefix=$INSTALL_DIR_GSTREAMER --default-library=static ./build
RUN ninja -C ./build
RUN ninja -C ./build install
...

I saved full log and see only one fatal in it. Not sure that it's a reason of the problem but still:

#29 345.7 Cloning into 'pygobject'...
#29 349.9 HEAD is now at 63825d8e release
#29 350.0 Cloning into 'gobject-introspection'...
#29 351.0 warning: Could not find remote branch master to clone.
#29 351.0 fatal: Remote branch master not found in upstream origin

On checking https://gitlab.gnome.org/GNOME/gobject-introspection I found the main branch which is probably just the new name of master.

But this error is strange enough because I found only one dependency on gobject-introspection in pango and in the .wrap file the branch name for gobject-introspection is specified properly as revision=main.

Also I tried to stream WAV file from Docker with gst-launch-1.0 and it also fails with unable to create pipeline and multifile plugin not found.

On checking configuration summary in the log I see all base, good, bad plugins:

...
#29 356.1 gst-plugins-good 1.20.3
#29 356.1
#29 356.1     Plugins: alpha, alphacolor, apetag, audiofx, audioparsers, auparse,
#29 356.1              autodetect, avi, cutter, navigationtest, debug, deinterlace, dtmf,
#29 356.1              effectv, equalizer, flv, flxdec, goom, goom2k1, icydemux,
#29 356.1              id3demux, imagefreeze, interleave, isomp4, alaw, mulaw, level,
#29 356.1              matroska, monoscope, multifile, multipart, replaygain, rtp,
#29 356.1              rtpmanager, rtsp, shapewipe, smpte, spectrum, udp, videobox,
#29 367.6              videocrop, videofilter, videomixer, wavenc, wavparse, y4menc,
#29 367.6              ossaudio, oss4, video4linux2, ximagesrc, cairo, jpeg, lame, dv,
#29 367.6              png, soup
...

So there are 2 main questions:

How to fix the gobject-introspection problem (I suspect somewhere in the sub-project there's a .wrap file with revision=master, but where it is)?

What else to check to understand why GStreamer tools are not working?

Any help is appreciated.


问:
Use configuration properties in Spring expression language
I have a class with configuration properties:

```<code>@Data
@ConfigurationProperties("message-starter")
public class JobProperties {

    public Duration kafkaSendingPeriod;
    public Duration rabbitSendingPeriod;
}
</code>```

And class that aggregates this properties and uses them in @Scheduled annotation using Spring expression language:

```<code>@Component
@EnableConfigurationProperties(JobProperties.class)
@RequiredArgsConstructor
public class Job {

    public final JobProperties jobProperties;

    @Scheduled(fixedRateString="#{@jobProperties.getKafkaSendingPeriod()}")
    public void fun(){
        System.out.println("Time: " + LocalDateTime.now());
    }
}
</code>```

But when I run it I get the following exception:

```<code>Description:

A component required a bean named 'jobProperties' that could not be found.

Action:

Consider defining a bean named 'jobProperties' in your configuration.
</code>```

Please tell me how to fix this exception so that I can get the value of the fields of the JobProperties class?

Body:
I have a class with configuration properties:

@Data
@ConfigurationProperties("message-starter")
public class JobProperties {

    public Duration kafkaSendingPeriod;
    public Duration rabbitSendingPeriod;
}

And class that aggregates this properties and uses them in @Scheduled annotation using Spring expression language:

@Component
@EnableConfigurationProperties(JobProperties.class)
@RequiredArgsConstructor
public class Job {

    public final JobProperties jobProperties;

    @Scheduled(fixedRateString="#{@jobProperties.getKafkaSendingPeriod()}")
    public void fun(){
        System.out.println("Time: " + LocalDateTime.now());
    }
}

But when I run it I get the following exception:

Description:

A component required a bean named 'jobProperties' that could not be found.

Action:

Consider defining a bean named 'jobProperties' in your configuration.

Please tell me how to fix this exception so that I can get the value of the fields of the JobProperties class?


问:
Spring-Batch ItermReader using REST Endpoint as source
Could not find a source as REST endpoint using which ItemReader in spring-batch can can invoke it thousand times and read json.

I tried going through  https://docs.spring.io/spring-batch/docs/current/reference/html/readersAndWriters.html#itemReader
and I could not see for ItemReader is hitting any REST endpoint.

My use case is,

Read DB for 200,000 unique value

Using this values call to REST point each time to get json results

Also at the same time using (1) read unique results from DB

Combine result 2 and 3 for each of the elements out of 200,000

Finally store them on to a DB for each element.

Including Error and Exception Handling with Transactional capabilities.

Deploy them to Kubernetes


问:
How do you properly integrate react-hook-form v7 with reactstrap 9
I am trying to using reference for mulltiple input field for validation using react hook form and the input tag is from Reactstrap.but after submit it is not working and also validation part is not working well. My Question is how to register multiple inpult field using Reactstrap 9 react hook form v7.

This my code which i have done for one input field but i want to aplly the same thing for multiple input field and how to implement the same thing for multiple input field.

```<code>const {ref,...sample} = register('firstname','middlename');
</code>```
```<code><InputclassName="mb-3"placeholder="First Name*"id="firstname"name="firstname"innerRef={ref} {...sample}/>
</code>```

Body:
I am trying to using reference for mulltiple input field for validation using react hook form and the input tag is from Reactstrap.but after submit it is not working and also validation part is not working well. My Question is how to register multiple inpult field using Reactstrap 9 react hook form v7.

This my code which i have done for one input field but i want to aplly the same thing for multiple input field and how to implement the same thing for multiple input field.

const {ref,...sample} = register('firstname','middlename');

<InputclassName="mb-3"placeholder="First Name*"id="firstname"name="firstname"innerRef={ref} {...sample}/>


问:
Confusion matrix not making any sense after training a 3 class image classification model
I'm a rookie at machine learning so please bear with me.

I have a model that trains images and classifies them in 3 different classes. I'm trying to get the confusion matrix for the test data, but either I don't understand it or it's not making any sense. When the model is done training after 200 epochs it shows that the accuracy is around 65%:

loss: 1.5386 - accuracy: 0.6583

But then when the confusion matrix is printed like this:

[[23 51 42]

[20 27 25]

[47 69 56]]

Which isn't correct because the "true" results (23, 27 and 56) don't make up for 65% of all the results. If you add up the numbers in the matrix it adds to the amount of test images so I know that part is correct.

I had a tensorflow warning just before printing the confusion matrix that says the following, but I don't really get its meaning:

WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least steps_per_epoch * epochs batches (in this case, 13 batches). You may need to use the repeat() function when building your dataset

This is my code:

```<code>import sys
from matplotlib import pyplot
import numpy as np
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, Flatten, Dense, MaxPooling2D, Dropout, GlobalAveragePooling2D
from tensorflow.keras.optimizers import SGD, RMSprop, Adam
from keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import confusion_matrix

CLASSES = 3

# define cnn model
def define_model():
    # load model
    base_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
    #add new classifier layers
    x = base_model.output
    x = Dropout(0.4)(x)
    x = GlobalAveragePooling2D(name='avg_pool')(x)
    predictions = Dense(CLASSES, activation='softmax')(x)
    model = Model(inputs=base_model.input, outputs=predictions)

    # mark loaded layers as not trainable
    for layer in base_model.layers:
        layer.trainable = False

    # compile model
    opt = RMSprop(lr=0.0001)
               #momentum=0.9)
    model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
    return model

# plot diagnostic learning curves
def summarize_diagnostics(history):
    # plot loss
    pyplot.subplot(211)
    pyplot.title('Cross Entropy Loss')
    pyplot.plot(history.history['loss'], color='blue', label='train')
    pyplot.plot(history.history['val_loss'], color='orange', label='test')
    # plot accuracy
    pyplot.subplot(212)
    pyplot.title('Classification Accuracy')
    pyplot.plot(history.history['accuracy'], color='blue', label='train')
    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')
    # save plot to file
    filename = sys.argv[0].split('/')[-1]
    pyplot.savefig(filename + '_plot.png')
    pyplot.close()

# run the test harness for evaluating a model
def run_test_harness():
    # define model
    model = define_model()
    # create data generator
    datagen = ImageDataGenerator(featurewise_center=True)
    # specify imagenet mean values for centering
    datagen.mean = [123.68, 116.779, 103.939]
    # prepare iterators
    train_it = datagen.flow_from_directory('../datasetMainPruebas3ClasesQuitandoConfusosCV1/train/',
        class_mode='categorical', batch_size=32, target_size=(224, 224))
    test_it = datagen.flow_from_directory('../datasetMainPruebas3ClasesQuitandoConfusosCV1/test/',
        class_mode='categorical', batch_size=32, target_size=(224, 224))
    # fit model
    history = model.fit_generator(train_it, steps_per_epoch=len(train_it),
        validation_data=test_it, validation_steps=len(test_it), epochs=200, verbose=1)
    # evaluate model
    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)
    print('> %.3f' % (acc * 100.0))

    #confusion matrix
    Y_pred = model.predict_generator(test_it, len(test_it) + 1)
    y_pred = np.argmax(Y_pred, axis=1)
    print('Confusion Matrix')

    cm = confusion_matrix(test_it.classes, y_pred)
    print(cm)

    # learning curves
    summarize_diagnostics(history)

# entry point, run the test harness
run_test_harness()
</code>```

Any help or tip is welcome, thank you

Edit: after checking one of the comments I changed my CM code to the following:

```<code>    #confusion matrix
    all_y_pred = []
    all_y_true = []

    for i in range(len(test_it)):
        x, y = test_it[i]
        y_pred = model.predict(x)

        all_y_pred.append(y_pred)
        all_y_true.append(y)

    all_y_pred = np.concatenate(all_y_pred, axis=0)
    all_y_true = np.concatenate(all_y_true, axis=0)

    print('Confusion Matrix')

    cm = confusion_matrix(all_y_true, all_y_pred)
    print(cm)
</code>```

And now the error I get says "Classification metrics can't handle a mix of multilabel-indicator and continuous-multioutput targets"

Any idea why?

Body:
I'm a rookie at machine learning so please bear with me.

I have a model that trains images and classifies them in 3 different classes. I'm trying to get the confusion matrix for the test data, but either I don't understand it or it's not making any sense. When the model is done training after 200 epochs it shows that the accuracy is around 65%:

loss: 1.5386 - accuracy: 0.6583

But then when the confusion matrix is printed like this:

[[23 51 42]

[20 27 25]

[47 69 56]]

Which isn't correct because the "true" results (23, 27 and 56) don't make up for 65% of all the results. If you add up the numbers in the matrix it adds to the amount of test images so I know that part is correct.

I had a tensorflow warning just before printing the confusion matrix that says the following, but I don't really get its meaning:

WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least steps_per_epoch * epochs batches (in this case, 13 batches). You may need to use the repeat() function when building your dataset

This is my code:

import sys
from matplotlib import pyplot
import numpy as np
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, Flatten, Dense, MaxPooling2D, Dropout, GlobalAveragePooling2D
from tensorflow.keras.optimizers import SGD, RMSprop, Adam
from keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import confusion_matrix

CLASSES = 3

# define cnn model
def define_model():
    # load model
    base_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
    #add new classifier layers
    x = base_model.output
    x = Dropout(0.4)(x)
    x = GlobalAveragePooling2D(name='avg_pool')(x)
    predictions = Dense(CLASSES, activation='softmax')(x)
    model = Model(inputs=base_model.input, outputs=predictions)

    # mark loaded layers as not trainable
    for layer in base_model.layers:
        layer.trainable = False

    # compile model
    opt = RMSprop(lr=0.0001)
               #momentum=0.9)
    model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
    return model

# plot diagnostic learning curves
def summarize_diagnostics(history):
    # plot loss
    pyplot.subplot(211)
    pyplot.title('Cross Entropy Loss')
    pyplot.plot(history.history['loss'], color='blue', label='train')
    pyplot.plot(history.history['val_loss'], color='orange', label='test')
    # plot accuracy
    pyplot.subplot(212)
    pyplot.title('Classification Accuracy')
    pyplot.plot(history.history['accuracy'], color='blue', label='train')
    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')
    # save plot to file
    filename = sys.argv[0].split('/')[-1]
    pyplot.savefig(filename + '_plot.png')
    pyplot.close()

# run the test harness for evaluating a model
def run_test_harness():
    # define model
    model = define_model()
    # create data generator
    datagen = ImageDataGenerator(featurewise_center=True)
    # specify imagenet mean values for centering
    datagen.mean = [123.68, 116.779, 103.939]
    # prepare iterators
    train_it = datagen.flow_from_directory('../datasetMainPruebas3ClasesQuitandoConfusosCV1/train/',
        class_mode='categorical', batch_size=32, target_size=(224, 224))
    test_it = datagen.flow_from_directory('../datasetMainPruebas3ClasesQuitandoConfusosCV1/test/',
        class_mode='categorical', batch_size=32, target_size=(224, 224))
    # fit model
    history = model.fit_generator(train_it, steps_per_epoch=len(train_it),
        validation_data=test_it, validation_steps=len(test_it), epochs=200, verbose=1)
    # evaluate model
    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)
    print('> %.3f' % (acc * 100.0))

    #confusion matrix
    Y_pred = model.predict_generator(test_it, len(test_it) + 1)
    y_pred = np.argmax(Y_pred, axis=1)
    print('Confusion Matrix')

    cm = confusion_matrix(test_it.classes, y_pred)
    print(cm)

    # learning curves
    summarize_diagnostics(history)

# entry point, run the test harness
run_test_harness()

Any help or tip is welcome, thank you

Edit: after checking one of the comments I changed my CM code to the following:

    #confusion matrix
    all_y_pred = []
    all_y_true = []

    for i in range(len(test_it)):
        x, y = test_it[i]
        y_pred = model.predict(x)

        all_y_pred.append(y_pred)
        all_y_true.append(y)

    all_y_pred = np.concatenate(all_y_pred, axis=0)
    all_y_true = np.concatenate(all_y_true, axis=0)

    print('Confusion Matrix')

    cm = confusion_matrix(all_y_true, all_y_pred)
    print(cm)

And now the error I get says "Classification metrics can't handle a mix of multilabel-indicator and continuous-multioutput targets"

Any idea why?


问:
VBA Selenium to press on the blank area and choose or type second option manually
I have failed to use or press the drop down list so as a way around, i want to press on the blank white area so it will open the list then choose 2nd option from it or type it myself through send keys.

HTML Code:

```<code><input class="dxeEditArea_Office2010Blue dxeEditAreaSys" id="Dialog_v12_31833516_MainLayoutEdit_xaf_l691_xaf_dviImportExportFormat_Edit_dropdown_DD_I" name="Dialog$v12_31833516$MainLayoutEdit$xaf_l691$xaf_dviImportExportFormat_Edit_dropdown$DD" onchange="ASPx.ETextChanged('Dialog_v12_31833516_MainLayoutEdit_xaf_l691_xaf_dviImportExportFormat_Edit_dropdown_DD')" value="Coprocess.AR Invoices Status" type="text" autocomplete="off">

<td id="Dialog_v12_31833516_MainLayoutEdit_xaf_l691_xaf_dviImportExportFormat_Edit_dropdown_DD_DDD_L_LBI2T0" class="dxeListBoxItem_Office2010Blue  dxeListBoxItemSelected_Office2010Blue dxeListBoxItemHover_Office2010Blue">AP Invoices Status</td>
</code>```

i use the below line of code to click on the blank space.
i don't use find element by id as it's always changing (dynamic not static).

```<code> br.FindElementByXPath("//*[contains(@id,'dviImportExportFormat_Edit_dropdown_DD_I')]").Click
</code>```

Then choose from the list (AP Invoices Status) by typing it manually through SendKeys

```<code>br.FindElementByXPath("//*[contains(@id,'dviImportExportFormat_Edit_dropdown_DD_DDD_L_LBI2T0')]").SendKeys "AP Invoices Status"

</code>```

but sadly i always get No such element found error.

Can anyone help me with this, am fairly new to Selenium and no skills in HTML.

Thanks in advance.

Body:
I have failed to use or press the drop down list so as a way around, i want to press on the blank white area so it will open the list then choose 2nd option from it or type it myself through send keys.

HTML Code:

<input class="dxeEditArea_Office2010Blue dxeEditAreaSys" id="Dialog_v12_31833516_MainLayoutEdit_xaf_l691_xaf_dviImportExportFormat_Edit_dropdown_DD_I" name="Dialog$v12_31833516$MainLayoutEdit$xaf_l691$xaf_dviImportExportFormat_Edit_dropdown$DD" onchange="ASPx.ETextChanged('Dialog_v12_31833516_MainLayoutEdit_xaf_l691_xaf_dviImportExportFormat_Edit_dropdown_DD')" value="Coprocess.AR Invoices Status" type="text" autocomplete="off">

AP Invoices Status

i use the below line of code to click on the blank space.
i don't use find element by id as it's always changing (dynamic not static).

 br.FindElementByXPath("//*[contains(@id,'dviImportExportFormat_Edit_dropdown_DD_I')]").Click

Then choose from the list (AP Invoices Status) by typing it manually through SendKeys

br.FindElementByXPath("//*[contains(@id,'dviImportExportFormat_Edit_dropdown_DD_DDD_L_LBI2T0')]").SendKeys "AP Invoices Status"

but sadly i always get No such element found error.

Can anyone help me with this, am fairly new to Selenium and no skills in HTML.

Thanks in advance.


问:
How can I integrate Tapatalk and XenForo in my java application?
I'm trying to create a web application in which I want to display data from forums using Tapatalk and XenForo.
I want to display all the posts and messages I get in my forum feed. I want to create the application in Java.

I'm completely new to this so can anyone give me idea for it? Is there any packages to implement them?