问:
Flutter convert Widget to Json
I have a main screen with several Buttons which push the user to different screens and I have a FAB which pushs the user to a screen he saved as favorite. I do this with a cubit from BLoC: (FAB onPress function): Navigator.push(context, MaterialPageRoute(builder: (context) =>  state.favWidget!));
Problem: I try to save the state of the Cubit (Shared prefs or Hydrated, dosent matter for me - I prefere HydratedCubit) so that the user reaches his favorite screen even after a restart.

Here is the FavWidgetState:

```<code>class FavWidgetState extends Equatable {
  factory FavWidgetState.initial() {
    return const FavWidgetState(favWidget: null);
  }

   final Widget? favWidget;

  const FavWidgetState({
    required this.favWidget,
  });
  Map<String, dynamic> toJson() {
    return {
      'favWidget': this.favWidget,
    };
  }

  factory FavWidgetState.fromJson(Map<String, dynamic> json) {
    return FavWidgetState(
      favWidget: json['favWidget'] as Widget,
    );
  }

  @override
  List<Object?> get props => [favWidget];
</code>```

I added the fromJson and toJson with the dart dataclass extention

Inside FaveWidgetcubit is just little code:

```<code> FavWidgetCubit() : super(FavWidgetState.initial());

  void setFaveWidget({required Widget? widget})async{
    emit(FavWidgetState(favWidget: widget));
  }

  @override
  FavWidgetState? fromJson(Map<String, dynamic> json) {
    return FavWidgetState.fromJson(json);
  }

  @override
  Map<String, dynamic>? toJson(FavWidgetState state) {
      return state.toJson();
  }
</code>```

You can imagine that this won't with the error: Unhandled Exception: Converting object to an encodable object failed: Instance of ...
How do I make the Widget? widget to a convertible object?

Title: Flutter convert Widget to Json

Body:
I have a main screen with several Buttons which push the user to different screens and I have a FAB which pushs the user to a screen he saved as favorite. I do this with a cubit from BLoC: (FAB onPress function): Navigator.push(context, MaterialPageRoute(builder: (context) =>  state.favWidget!));
Problem: I try to save the state of the Cubit (Shared prefs or Hydrated, dosent matter for me - I prefere HydratedCubit) so that the user reaches his favorite screen even after a restart.

Here is the FavWidgetState:

class FavWidgetState extends Equatable {
  factory FavWidgetState.initial() {
    return const FavWidgetState(favWidget: null);
  }

   final Widget? favWidget;

  const FavWidgetState({
    required this.favWidget,
  });
  Map<String, dynamic> toJson() {
    return {
      'favWidget': this.favWidget,
    };
  }

  factory FavWidgetState.fromJson(Map<String, dynamic> json) {
    return FavWidgetState(
      favWidget: json['favWidget'] as Widget,
    );
  }

  @override
  List<Object?> get props => [favWidget];

I added the fromJson and toJson with the dart dataclass extention

Inside FaveWidgetcubit is just little code:

 FavWidgetCubit() : super(FavWidgetState.initial());

  void setFaveWidget({required Widget? widget})async{
    emit(FavWidgetState(favWidget: widget));
  }

  @override
  FavWidgetState? fromJson(Map<String, dynamic> json) {
    return FavWidgetState.fromJson(json);
  }

  @override
  Map<String, dynamic>? toJson(FavWidgetState state) {
      return state.toJson();
  }

You can imagine that this won't with the error: Unhandled Exception: Converting object to an encodable object failed: Instance of ...
How do I make the Widget? widget to a convertible object?


来源: stackexchange

问:
ffmpeg cut and stitch video
I have a scenario where i need to cut and stitch parts of the video together using ffmpeg, but this video has multiple audio channels (8 audio channels). The below is working for me but only gives me one audio channel as output

```<code>ffmpeg -i c:\process\abc.mxf -filter_complex \
"[0:v]trim=600:2663,setpts=PTS-STARTPTS,format=yuv420p[0v]; \
[0:a]atrim=600:2663,asetpts=PTS-STARTPTS[0a]; \
[0:v]trim=2886:3286,setpts=PTS-STARTPTS,format=yuv420p[1v]; \
[0:a]atrim=2886:3286,asetpts=PTS-STARTPTS[1a]; \
[0v][0a][1v][1a]concat=n=2:v=1:a=1[outv][outa]" -map [outv] -map [outa] out.mxf
</code>```

How can i get all the 8 audio channels in the output. I have tried the below, as an attempt to get two audio channels, but does work

```<code>ffmpeg -i c:\process\abc.mxf -filter_complex \
"[0:v]trim=600:2663,setpts=PTS-STARTPTS,format=yuv420p[0v]; \
[0:a]atrim=600:2663,asetpts=PTS-STARTPTS[0a]; \
[0:b]atrim=600:2663,asetpts=PTS-STARTPTS[2a]; \
[0:v]trim=2886:3286,setpts=PTS-STARTPTS,format=yuv420p[1v]; \
[0:a]atrim=2886:3286,asetpts=PTS-STARTPTS[1a];
[0:b]atrim=600:2663,asetpts=PTS-STARTPTS[3a];  \
[0v][0a][2a][1v][1a][3a]concat=n=6:v=1:a=2[outv][outa]" -map [outv] -map [outa] out.mxf
</code>```

Any hint will be much appreciated.

ANOTHER ATTEMPT

```<code>ffmpeg -i c:\process\3010010155-TCRHD.mxf -filter_complex " \
[0:v]trim=600:2663,setpts=PTS-STARTPTS,format=yuv420p[0v]; \
[0:a:0]atrim=600:2663,asetpts=PTS-STARTPTS[0a]; \
[0:a:1]atrim=600:2663,asetpts=PTS-STARTPTS[2a]; \
[0:v]trim=2886:3286,setpts=PTS-STARTPTS,format=yuv420p[1v]; \
[0:a:0]atrim=2886:3286,asetpts=PTS-STARTPTS[1a]; \
[0:a:1]atrim=600:2663,asetpts=PTS-STARTPTS[3a]; \
[0v][0a][2a][1v][1a][3a]concat=n=6:v=1:a=2[outv][outa]" -map [outv] -map [outa] out.mxf
</code>```

This gives me an error Cannot find a matching stream for unlabeled input pad 6 on filter Parsed_concat_14

ContentLicense: CC BY-SA 4.0

Title: ffmpeg cut and stitch video

Body:
I have a scenario where i need to cut and stitch parts of the video together using ffmpeg, but this video has multiple audio channels (8 audio channels). The below is working for me but only gives me one audio channel as output

ffmpeg -i c:\process\abc.mxf -filter_complex \
"[0:v]trim=600:2663,setpts=PTS-STARTPTS,format=yuv420p[0v]; \
[0:a]atrim=600:2663,asetpts=PTS-STARTPTS[0a]; \
[0:v]trim=2886:3286,setpts=PTS-STARTPTS,format=yuv420p[1v]; \
[0:a]atrim=2886:3286,asetpts=PTS-STARTPTS[1a]; \
[0v][0a][1v][1a]concat=n=2:v=1:a=1[outv][outa]" -map [outv] -map [outa] out.mxf

How can i get all the 8 audio channels in the output. I have tried the below, as an attempt to get two audio channels, but does work

ffmpeg -i c:\process\abc.mxf -filter_complex \
"[0:v]trim=600:2663,setpts=PTS-STARTPTS,format=yuv420p[0v]; \
[0:a]atrim=600:2663,asetpts=PTS-STARTPTS[0a]; \
[0:b]atrim=600:2663,asetpts=PTS-STARTPTS[2a]; \
[0:v]trim=2886:3286,setpts=PTS-STARTPTS,format=yuv420p[1v]; \
[0:a]atrim=2886:3286,asetpts=PTS-STARTPTS[1a];
[0:b]atrim=600:2663,asetpts=PTS-STARTPTS[3a];  \
[0v][0a][2a][1v][1a][3a]concat=n=6:v=1:a=2[outv][outa]" -map [outv] -map [outa] out.mxf

Any hint will be much appreciated.

ANOTHER ATTEMPT

ffmpeg -i c:\process\3010010155-TCRHD.mxf -filter_complex " \
[0:v]trim=600:2663,setpts=PTS-STARTPTS,format=yuv420p[0v]; \
[0:a:0]atrim=600:2663,asetpts=PTS-STARTPTS[0a]; \
[0:a:1]atrim=600:2663,asetpts=PTS-STARTPTS[2a]; \
[0:v]trim=2886:3286,setpts=PTS-STARTPTS,format=yuv420p[1v]; \
[0:a:0]atrim=2886:3286,asetpts=PTS-STARTPTS[1a]; \
[0:a:1]atrim=600:2663,asetpts=PTS-STARTPTS[3a]; \
[0v][0a][2a][1v][1a][3a]concat=n=6:v=1:a=2[outv][outa]" -map [outv] -map [outa] out.mxf

This gives me an error Cannot find a matching stream for unlabeled input pad 6 on filter Parsed_concat_14


问:
Setting up triggers in MySQL
I am trying to create a trigger where a new record populates in another table when I enter data into table "employee." However, I am getting an error. Here is the trigger I have so far:

```<code>Create trigger empaftertrigger after INSERT ON employee
FOR EACH ROW
Insert into tbl_employee_audit (emp_id, audit_data) values (new.emp_id, "New employee with ID "new.emp_id "was added on " NOW());
</code>```

Error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'new.emp_id "was added on " NOW())' at line 3

I must have the new.emp_id populate in between the string that is supposed to enter the column for audit data. Thanks in advance for the help.

Title: Setting up triggers in MySQL

Body:
I am trying to create a trigger where a new record populates in another table when I enter data into table "employee." However, I am getting an error. Here is the trigger I have so far:

Create trigger empaftertrigger after INSERT ON employee
FOR EACH ROW
Insert into tbl_employee_audit (emp_id, audit_data) values (new.emp_id, "New employee with ID "new.emp_id "was added on " NOW());

Error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'new.emp_id "was added on " NOW())' at line 3

I must have the new.emp_id populate in between the string that is supposed to enter the column for audit data. Thanks in advance for the help.


问:
How does JS handle floating point multiplication?

Can someone please explain the above behavior?


问:
How to send form data(like HTTP POST) containing image and text via Rsocket?
I want the functionality similar to HTTP POST using Rsocket. Using Rsocket's request/response pattern, the data(image file and text) needs to be send and confirmation will be sent back to requester.

I tried to create a simple CustomData class to test :

RSocket Requester :

```<code>            RSocketRequester req = RSocketRequester.builder()
                .websocket(URI.create("ws://localhost:7000/rsocket"));

            req.route("message")
                .data(Mono.just(new CustomData("name", 12)), CustomData.class)
                .retrieveMono(String.class).subscribe((value) -> {
                    System.out.println(value);
                });
</code>```

Message Handler:

```<code>        @MessageMapping("message")
        public Mono<String> response(@Payload CustomData cData) {
            return Mono.just("data received!");
        }
</code>```

I am getting this exception :

```<code>java.lang.IllegalArgumentException: No encoder for com.demo1.demo.customdata.CustomData
</code>```

Can anyone please provide an example to fulfil this?

Body:
I want the functionality similar to HTTP POST using Rsocket. Using Rsocket's request/response pattern, the data(image file and text) needs to be send and confirmation will be sent back to requester.

I tried to create a simple CustomData class to test :

RSocket Requester :

            RSocketRequester req = RSocketRequester.builder()
                .websocket(URI.create("ws://localhost:7000/rsocket"));

            req.route("message")
                .data(Mono.just(new CustomData("name", 12)), CustomData.class)
                .retrieveMono(String.class).subscribe((value) -> {
                    System.out.println(value);
                });

Message Handler:

        @MessageMapping("message")
        public Mono<String> response(@Payload CustomData cData) {
            return Mono.just("data received!");
        }

I am getting this exception :

java.lang.IllegalArgumentException: No encoder for com.demo1.demo.customdata.CustomData

Can anyone please provide an example to fulfil this?


问:
Checking the data properties in mat_dialog_data to *ngIf statement
enter image description here

In the image above, I want to show the 2nd field which is PLEASE SELECT SUPPLIER GROUP if FARM is selected on the list.

in editDATA function I want to pass the

```<code>leftVal && resData['setting_val'][0]
</code>```

values in mat_dialog_data to div "*ngIf" statement in HTML below.

What I've tried but it reads only the first value.

```<code>//FUNCTION
editData() {
     let resData = this.formData.value
        , leftVal = this.formData.value.setting_col
     if (leftVal == "Farm") {
      let dr = this.dialog.open(AddSettingComponent, {
       data: leftVal && resData['setting_val'][0]
      ///// I WANT THIS data object here to pass both assign values to div
      });

      dr.afterClosed().subscribe((result: any) => {
        this.selectData([this.temdata]);

      });

     } else {
      this.alertService.onWarning('please select item to update');

    }

  }
</code>```

HTML

```<code> <mat-form-field appearance="outline" *ngIf="this.data[0] == 'Farm'" style="margin-left: 0.5rem;">
                <mat-label>Please select supplier group</mat-label>
                    <mat-select formControlName='header_id'>
                       <mat-option *ngFor="let val of SupplierGroup" [value]='val.setting_id'>
                          {{val.setting_value}}
                       </mat-option>
                    </mat-select>
                  </mat-form-field>
</code>```

Body:
enter image description here

In the image above, I want to show the 2nd field which is PLEASE SELECT SUPPLIER GROUP if FARM is selected on the list.

in editDATA function I want to pass the

leftVal && resData['setting_val'][0]

values in mat_dialog_data to div "*ngIf" statement in HTML below.

What I've tried but it reads only the first value.

//FUNCTION
editData() {
     let resData = this.formData.value
        , leftVal = this.formData.value.setting_col
     if (leftVal == "Farm") {
      let dr = this.dialog.open(AddSettingComponent, {
       data: leftVal && resData['setting_val'][0]
      ///// I WANT THIS data object here to pass both assign values to div
      });

      dr.afterClosed().subscribe((result: any) => {
        this.selectData([this.temdata]);

      });

     } else {
      this.alertService.onWarning('please select item to update');

    }

  }

HTML

 <mat-form-field appearance="outline" *ngIf="this.data[0] == 'Farm'" style="margin-left: 0.5rem;">
                <mat-label>Please select supplier group</mat-label>
                    <mat-select formControlName='header_id'>
                       <mat-option *ngFor="let val of SupplierGroup" [value]='val.setting_id'>
                          {{val.setting_value}}
                       </mat-option>
                    </mat-select>
                  </mat-form-field>


问:
I am trying to insert a map into my flutter app but i keep getting erros
Below are the errors i keep getting when running my code. I researched online and tried changing and adding information in my pupspec.yaml which i saw online, but i still keep getting these errors. I also added some information in my androidmanifest.xml from examples i saw but still kept getting the same errors.

```<code>I/PlatformViewsController(32458): Using hybrid composition for platform view: 3
E/BufferItemConsumer(32458): [ImageReader-1080x1812f1m3-32458-0] Failed to release buffer: Unknown error -1 (1)
E/PlatformViewsController(32458): Disposing platform view threw an exception
E/PlatformViewsController(32458): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.AbstractCollection.isEmpty()' on a null object reference
E/PlatformViewsController(32458):   at com.google.android.gms.dynamic.DeferredLifecycleHelper.zae(com.google.android.gms:play-services-base@@18.0.1:1)
E/PlatformViewsController(32458):   at com.google.android.gms.dynamic.DeferredLifecycleHelper.onDestroy(com.google.android.gms:play-services-base@@18.0.1:2)
E/PlatformViewsController(32458):   at com.google.android.gms.maps.MapView.onDestroy(com.google.android.gms:play-services-maps@@18.1.0:1)
E/PlatformViewsController(32458):   at io.flutter.plugins.googlemaps.GoogleMapController.destroyMapViewIfNecessary(GoogleMapController.java:891)
E/PlatformViewsController(32458):   at io.flutter.plugins.googlemaps.GoogleMapController.dispose(GoogleMapController.java:578)
E/PlatformViewsController(32458):   at io.flutter.plugin.platform.PlatformViewsController$1.dispose(PlatformViewsController.java:376)
E/PlatformViewsController(32458):   at io.flutter.embedding.en
</code>```

Below is the code which i am running for the google maps to display in the app.

```<code>class CurrentLocationView extends StatefulWidget {
  const CurrentLocationView({super.key});

  @override
  State<CurrentLocationView> createState() => _CurrentLocationViewState();
}

class _CurrentLocationViewState extends State<CurrentLocationView> {
  late GoogleMapController googleMapController;

  static const CameraPosition initialCameraPosition = CameraPosition(
    target: LatLng(
      52.586971,
      -2.128820,
    ),
    zoom: 14,
  );

  Set<Marker> markers = {};

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Center(child: const Text('User current location')),
        backgroundColor: Colors.deepPurple[200],
        elevation: 0,
      ),
      body: GoogleMap(
        initialCameraPosition: initialCameraPosition,
        markers: markers,
        zoomControlsEnabled: false,
        mapType: MapType.normal,
        onMapCreated: (GoogleMapController controller) {
          googleMapController = controller;
        },
      ),
    );
  }
}
</code>```

Body:
Below are the errors i keep getting when running my code. I researched online and tried changing and adding information in my pupspec.yaml which i saw online, but i still keep getting these errors. I also added some information in my androidmanifest.xml from examples i saw but still kept getting the same errors.

I/PlatformViewsController(32458): Using hybrid composition for platform view: 3
E/BufferItemConsumer(32458): [ImageReader-1080x1812f1m3-32458-0] Failed to release buffer: Unknown error -1 (1)
E/PlatformViewsController(32458): Disposing platform view threw an exception
E/PlatformViewsController(32458): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.AbstractCollection.isEmpty()' on a null object reference
E/PlatformViewsController(32458):   at com.google.android.gms.dynamic.DeferredLifecycleHelper.zae(com.google.android.gms:play-services-base@@18.0.1:1)
E/PlatformViewsController(32458):   at com.google.android.gms.dynamic.DeferredLifecycleHelper.onDestroy(com.google.android.gms:play-services-base@@18.0.1:2)
E/PlatformViewsController(32458):   at com.google.android.gms.maps.MapView.onDestroy(com.google.android.gms:play-services-maps@@18.1.0:1)
E/PlatformViewsController(32458):   at io.flutter.plugins.googlemaps.GoogleMapController.destroyMapViewIfNecessary(GoogleMapController.java:891)
E/PlatformViewsController(32458):   at io.flutter.plugins.googlemaps.GoogleMapController.dispose(GoogleMapController.java:578)
E/PlatformViewsController(32458):   at io.flutter.plugin.platform.PlatformViewsController$1.dispose(PlatformViewsController.java:376)
E/PlatformViewsController(32458):   at io.flutter.embedding.en

Below is the code which i am running for the google maps to display in the app.

class CurrentLocationView extends StatefulWidget {
  const CurrentLocationView({super.key});

  @override
  State<CurrentLocationView> createState() => _CurrentLocationViewState();
}

class _CurrentLocationViewState extends State<CurrentLocationView> {
  late GoogleMapController googleMapController;

  static const CameraPosition initialCameraPosition = CameraPosition(
    target: LatLng(
      52.586971,
      -2.128820,
    ),
    zoom: 14,
  );

  Set<Marker> markers = {};

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Center(child: const Text('User current location')),
        backgroundColor: Colors.deepPurple[200],
        elevation: 0,
      ),
      body: GoogleMap(
        initialCameraPosition: initialCameraPosition,
        markers: markers,
        zoomControlsEnabled: false,
        mapType: MapType.normal,
        onMapCreated: (GoogleMapController controller) {
          googleMapController = controller;
        },
      ),
    );
  }
}


问:
IBM Content Navigator - Merge and Split for TXT files
I am currently exploring Merge and Split functionality of Navigator application and observed some interesting thing about TXT files.

I have configured ICN Desktop to use Daeja ViewONE Vitual viewer for all non-MS OFFICE files. I can see Merge and Split menu option does not get displayed for TXT files whereas it gets displayed for most of other format files like TIFF, PDF, JPG, etc.

As per my understanding, because TXT files do not have pages, the said functionality is not applicable to these files. Is that the only reason behind it or there is something more?

I tried to look for IBM documentation but could not find any.

Any pointers would be appreciated. Thanks in advance.


问:
Performance issue with Pandas when aggregating using a custom defined function
I have database of above 500.000 records and 140 MB (when stored as CSV). Pandas takes about 1.5 seconds to load it, parsing dates included. Is not a problem at all. Now, I have a Python program that is continuously creating more records, which I want to add to the database (I also remove older records, so the database has a fairly stable size). And I'm facing a performance issue, as adding the new records takes longer than the process creating such records.

For adding these new records, I basically merge the freshly obtained Dataframe with the one that contains the database, which is loaded from a CSV file, i.e.:

```<code># read the database
old_df = pd.read_csv('database.csv',
                 index_col=False,
                 parse_dates=['date'],
                 dtype=dtypes)

# some process produces new_df

# I merge them by just concatenating
merged = pd.concat([df, df2])
</code>```

This step is even faster, so no problem so far. Perhaps it's worth to note that the new_df is tiny compared to old_df. Typically less than 10 new records are added each time.

Now, a particularity of this database is that some of the new records are supposed to replace their counterpart in the database, i.e. they not just grow but update it (The details are not important for the problem, but for a bit of context, the database keeps memory of previous fails in the column type, which can be either 'success' or' 'failed', that correspond to attempts to get a file stored in the column file. This way, when a latter attempts of the program success, the record for the fail is replaced by the success.)

The replacement consists of grouping the database by the column file, so each file is unique. Once grouped, I need to aggregate to define a value for type, so I keep just one record for the given file. And my problem is that the aggregation is done through a user defined function that has become a bottleneck of the program.

This code:

```<code>merged = merged.groupby('file', as_index=False).agg({'type': 'last'})
</code>```

runs in less than a second, whereas this:

```<code>def keep_success(x):
   """! Auxiliary function to keep `success` if it exist."""
   if (x == "success").any():
       return 'success'
   else:
       return x.iloc[-1]

merged = merged.groupby('file', as_index=False).agg({'type': keep_success})
</code>```

takes more than a minute. So far I was using 'last', but a change in my program made that sometimes 'success' is previous to 'fail', so I need to account for the unknown order of these two values.

TL;DR; I need a FAST way to aggregate records in a Dataframe sharing the file column, and keeping just the value 'success' for the column type in case there is any occurrence of this value within the group. Otherwise we keep 'failed'

EDIT to add my guess:
I think the problem is in the string comparison. The program has to go through ALL the database making trivial/useless comparisons that systematically are not fulfilled. To replace about 10 records, we need to check the equity of above 500.000 strings. Can I work around this taking advantage of what I known, i.e. that most records, once grouped, are unique so we do not need to do anything to with them?

Body:
I have database of above 500.000 records and 140 MB (when stored as CSV). Pandas takes about 1.5 seconds to load it, parsing dates included. Is not a problem at all. Now, I have a Python program that is continuously creating more records, which I want to add to the database (I also remove older records, so the database has a fairly stable size). And I'm facing a performance issue, as adding the new records takes longer than the process creating such records.

For adding these new records, I basically merge the freshly obtained Dataframe with the one that contains the database, which is loaded from a CSV file, i.e.:

# read the database
old_df = pd.read_csv('database.csv',
                 index_col=False,
                 parse_dates=['date'],
                 dtype=dtypes)

# some process produces new_df

# I merge them by just concatenating
merged = pd.concat([df, df2])

This step is even faster, so no problem so far. Perhaps it's worth to note that the new_df is tiny compared to old_df. Typically less than 10 new records are added each time.

Now, a particularity of this database is that some of the new records are supposed to replace their counterpart in the database, i.e. they not just grow but update it (The details are not important for the problem, but for a bit of context, the database keeps memory of previous fails in the column type, which can be either 'success' or' 'failed', that correspond to attempts to get a file stored in the column file. This way, when a latter attempts of the program success, the record for the fail is replaced by the success.)

The replacement consists of grouping the database by the column file, so each file is unique. Once grouped, I need to aggregate to define a value for type, so I keep just one record for the given file. And my problem is that the aggregation is done through a user defined function that has become a bottleneck of the program.

This code:

merged = merged.groupby('file', as_index=False).agg({'type': 'last'})

runs in less than a second, whereas this:

def keep_success(x):
   """! Auxiliary function to keep `success` if it exist."""
   if (x == "success").any():
       return 'success'
   else:
       return x.iloc[-1]

merged = merged.groupby('file', as_index=False).agg({'type': keep_success})

takes more than a minute. So far I was using 'last', but a change in my program made that sometimes 'success' is previous to 'fail', so I need to account for the unknown order of these two values.

TL;DR; I need a FAST way to aggregate records in a Dataframe sharing the file column, and keeping just the value 'success' for the column type in case there is any occurrence of this value within the group. Otherwise we keep 'failed'

EDIT to add my guess:
I think the problem is in the string comparison. The program has to go through ALL the database making trivial/useless comparisons that systematically are not fulfilled. To replace about 10 records, we need to check the equity of above 500.000 strings. Can I work around this taking advantage of what I known, i.e. that most records, once grouped, are unique so we do not need to do anything to with them?


问:
Javascript - If statement doesn't recognize variable update after another If statement executes
I have a variable called isHome set to false initially. Then I have a couple of functions to comeHome and greetMother that should execute depending on whether isHome is true or false.

After comeHome is called (because isHome = false ) it sets isHome to true. But how come the greetMother() isn't being called afterwards?

It would be nice to get an in-depth explanation for why I can't (programmatically) greet my mother :/

(Note: I don't have much exp with JS, this is my first SO question, and apologies in advance if I created a duplicate Q)

The code:

```<code>  let isHome = false;

  const comeHome = () => {
    isHome = true;
    console.log("Going home now");
  };

  const greetMother = () => {
    console.log("Hi Mom!");
  };

  if (isHome === false) {
    setTimeout(() => {
      comeHome();
    }, 2000);
  }

// console.log(isHome) here returns false

  if (isHome === true) {
    greetMother();
  }
</code>```

The output, and expected outcome

"Going home now"

I console-logged isHome on that line, and it still returns false even though comHome() sets it to true. My assumption is that JS can update global variables from inside functions without needing to use return , so this problem is unexpected for me.

What I tried:

I tried swapping the conditionals (true first, false second)

Tried using if..else if.. statements

Tried wrapping the whole code inside a function, then running that one function

Tried the object oriented approach, but same result.

```<code>class AppObj {
  constructor() {
    this.isHome = false;
  }

  comeHome() {
    this.isHome = true;
    console.log("Going home now");
  }

  greetMother() {
    console.log("Hi Mom!");
  }

  run() {
    if (this.isHome === false) {
      setTimeout(() => {
        this.comeHome();
      }, 2000);
    }
    if (this.isHome === true) {
      this.greetMother();
    }
  }
}

const appObj = new AppObj();
appObj.run()
</code>```

Body:
I have a variable called isHome set to false initially. Then I have a couple of functions to comeHome and greetMother that should execute depending on whether isHome is true or false.

After comeHome is called (because isHome = false ) it sets isHome to true. But how come the greetMother() isn't being called afterwards?

It would be nice to get an in-depth explanation for why I can't (programmatically) greet my mother :/

(Note: I don't have much exp with JS, this is my first SO question, and apologies in advance if I created a duplicate Q)

The code:

  let isHome = false;

  const comeHome = () => {
    isHome = true;
    console.log("Going home now");
  };

  const greetMother = () => {
    console.log("Hi Mom!");
  };

  if (isHome === false) {
    setTimeout(() => {
      comeHome();
    }, 2000);
  }

// console.log(isHome) here returns false

  if (isHome === true) {
    greetMother();
  }

The output, and expected outcome

"Going home now"

I console-logged isHome on that line, and it still returns false even though comHome() sets it to true. My assumption is that JS can update global variables from inside functions without needing to use return , so this problem is unexpected for me.

What I tried:

I tried swapping the conditionals (true first, false second)

Tried using if..else if.. statements

Tried wrapping the whole code inside a function, then running that one function

Tried the object oriented approach, but same result.

class AppObj {
  constructor() {
    this.isHome = false;
  }

  comeHome() {
    this.isHome = true;
    console.log("Going home now");
  }

  greetMother() {
    console.log("Hi Mom!");
  }

  run() {
    if (this.isHome === false) {
      setTimeout(() => {
        this.comeHome();
      }, 2000);
    }
    if (this.isHome === true) {
      this.greetMother();
    }
  }
}

const appObj = new AppObj();
appObj.run()


问:
from azure.eventhub.aio import EventHubConsumerClient ModuleNotFoundError: No module named 'azure'
I try to run the below following code using python3 recv.py on visual studio code but I'm getting the following error

```<code>Traceback (most recent call last):
  File "recv.py", line 2, in <module>
    from azure.eventhub.aio import EventHubConsumerClient
ModuleNotFoundError: No module named 'azure'
</code>```

import asyncio
from azure.eventhub.aio import EventHubConsumerClient
from azure.eventhub.extensions.checkpointstoreblobaio import BlobCheckpointStore

async def on_event(partition_context, event):
    # Print the event data.
    print("Received the event: \"{}\" from the partition with ID: \"{}\"".format(event.body_as_str(encoding='UTF-8'), partition_context.partition_id))

    # Update the checkpoint so that the program doesn't read the events
    # that it has already read when you run it next time.
    await partition_context.update_checkpoint(event)

async def main():
    # Create an Azure blob checkpoint store to store the checkpoints.
    checkpoint_store = BlobCheckpointStore.from_connection_string("connection_string", "containername")

    # Create a consumer client for the event hub.
    client = EventHubConsumerClient.from_connection_string("connection_string", consumer_group="$Default", eventhub_name="eventhubinstance", checkpoint_store=checkpoint_store)
    async with client:
        # Call the receive method. Read from the beginning of the partition (starting_position: "-1")
        await client.receive(on_event=on_event,  starting_position="-1")

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    # Run the main method.
    loop.run_until_complete(main())```

I try to execute the file on my iTerm terminal and it's working fine. Can you tell me why it is n ot working in vscode?

I'm using Python 3.7.9

I have installed the package using pip3 install azure-eventhub (I have also tried with just pip) but the modules are still interpreting as missing whereas there are not.

Using pip show azure-eventhub WARNING: Package(s) not found: azure-eventhub but it is there I can see the package in /usr/local/lib/python3.10/site-packages

Body:
I try to run the below following code using python3 recv.py on visual studio code but I'm getting the following error

Traceback (most recent call last):
  File "recv.py", line 2, in <module>
    from azure.eventhub.aio import EventHubConsumerClient
ModuleNotFoundError: No module named 'azure'

import asyncio
from azure.eventhub.aio import EventHubConsumerClient
from azure.eventhub.extensions.checkpointstoreblobaio import BlobCheckpointStore

async def on_event(partition_context, event):
    # Print the event data.
    print("Received the event: \"{}\" from the partition with ID: \"{}\"".format(event.body_as_str(encoding='UTF-8'), partition_context.partition_id))

    # Update the checkpoint so that the program doesn't read the events
    # that it has already read when you run it next time.
    await partition_context.update_checkpoint(event)

async def main():
    # Create an Azure blob checkpoint store to store the checkpoints.
    checkpoint_store = BlobCheckpointStore.from_connection_string("connection_string", "containername")

    # Create a consumer client for the event hub.
    client = EventHubConsumerClient.from_connection_string("connection_string", consumer_group="$Default", eventhub_name="eventhubinstance", checkpoint_store=checkpoint_store)
    async with client:
        # Call the receive method. Read from the beginning of the partition (starting_position: "-1")
        await client.receive(on_event=on_event,  starting_position="-1")

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    # Run the main method.
    loop.run_until_complete(main())

I try to execute the file on my iTerm terminal and it's working fine. Can you tell me why it is n ot working in vscode?

I'm using Python 3.7.9

I have installed the package using pip3 install azure-eventhub (I have also tried with just pip) but the modules are still interpreting as missing whereas there are not.

Using pip show azure-eventhub WARNING: Package(s) not found: azure-eventhub but it is there I can see the package in /usr/local/lib/python3.10/site-packages


问:
Prisma schema - Build up a custom object from a relation
Can I build a custom object using a relation, and the properties that it references?

For example, if I have two models like this, where User is populated during authentication:

```<code>model User {
  id            String    @id @default(cuid()) @map("_id")
  name          String?
  email         String?   @unique
}

model Post {
  id          String   @id @default(auto()) @map("_id") @db.ObjectId
  title       String
  description String
  authorId    String
  authorEmail String
  authorName  String
  user        User     @relation(fields: [authorId, authorEmail, authorName], references: [id, email, name])
}
</code>```

This will take the user details and push them, individually, into authorId, authorName and authorEmail. What I would like is some way of loading them into an embedded document called author, like so:

```<code>model Post {
  id          String   @id @default(auto()) @map("_id") @db.ObjectId
  title       String
  description String
  author      Author
  user        User     @relation(fields: [author], references: [id, email, name])
}

type Author {
  id    String
  name  String
  email String
}
</code>```

Is this at all possible? I feel like I've tried everything.

Body:
Can I build a custom object using a relation, and the properties that it references?

For example, if I have two models like this, where User is populated during authentication:

model User {
  id            String    @id @default(cuid()) @map("_id")
  name          String?
  email         String?   @unique
}

model Post {
  id          String   @id @default(auto()) @map("_id") @db.ObjectId
  title       String
  description String
  authorId    String
  authorEmail String
  authorName  String
  user        User     @relation(fields: [authorId, authorEmail, authorName], references: [id, email, name])
}

This will take the user details and push them, individually, into authorId, authorName and authorEmail. What I would like is some way of loading them into an embedded document called author, like so:

model Post {
  id          String   @id @default(auto()) @map("_id") @db.ObjectId
  title       String
  description String
  author      Author
  user        User     @relation(fields: [author], references: [id, email, name])
}

type Author {
  id    String
  name  String
  email String
}

Is this at all possible? I feel like I've tried everything.


问:
Add MySQL column comment as a metadata to Avro schema through the Debezium connector
Kafka Connect is used through the Confluent platform and io.debezium.connector.mysql.MySqlConnector is used as the Debezium connector.

In my case, MySQL table includes columns with sensitive data and these columns must be tagged as sensitive for further use.

```<code>SHOW FULL COLUMNS FROM astronauts;
+---------+--------------+--------------------+------+-----+---------+-------+---------------------------------+------------------+
| Field   | Type         | Collation          | Null | Key | Default | Extra | Privileges                      | Comment          |
+---------+--------------+--------------------+------+-----+---------+-------+---------------------------------+------------------+
| orderid | int          | NULL               | YES  |     | NULL    |       | select,insert,update,references |                  |
| name    | varchar(100) | utf8mb4_0900_ai_ci | NO   |     | NULL    |       | select,insert,update,references | sensitive column |
+---------+--------------+--------------------+------+-----+---------+-------+---------------------------------+------------------+
</code>```

Notice MySQL comment for the name column.

Based on this table, I would like to have this Avro schema in the Schema registry:

```<code>{
  "connect.name": "dbserver1.inventory.astronauts.Envelope",
  "connect.version": 1,
  "fields": [
    {
      "default": null,
      "name": "before",
      "type": [
        "null",
        {
          "connect.name": "dbserver1.inventory.astronauts.Value",
          "fields": [
            {
              "default": null,
              "name": "orderid",
              "type": [
                "null",
                "int"
              ]
            },
            {
              "name": "name",
              "type": {
                "MY_CUSTOM_ATTRIBUTE": "sensitive column",
                "type": "string"
              }
            }
          ],
          "name": "Value",
          "type": "record"
        }
      ]
    },
    {
      "default": null,
      "name": "after",
      "type": [
        "null",
        "Value"
      ]
    },
    {
      "name": "source",
      "type": {
        "connect.name": "io.debezium.connector.mysql.Source",
        "fields": [
          {
            "name": "version",
            "type": "string"
          },
          {
            "name": "connector",
            "type": "string"
          },
          {
            "name": "name",
            "type": "string"
          },
          {
            "name": "ts_ms",
            "type": "long"
          },
          {
            "default": "false",
            "name": "snapshot",
            "type": [
              {
                "connect.default": "false",
                "connect.name": "io.debezium.data.Enum",
                "connect.parameters": {
                  "allowed": "true,last,false,incremental"
                },
                "connect.version": 1,
                "type": "string"
              },
              "null"
            ]
          },
          {
            "name": "db",
            "type": "string"
          },
          {
            "default": null,
            "name": "sequence",
            "type": [
              "null",
              "string"
            ]
          },
          {
            "default": null,
            "name": "table",
            "type": [
              "null",
              "string"
            ]
          },
          {
            "name": "server_id",
            "type": "long"
          },
          {
            "default": null,
            "name": "gtid",
            "type": [
              "null",
              "string"
            ]
          },
          {
            "name": "file",
            "type": "string"
          },
          {
            "name": "pos",
            "type": "long"
          },
          {
            "name": "row",
            "type": "int"
          },
          {
            "default": null,
            "name": "thread",
            "type": [
              "null",
              "long"
            ]
          },
          {
            "default": null,
            "name": "query",
            "type": [
              "null",
              "string"
            ]
          }
        ],
        "name": "Source",
        "namespace": "io.debezium.connector.mysql",
        "type": "record"
      }
    },
    {
      "name": "op",
      "type": "string"
    },
    {
      "default": null,
      "name": "ts_ms",
      "type": [
        "null",
        "long"
      ]
    },
    {
      "default": null,
      "name": "transaction",
      "type": [
        "null",
        {
          "connect.name": "event.block",
          "connect.version": 1,
          "fields": [
            {
              "name": "id",
              "type": "string"
            },
            {
              "name": "total_order",
              "type": "long"
            },
            {
              "name": "data_collection_order",
              "type": "long"
            }
          ],
          "name": "block",
          "namespace": "event",
          "type": "record"
        }
      ]
    }
  ],
  "name": "Envelope",
  "namespace": "dbserver1.inventory.astronauts",
  "type": "record"
}
</code>```

Notice the custom schema field named MY_CUSTOM_ATTRIBUTE.

Debezium 2.0 supports schema doc from column comments [DBZ-5489], however, personally I think the doc field attribute is not appropriate since:

any implementation of a schema registry or system that processes the schemas is free to drop those fields when encoding/decoding and its fully spec compliant

Additionally, the doc field is solely intended to provide information to a user of the schema and is not intended as a form of metadata that downstream programs can rely on

source: https://avro.apache.org/docs/1.10.2/spec.html#Schema+Resolution

Based on the Avro schema docs, custom attributes for Avro schemas are allowed and these attributes are known as metadata:

A JSON object, of the form:

{"type": "typeName" ...attributes...}

where typeName is either a primitive or derived type name, as defined below. Attributes not defined in this document are permitted as metadata, but must not affect the format of serialized data.

source: https://avro.apache.org/docs/1.10.2/spec.html#schemas

I think Debezium transformations might be a solution, however, I have the following problems:

No idea how to get MySQL column comments in my custom transformation

org.apache.kafka.connect.data.SchemaBuilder does not allow to add custom attributes, afaik just doc and the specific field

Here are several native transformations for reference: https://github.com/apache/kafka/tree/trunk/connect/transforms/src/main/java/org/apache/kafka/connect/transforms/

Body:
Kafka Connect is used through the Confluent platform and io.debezium.connector.mysql.MySqlConnector is used as the Debezium connector.

In my case, MySQL table includes columns with sensitive data and these columns must be tagged as sensitive for further use.

SHOW FULL COLUMNS FROM astronauts;
+---------+--------------+--------------------+------+-----+---------+-------+---------------------------------+------------------+
| Field   | Type         | Collation          | Null | Key | Default | Extra | Privileges                      | Comment          |
+---------+--------------+--------------------+------+-----+---------+-------+---------------------------------+------------------+
| orderid | int          | NULL               | YES  |     | NULL    |       | select,insert,update,references |                  |
| name    | varchar(100) | utf8mb4_0900_ai_ci | NO   |     | NULL    |       | select,insert,update,references | sensitive column |
+---------+--------------+--------------------+------+-----+---------+-------+---------------------------------+------------------+

Notice MySQL comment for the name column.

Based on this table, I would like to have this Avro schema in the Schema registry:

{
  "connect.name": "dbserver1.inventory.astronauts.Envelope",
  "connect.version": 1,
  "fields": [
    {
      "default": null,
      "name": "before",
      "type": [
        "null",
        {
          "connect.name": "dbserver1.inventory.astronauts.Value",
          "fields": [
            {
              "default": null,
              "name": "orderid",
              "type": [
                "null",
                "int"
              ]
            },
            {
              "name": "name",
              "type": {
                "MY_CUSTOM_ATTRIBUTE": "sensitive column",
                "type": "string"
              }
            }
          ],
          "name": "Value",
          "type": "record"
        }
      ]
    },
    {
      "default": null,
      "name": "after",
      "type": [
        "null",
        "Value"
      ]
    },
    {
      "name": "source",
      "type": {
        "connect.name": "io.debezium.connector.mysql.Source",
        "fields": [
          {
            "name": "version",
            "type": "string"
          },
          {
            "name": "connector",
            "type": "string"
          },
          {
            "name": "name",
            "type": "string"
          },
          {
            "name": "ts_ms",
            "type": "long"
          },
          {
            "default": "false",
            "name": "snapshot",
            "type": [
              {
                "connect.default": "false",
                "connect.name": "io.debezium.data.Enum",
                "connect.parameters": {
                  "allowed": "true,last,false,incremental"
                },
                "connect.version": 1,
                "type": "string"
              },
              "null"
            ]
          },
          {
            "name": "db",
            "type": "string"
          },
          {
            "default": null,
            "name": "sequence",
            "type": [
              "null",
              "string"
            ]
          },
          {
            "default": null,
            "name": "table",
            "type": [
              "null",
              "string"
            ]
          },
          {
            "name": "server_id",
            "type": "long"
          },
          {
            "default": null,
            "name": "gtid",
            "type": [
              "null",
              "string"
            ]
          },
          {
            "name": "file",
            "type": "string"
          },
          {
            "name": "pos",
            "type": "long"
          },
          {
            "name": "row",
            "type": "int"
          },
          {
            "default": null,
            "name": "thread",
            "type": [
              "null",
              "long"
            ]
          },
          {
            "default": null,
            "name": "query",
            "type": [
              "null",
              "string"
            ]
          }
        ],
        "name": "Source",
        "namespace": "io.debezium.connector.mysql",
        "type": "record"
      }
    },
    {
      "name": "op",
      "type": "string"
    },
    {
      "default": null,
      "name": "ts_ms",
      "type": [
        "null",
        "long"
      ]
    },
    {
      "default": null,
      "name": "transaction",
      "type": [
        "null",
        {
          "connect.name": "event.block",
          "connect.version": 1,
          "fields": [
            {
              "name": "id",
              "type": "string"
            },
            {
              "name": "total_order",
              "type": "long"
            },
            {
              "name": "data_collection_order",
              "type": "long"
            }
          ],
          "name": "block",
          "namespace": "event",
          "type": "record"
        }
      ]
    }
  ],
  "name": "Envelope",
  "namespace": "dbserver1.inventory.astronauts",
  "type": "record"
}

Notice the custom schema field named MY_CUSTOM_ATTRIBUTE.

Debezium 2.0 supports schema doc from column comments [DBZ-5489], however, personally I think the doc field attribute is not appropriate since:

any implementation of a schema registry or system that processes the schemas is free to drop those fields when encoding/decoding and its fully spec compliant

Additionally, the doc field is solely intended to provide information to a user of the schema and is not intended as a form of metadata that downstream programs can rely on

source: https://avro.apache.org/docs/1.10.2/spec.html#Schema+Resolution

Based on the Avro schema docs, custom attributes for Avro schemas are allowed and these attributes are known as metadata:

A JSON object, of the form:

{"type": "typeName" ...attributes...}

where typeName is either a primitive or derived type name, as defined below. Attributes not defined in this document are permitted as metadata, but must not affect the format of serialized data.

source: https://avro.apache.org/docs/1.10.2/spec.html#schemas

I think Debezium transformations might be a solution, however, I have the following problems:

No idea how to get MySQL column comments in my custom transformation

org.apache.kafka.connect.data.SchemaBuilder does not allow to add custom attributes, afaik just doc and the specific field

Here are several native transformations for reference: https://github.com/apache/kafka/tree/trunk/connect/transforms/src/main/java/org/apache/kafka/connect/transforms/


问:
Connection Error on trying to connect to a mssql database running in a docker container

Connection error on tring to connect to mssql 2019 db running in a docker container

```<code>const sql = require('mssql');

async function connectdb() {
  const config = {
    user: 'SA',
    password: 'password',
    server: 'container_name',
    database: 'database_name',
  };
try{

    const connection = await sql.connect(config);
    console.log('Connected to the database!');
}
catch(err){
    console.error('Error connecting to the database:', err)
}
}

connectdb()
</code>```

Expected behaviour: "Connected to db" logged to the console.

Actual behaviour: "Error connecting to the database: ConnectionError: Failed to connect to container_name:1433 - getaddrinfo EAI_AGAIN container_name" logged to the console

Body:
Connection error on tring to connect to mssql 2019 db running in a docker container

const sql = require('mssql');

async function connectdb() {
  const config = {
    user: 'SA',
    password: 'password',
    server: 'container_name',
    database: 'database_name',
  };
try{

    const connection = await sql.connect(config);
    console.log('Connected to the database!');
}
catch(err){
    console.error('Error connecting to the database:', err)
}
}

connectdb()

Expected behaviour: "Connected to db" logged to the console.

Actual behaviour: "Error connecting to the database: ConnectionError: Failed to connect to container_name:1433 - getaddrinfo EAI_AGAIN container_name" logged to the console


问:
How to read stream using Openai completion API in Swift - iOS?
I am trying to read the output in stream (as it comes) rather than waiting up for the whole response.

I have used the following code.

```<code>func caller() {
        let completionAPIURL = URL(string: "https://api.openai.com/v1/completions")!

        var request = URLRequest(url: completionAPIURL)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("<Token>", forHTTPHeaderField: "Authorization")

        let requestBody = """
        {
            "model": "<model>",
            "prompt": "<prompt>",
            "max_tokens": 200,
            "stream": true
        }
        """
        request.httpBody = requestBody.data(using: .utf8)

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Error: \(error)")
                return
            }

            print((response as? HTTPURLResponse)?.statusCode)

            guard let httpResponse = response as? HTTPURLResponse,
                  (200...299).contains(httpResponse.statusCode) else {
                print("Error: invalid HTTP response code")
                return
            }

            guard let data = data else {
                print("Error: missing response data")
                return
            }

            let eventStreamString = String(data: data, encoding: .utf8)!
            let eventStreamLines = eventStreamString.components(separatedBy: "\n")

            for event in eventStreamLines {
                let eventFields = event.components(separatedBy: ":")
                if eventFields.count < 2 {
                    continue
                }

                if fieldName == "data" {
                    if fieldValue == "[DONE]" {
                        // Stream terminated
                        break
                    } else {
                        // Process event data
                        print(event)
                    }
                }
            }
        }
        task.resume()
    }

</code>```

The problem is, it still waits till whole response is in place and then prints the data. What I am trying to achieve is to get the data as and how stream is generated, and not after the whole response is in place.

I am comparatively newbie and would expect a detailed help.

Body:
I am trying to read the output in stream (as it comes) rather than waiting up for the whole response.

I have used the following code.

func caller() {
        let completionAPIURL = URL(string: "https://api.openai.com/v1/completions")!

        var request = URLRequest(url: completionAPIURL)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("<Token>", forHTTPHeaderField: "Authorization")

        let requestBody = """
        {
            "model": "<model>",
            "prompt": "<prompt>",
            "max_tokens": 200,
            "stream": true
        }
        """
        request.httpBody = requestBody.data(using: .utf8)

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Error: \(error)")
                return
            }

            print((response as? HTTPURLResponse)?.statusCode)

            guard let httpResponse = response as? HTTPURLResponse,
                  (200...299).contains(httpResponse.statusCode) else {
                print("Error: invalid HTTP response code")
                return
            }

            guard let data = data else {
                print("Error: missing response data")
                return
            }

            let eventStreamString = String(data: data, encoding: .utf8)!
            let eventStreamLines = eventStreamString.components(separatedBy: "\n")

            for event in eventStreamLines {
                let eventFields = event.components(separatedBy: ":")
                if eventFields.count < 2 {
                    continue
                }

                if fieldName == "data" {
                    if fieldValue == "[DONE]" {
                        // Stream terminated
                        break
                    } else {
                        // Process event data
                        print(event)
                    }
                }
            }
        }
        task.resume()
    }

The problem is, it still waits till whole response is in place and then prints the data. What I am trying to achieve is to get the data as and how stream is generated, and not after the whole response is in place.

I am comparatively newbie and would expect a detailed help.


问:
GStreamer java: AppSink not receiving new_sample signal
I have the task to stream an IP camera's video stream (RTP/RTSP in h264) via J2EE application server to a browser. For this I am using GStreamer 1.21.3 (latest dev release) with the gstreamer-java library on top. We are aiming towards a Websocket solution as the traditional HLS introduces significant latency.
After having figured out what to do with the gst-launch executable on the commandline, I ended up with this code (for the moment):

```<code>/*
 * Configuration for RTSP over TCP to WebSocket:
 *  1. rtspsrc to ip camera
 *  2. rtph264depay ! h246parse to extract the h264 content
 *  3. mp4mux to create fragmented MP4
 *  4. appsink to grab the frames and use them in Websocket server
 */
final String gstPipeline = String.format("rtspsrc onvif-mode=true protocols=tcp user-id=%s user-pw=%s location=%s latency=200"
        + " ! rtph264depay ! h264parse"
        + " ! mp4mux streamable=true fragment-duration=5000"
        + " ! appsink name=sink", USERNAME, PASSWORD, uri);
final Pipeline pipeline = initGStreamerPipeline(gstPipeline);
// Add listener to consume the incoming data
final AppSink sink = (AppSink) pipeline.getElementByName("sink");
sink.setCaps(Caps.anyCaps());
sink.set("emit-signals", true);
sink.set("max-buffers", 50);
sink.connect((NEW_SAMPLE) appsink -> {
    final Sample sample = appsink.pullSample();
    if (sample == null)
    {
        return FlowReturn.OK;
    }

    final Buffer buffer = sample.getBuffer();
    try
    {
        final ByteBuffer buf = buffer.map(false);
        LOGGER.debug("Unicast HTTP/TCP message received: {}", new String(Hex.encodeHex(buf, true)));
        if (session != null)
        {
            try
            {
                buf.flip();
                session.getRemote().sendBytes(buf);
            }
            catch (final Exception e)
            {
                LOGGER.error("Failed to send data via WebSocket", e);
            }
        }
    }
    finally
    {
        buffer.unmap();
    }

    return FlowReturn.OK;
});
sink.connect((AppSink.EOS) s -> LOGGER.info("Appsink is EOS"));
sink.connect((AppSink.NEW_PREROLL) s -> {
    LOGGER.info("Appsink NEW_PREROLL");
    return FlowReturn.OK;
});

LOGGER.info("Connecting to {}", uri);

/**
 * Start the pipeline. Attach a bus listener to call Gst.quit on EOS or error.
 */
pipeline.getBus().connect((Bus.ERROR) ((source, code, message) -> {
    LOGGER.info(message);
    Gst.quit();
}));
pipeline.getBus().connect((Bus.EOS) (source) -> Gst.quit());
pipeline.play();

/**
 * Wait until Gst.quit() called.
 */
LOGGER.info("Starting to consume media stream...");
Gst.main();
pipeline.stop();
server.stop();
</code>```

Now I seem to be stuck here, because the AppSink at the end of the pipeline never gets its new_sample signal triggered. The complete example works like a charme when I replace the appsink with a filesink. I have noticed that there are some other threads (like this one) with similar problems which normally boil down to "you forgot to set emit-signals=true". Any ideas why my appsink gets no data?

Update:

It appears that the problem is the URL I am passing to the pipeline string. It has two query parameters: http://192.168.xx.xx:544/streaming?video=0&meta=1. If I remove the second parameter (and the ambersand along with it), the pipeline works. Unfortunately I found no docs how to escape URLs in the correct way so GStreamer can read it. Can anyone share such documentation?

Update 2:

It starts getting weired now: It looks like the name of the URL parameter is the problem. I have started to replace it with some dummy argument and it works. So the ambersand is not the problem. Then I used VLC media player to consume the stream with the &meta=1 in place which also worked. Is it possible that the string "meta" is treated special in gstreamer?

Body:
I have the task to stream an IP camera's video stream (RTP/RTSP in h264) via J2EE application server to a browser. For this I am using GStreamer 1.21.3 (latest dev release) with the gstreamer-java library on top. We are aiming towards a Websocket solution as the traditional HLS introduces significant latency.
After having figured out what to do with the gst-launch executable on the commandline, I ended up with this code (for the moment):

/*
 * Configuration for RTSP over TCP to WebSocket:
 *  1. rtspsrc to ip camera
 *  2. rtph264depay ! h246parse to extract the h264 content
 *  3. mp4mux to create fragmented MP4
 *  4. appsink to grab the frames and use them in Websocket server
 */
final String gstPipeline = String.format("rtspsrc onvif-mode=true protocols=tcp user-id=%s user-pw=%s location=%s latency=200"
        + " ! rtph264depay ! h264parse"
        + " ! mp4mux streamable=true fragment-duration=5000"
        + " ! appsink name=sink", USERNAME, PASSWORD, uri);
final Pipeline pipeline = initGStreamerPipeline(gstPipeline);
// Add listener to consume the incoming data
final AppSink sink = (AppSink) pipeline.getElementByName("sink");
sink.setCaps(Caps.anyCaps());
sink.set("emit-signals", true);
sink.set("max-buffers", 50);
sink.connect((NEW_SAMPLE) appsink -> {
    final Sample sample = appsink.pullSample();
    if (sample == null)
    {
        return FlowReturn.OK;
    }

    final Buffer buffer = sample.getBuffer();
    try
    {
        final ByteBuffer buf = buffer.map(false);
        LOGGER.debug("Unicast HTTP/TCP message received: {}", new String(Hex.encodeHex(buf, true)));
        if (session != null)
        {
            try
            {
                buf.flip();
                session.getRemote().sendBytes(buf);
            }
            catch (final Exception e)
            {
                LOGGER.error("Failed to send data via WebSocket", e);
            }
        }
    }
    finally
    {
        buffer.unmap();
    }

    return FlowReturn.OK;
});
sink.connect((AppSink.EOS) s -> LOGGER.info("Appsink is EOS"));
sink.connect((AppSink.NEW_PREROLL) s -> {
    LOGGER.info("Appsink NEW_PREROLL");
    return FlowReturn.OK;
});

LOGGER.info("Connecting to {}", uri);

/**
 * Start the pipeline. Attach a bus listener to call Gst.quit on EOS or error.
 */
pipeline.getBus().connect((Bus.ERROR) ((source, code, message) -> {
    LOGGER.info(message);
    Gst.quit();
}));
pipeline.getBus().connect((Bus.EOS) (source) -> Gst.quit());
pipeline.play();

/**
 * Wait until Gst.quit() called.
 */
LOGGER.info("Starting to consume media stream...");
Gst.main();
pipeline.stop();
server.stop();

Now I seem to be stuck here, because the AppSink at the end of the pipeline never gets its new_sample signal triggered. The complete example works like a charme when I replace the appsink with a filesink. I have noticed that there are some other threads (like this one) with similar problems which normally boil down to "you forgot to set emit-signals=true". Any ideas why my appsink gets no data?

Update:

It appears that the problem is the URL I am passing to the pipeline string. It has two query parameters: http://192.168.xx.xx:544/streaming?video=0&meta=1. If I remove the second parameter (and the ambersand along with it), the pipeline works. Unfortunately I found no docs how to escape URLs in the correct way so GStreamer can read it. Can anyone share such documentation?

Update 2:

It starts getting weired now: It looks like the name of the URL parameter is the problem. I have started to replace it with some dummy argument and it works. So the ambersand is not the problem. Then I used VLC media player to consume the stream with the &meta=1 in place which also worked. Is it possible that the string "meta" is treated special in gstreamer?


问:
How to dockerize nx monorepo which has a shared package.json on root?
I have an Nx Monorepo project which includes one frontend-next project, one gateway microservice and four microservices. They are sharing the same package.json. I am struggling with dockerizing them.

My project structure is like this:

```<code>├── monorepo-folder
|  |--apps
|    ├── frontend-next
|    |    ├── src
|    |    ├── Dockerfile
|    |    ├── tsconfig.build.json
|    |    ├── tsconfig.json
|    ├── api-gateway
|    |    ├── src
|    |    ├── Dockerfile
|    |    ├── tsconfig.build.json
|    |    ├── tsconfig.json
|    ├── user-service
|    |    ├── src
|    |    ├── Dockerfile
|    |    ├── tsconfig.build.json
|    |    ├── tsconfig.json
├── tsconfig.json
├── .dockerignore
├── nx.json
├── package.json
├── package-lock.json
├── yarn.lock
├── docker-compose.yml
├── .dockerignore
</code>```

Here is an example of the "Dockerfile" inside of each project:

```<code># microservice1/Dockerfile
FROM node:14

# Create app directory
WORKDIR /monorepo-folder/apps/user-service/

# Install app dependencies
COPY /monorepo-folder/package*.json ./
RUN npm install

# Bundle app source
COPY . .

EXPOSE 3000
CMD [ "npm", "start" ]
</code>```

I have run docker-compose build, and there was a warning about the COPY, but it disappeared too fast, so I couldn't catch it.

Here is my docker-compose.yml file:

```<code>version: '3.8'

services:
  postgres:
    image: postgres:14.1-alpine
    container_name: commerce-postgres-db
    environment:
      POSTGRES_DB: commerce
      POSTGRES_USER: ogeday
      POSTGRES_PASSWORD: develop
    volumes:
      - './_datastorage/postgres/data:/var/lib/postgresql/data'
    ports:
      - '5432:5432'
  rabbitmq:
    image: rabbitmq:3.8.9-management
    ports:
      - '5672:5672'
      - '15672:15672'
  kafka:
    image: wurstmeister/kafka:2.13-2.6.0
    ports:
      - '9092:9092'
    environment:
      KAFKA_LISTENERS: PLAINTEXT://:9092
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
      KAFKA_CREATE_TOPICS: 'my-topic:1:1'
  api-gateway:
    build: ./apps/api-gateway
    depends_on:
      - postgres
      - rabbitmq
      - kafka
    environment:
      DATABASE_URL: postgres://my_user:my_password@postgres:5432/my_database
      MESSAGE_BROKER_URL: amqp://guest:guest@rabbitmq:5672
      EVENT_BUS_URL: kafka:9092
  product-service:
    build: ./apps/product-service
    depends_on:
      - postgres
      - rabbitmq
      - kafka
    environment:
      DATABASE_URL: postgres://my_user:my_password@postgres:5432/my_database
      MESSAGE_BROKER_URL: amqp://guest:guest@rabbitmq:5672
      EVENT_BUS_URL: kafka:9092
  user-service:
    build: ./apps/user-service/
    depends_on:
      - postgres
      - rabbitmq
      - kafka
    environment:
      DATABASE_URL: postgres://my_user:my_password@postgres:5432/my_database
      MESSAGE_BROKER_URL: amqp://guest:guest@rabbitmq:5672
      EVENT_BUS_URL: kafka:9092
  order-service:
    build: ./apps/order-service/
    depends_on:
      - postgres
      - rabbitmq
      - kafka
    environment:
      DATABASE_URL: postgres://my_user:my_password@postgres:5432/my_database
      MESSAGE_BROKER_URL: amqp://guest:guest@rabbitmq:5672
      EVENT_BUS_URL: kafka:9092
  communication-engine:
    build: ./apps/communication-engine/
    depends_on:
      - postgres
      - rabbitmq
      - kafka
    environment:
      DATABASE_URL: postgres://my_user:my_password@postgres:5432/my_database
      MESSAGE_BROKER_URL: amqp://guest:guest@rabbitmq:5672
      EVENT_BUS_URL: kafka:9092
  frontend:
    build: ./apps/frontend-next/
    depends_on:
      - api-gateway
      - product-service
      - user-service
      - order-service
      - communication-engine
    ports:
      - '4200:4200'
    environment:
      API_URL: http://localhost:4200
      MESSAGE_BROKER_URL: amqp://guest:guest@rabbitmq:5672
      EVENT_BUS_URL: kafka:9092
volumes:
  my-database:
</code>```

I have run docker-compose up, and I got this error:

```<code>commerce-workspace-order-service-1         | npm ERR! code ENOENT
commerce-workspace-order-service-1         | npm ERR! syscall open
commerce-workspace-communication-engine-1  | npm ERR! code ENOENT
commerce-workspace-communication-engine-1  | npm ERR! syscall open
commerce-workspace-product-service-1       | npm ERR! code ENOENT
commerce-workspace-communication-engine-1  | npm ERR! path /commerce-apps/communication-engine/package.json
commerce-workspace-api-gateway-1           | npm ERR! code ENOENT
commerce-workspace-communication-engine-1  | npm ERR! errno -2
commerce-workspace-order-service-1         | npm ERR! path /commerce-workspace/apps/order-service/package.json
commerce-workspace-api-gateway-1           | npm ERR! syscall open
commerce-workspace-api-gateway-1           | npm ERR! path /commerce-workspace/apps/api-gateway/package.json
commerce-workspace-order-service-1         | npm ERR! errno -2
commerce-workspace-user-service-1          | npm ERR! code ENOENT
commerce-workspace-user-service-1          | npm ERR! syscall open
commerce-workspace-user-service-1          | npm ERR! path /commerce-workspace/apps/user-service/package.json
commerce-workspace-api-gateway-1           | npm ERR! errno -2
commerce-workspace-product-service-1       | npm ERR! syscall open
commerce-workspace-user-service-1          | npm ERR! errno -2
commerce-workspace-product-service-1       | npm ERR! path /commerce-workspace/apps/product-service/package.json
commerce-workspace-product-service-1       | npm ERR! errno -2
commerce-workspace-communication-engine-1  | npm ERR! enoent ENOENT: no such file or directory, open '/commerce-workspace/apps/communication-engine/package.json'
commerce-workspace-api-gateway-1           | npm ERR! enoent ENOENT: no such file or directory, open '/commerce-workspace/apps/api-gateway/package.json'
commerce-workspace-api-gateway-1           | npm ERR! enoent This is related to npm not being able to find a file.
</code>```

I understand that COPY is not working correctly.
Any idea or suggestion would be nice to solve that issue.
Thank you!

Body:
I have an Nx Monorepo project which includes one frontend-next project, one gateway microservice and four microservices. They are sharing the same package.json. I am struggling with dockerizing them.

My project structure is like this:

├── monorepo-folder
|  |--apps
|    ├── frontend-next
|    |    ├── src
|    |    ├── Dockerfile
|    |    ├── tsconfig.build.json
|    |    ├── tsconfig.json
|    ├── api-gateway
|    |    ├── src
|    |    ├── Dockerfile
|    |    ├── tsconfig.build.json
|    |    ├── tsconfig.json
|    ├── user-service
|    |    ├── src
|    |    ├── Dockerfile
|    |    ├── tsconfig.build.json
|    |    ├── tsconfig.json
├── tsconfig.json
├── .dockerignore
├── nx.json
├── package.json
├── package-lock.json
├── yarn.lock
├── docker-compose.yml
├── .dockerignore

Here is an example of the "Dockerfile" inside of each project:

# microservice1/Dockerfile
FROM node:14

# Create app directory
WORKDIR /monorepo-folder/apps/user-service/

# Install app dependencies
COPY /monorepo-folder/package*.json ./
RUN npm install

# Bundle app source
COPY . .

EXPOSE 3000
CMD [ "npm", "start" ]

I have run docker-compose build, and there was a warning about the COPY, but it disappeared too fast, so I couldn't catch it.

Here is my docker-compose.yml file:

version: '3.8'

services:
  postgres:
    image: postgres:14.1-alpine
    container_name: commerce-postgres-db
    environment:
      POSTGRES_DB: commerce
      POSTGRES_USER: ogeday
      POSTGRES_PASSWORD: develop
    volumes:
      - './_datastorage/postgres/data:/var/lib/postgresql/data'
    ports:
      - '5432:5432'
  rabbitmq:
    image: rabbitmq:3.8.9-management
    ports:
      - '5672:5672'
      - '15672:15672'
  kafka:
    image: wurstmeister/kafka:2.13-2.6.0
    ports:
      - '9092:9092'
    environment:
      KAFKA_LISTENERS: PLAINTEXT://:9092
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
      KAFKA_CREATE_TOPICS: 'my-topic:1:1'
  api-gateway:
    build: ./apps/api-gateway
    depends_on:
      - postgres
      - rabbitmq
      - kafka
    environment:
      DATABASE_URL: postgres://my_user:my_password@postgres:5432/my_database
      MESSAGE_BROKER_URL: amqp://guest:guest@rabbitmq:5672
      EVENT_BUS_URL: kafka:9092
  product-service:
    build: ./apps/product-service
    depends_on:
      - postgres
      - rabbitmq
      - kafka
    environment:
      DATABASE_URL: postgres://my_user:my_password@postgres:5432/my_database
      MESSAGE_BROKER_URL: amqp://guest:guest@rabbitmq:5672
      EVENT_BUS_URL: kafka:9092
  user-service:
    build: ./apps/user-service/
    depends_on:
      - postgres
      - rabbitmq
      - kafka
    environment:
      DATABASE_URL: postgres://my_user:my_password@postgres:5432/my_database
      MESSAGE_BROKER_URL: amqp://guest:guest@rabbitmq:5672
      EVENT_BUS_URL: kafka:9092
  order-service:
    build: ./apps/order-service/
    depends_on:
      - postgres
      - rabbitmq
      - kafka
    environment:
      DATABASE_URL: postgres://my_user:my_password@postgres:5432/my_database
      MESSAGE_BROKER_URL: amqp://guest:guest@rabbitmq:5672
      EVENT_BUS_URL: kafka:9092
  communication-engine:
    build: ./apps/communication-engine/
    depends_on:
      - postgres
      - rabbitmq
      - kafka
    environment:
      DATABASE_URL: postgres://my_user:my_password@postgres:5432/my_database
      MESSAGE_BROKER_URL: amqp://guest:guest@rabbitmq:5672
      EVENT_BUS_URL: kafka:9092
  frontend:
    build: ./apps/frontend-next/
    depends_on:
      - api-gateway
      - product-service
      - user-service
      - order-service
      - communication-engine
    ports:
      - '4200:4200'
    environment:
      API_URL: http://localhost:4200
      MESSAGE_BROKER_URL: amqp://guest:guest@rabbitmq:5672
      EVENT_BUS_URL: kafka:9092
volumes:
  my-database:

I have run docker-compose up, and I got this error:

commerce-workspace-order-service-1         | npm ERR! code ENOENT
commerce-workspace-order-service-1         | npm ERR! syscall open
commerce-workspace-communication-engine-1  | npm ERR! code ENOENT
commerce-workspace-communication-engine-1  | npm ERR! syscall open
commerce-workspace-product-service-1       | npm ERR! code ENOENT
commerce-workspace-communication-engine-1  | npm ERR! path /commerce-apps/communication-engine/package.json
commerce-workspace-api-gateway-1           | npm ERR! code ENOENT
commerce-workspace-communication-engine-1  | npm ERR! errno -2
commerce-workspace-order-service-1         | npm ERR! path /commerce-workspace/apps/order-service/package.json
commerce-workspace-api-gateway-1           | npm ERR! syscall open
commerce-workspace-api-gateway-1           | npm ERR! path /commerce-workspace/apps/api-gateway/package.json
commerce-workspace-order-service-1         | npm ERR! errno -2
commerce-workspace-user-service-1          | npm ERR! code ENOENT
commerce-workspace-user-service-1          | npm ERR! syscall open
commerce-workspace-user-service-1          | npm ERR! path /commerce-workspace/apps/user-service/package.json
commerce-workspace-api-gateway-1           | npm ERR! errno -2
commerce-workspace-product-service-1       | npm ERR! syscall open
commerce-workspace-user-service-1          | npm ERR! errno -2
commerce-workspace-product-service-1       | npm ERR! path /commerce-workspace/apps/product-service/package.json
commerce-workspace-product-service-1       | npm ERR! errno -2
commerce-workspace-communication-engine-1  | npm ERR! enoent ENOENT: no such file or directory, open '/commerce-workspace/apps/communication-engine/package.json'
commerce-workspace-api-gateway-1           | npm ERR! enoent ENOENT: no such file or directory, open '/commerce-workspace/apps/api-gateway/package.json'
commerce-workspace-api-gateway-1           | npm ERR! enoent This is related to npm not being able to find a file.

I understand that COPY is not working correctly.
Any idea or suggestion would be nice to solve that issue.
Thank you!


问:
Send Message with user mention to MS Teams
I want to send a simple message which will mention user via MS Teams Webhook connector.

I can send Adaptive Card with this

```<code>{
"type": "message",
"attachments": [
    {
    "contentType": "application/vnd.microsoft.card.adaptive",
    "content": {
        "type": "AdaptiveCard",
        "body": [
            {
                "type": "TextBlock",
                "size": "Medium",
                "weight": "Bolder",
                "text": "Card title here"
            },
            {
                "type": "TextBlock",
                "text": "<at>Name AAD</at> - Message here"
            }
        ],
        "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
        "version": "1.0",
        "msteams": {
            "entities": [
                {
                    "type": "mention",
                    "text": "<at>Name AAD</at>",
                    "mentioned": {
                      "id": "xxx",
                      "name": "Name"
                    }
                  }
            ]
        }
    }
}]
}
</code>```

But the width of the Adaptive Card is not customizable and I'd like to send just a simnple message without any additional color changes or text formatting. Like the latest message in this picture.

Body:
I want to send a simple message which will mention user via MS Teams Webhook connector.

I can send Adaptive Card with this

{
"type": "message",
"attachments": [
    {
    "contentType": "application/vnd.microsoft.card.adaptive",
    "content": {
        "type": "AdaptiveCard",
        "body": [
            {
                "type": "TextBlock",
                "size": "Medium",
                "weight": "Bolder",
                "text": "Card title here"
            },
            {
                "type": "TextBlock",
                "text": "<at>Name AAD</at> - Message here"
            }
        ],
        "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
        "version": "1.0",
        "msteams": {
            "entities": [
                {
                    "type": "mention",
                    "text": "<at>Name AAD</at>",
                    "mentioned": {
                      "id": "xxx",
                      "name": "Name"
                    }
                  }
            ]
        }
    }
}]
}

But the width of the Adaptive Card is not customizable and I'd like to send just a simnple message without any additional color changes or text formatting. Like the latest message in this picture.


问:
How to access localhost endpoint in dialogflow fulfilment inline editor
I am building a chatbot for the company i am working in using dialogflow. I am making some APIs call in my application using the fulfilment inline editor. The problem is i cannot access the localhost endpoint running on my machine. In order to make localhost available on internet, i used ngrok but the result is still same. Can someone helps me out ?
This is my code :

```<code>const { axios } = require('axios');

const data = {

    };
axios.post('https://10b7-185-177-125-173.eu.ngrok.io/**/**/**', data)
        .then(response => {
            // some logic here
        })
        .catch(error => {
            // some logic here
        });
    agent.add(msg);
</code>```

and i am using axios "^0.27.2" version

Body:
I am building a chatbot for the company i am working in using dialogflow. I am making some APIs call in my application using the fulfilment inline editor. The problem is i cannot access the localhost endpoint running on my machine. In order to make localhost available on internet, i used ngrok but the result is still same. Can someone helps me out ?
This is my code :

const { axios } = require('axios');

const data = {

    };
axios.post('https://10b7-185-177-125-173.eu.ngrok.io/**/**/**', data)
        .then(response => {
            // some logic here
        })
        .catch(error => {
            // some logic here
        });
    agent.add(msg);

and i am using axios "^0.27.2" version


问:
The image copied from RStudio is not correct. How is this solved?
I made a plot in RStudio. I want to copy that plot into another program. I go to "export" and then select "copy to clipboard." The popup has the correct figure, but when I paste it into another program there are problems. In "copy to clipboard" I have two options: "bitmap" and "metafile."
In "bitmap" the pasted file contains part of the figure and part of the background screen. Kind of like a screenshot where I miss a part of what I was trying to copy.
In "metafile" the figure looks good (it is the right part of the screen) but the confidence interval is missing.

I contacted Posit, but was directed here. I never had this problem before. Any idea how I correct it?
What I want is this:

But here is what I get:

I tried to enter the other image, but the system did not allow that. Just picture the first image without a confidence interval.


问:
cpputest mock EXPECTED calls that WERE NOT fulfilled
I'm trying to test some cpp code with cpputest. There is the code I would test:

```<code>void TA_MotRunng(rte_MotRunng_t_iArgs_t *args)
{
MotRunngLocalVariables_t lv;

InpGetAndChk(args, &lv);
std::cout << "lv.ip.drvEna_HW = " << lv.ip.drvEna_HW << std::endl;

/* motor running */
if ((ON            == lv.ip.drvEna_HW) &&
    (ON            == lv.ip.drvEnaSW) &&
    ((drv_ENABLED    == lv.ip.drvSts) || (drv_RESTARTING == lv.ip.drvSts)) &&
    (lv.ip.drvSpd   > 500.0f))
{
    lv.sts.motRunng_sts = ON;
}

/* motor not running */
if ((OFF           == lv.ip.drvEna_HW) ||
    (OFF           == lv.ip.drvEnaSW) ||
    ((drv_ENABLED != lv.ip.drvSts  ) && (drv_RESTARTING != lv.ip.drvSts)) ||
    (lv.ip.drvSpd < 50.0f       ))
{
    lv.sts.motRunng_sts = OFF;
}

// write output
lv.op.motRunng = lv.sts.motRunng_sts;

SetOutp(args, &lv);

}
</code>```

And I wrote a test code like this

```<code>#include "../includes/TestMotRunng.hpp"
#include <iostream>

TEST_GROUP(TA_MotRunngTest)
{
    TA_MotRunngTest test;
    void setup()
    {
        test.setUp();
    }
    void teardown()
    {
        test.tearDown();
    }
};

TEST(TA_MotRunngTest, testMotRunning)
{
    test.testMotRunning();
}

TEST(TA_MotRunngTest, testMotNotRunning)
{
    test.testMotNotRunning();
}

TA_MotRunngTest::TA_MotRunngTest() {}

void TA_MotRunngTest::setUp()
{
    // Set up
    // ...
    mock().clear();
}

void TA_MotRunngTest::tearDown()
{
    std::cout << "teardown" << std::endl;
    mock().checkExpectations();
    mock().clear();
}

void TA_MotRunngTest::testMotRunning()
{
    rte_MotRunng_t_iArgs_t args;
    MotRunngLocalVariables_t lv;
    MockSupport mock;

    // Set the input values to make the motor running
    lv.ip.drvEna_HW = ON;
    lv.ip.drvEnaSW = ON;
    lv.ip.drvSts = drv_ENABLED;
    lv.ip.drvSpd = 501.0f;
    mock.expectOneCall("InpGetAndChk")
    .withOutputParameterReturning("args", &args, sizeof(args))
    .withOutputParameterReturning("lv", &lv, sizeof(lv));
    TA_MotRunng(&args);

    // Verify that the output value for motor running is ON
    mock.checkExpectations();
    CHECK_EQUAL(ON, lv.sts.motRunng_sts);
</code>```

}

```<code>void TA_MotRunngTest::testMotNotRunning()
{
}

static void __wrap_InpGetAndChk(rte_MotRunng_t_iArgs_t const *args,
MotRunngLocalVariables_t *lv)
{
    // mock the InpGetAndChk function and set the input values
    mock().actualCall("InpGetAndChk").withOutputParameter("args",
    (void*)args).withOutputParameter("lv", lv);
    lv->ip.drvEna_HW = ON;
    lv->ip.drvEnaSW = ON;
    lv->ip.drvSts = drv_ENABLED;
    lv->ip.drvSpd = 600.0f;
}
</code>```

I'm trying to mock the inpGetAndChk function but I've an error:

/usr/src/app/tests/src/TestMotRunng.cpp:17: error: Failure in TEST(TA_MotRunngTest, testMotRunning)
Mock Failure: Expected call WAS NOT fulfilled.
EXPECTED calls that WERE NOT fulfilled:
InpGetAndChk -> const void* args: , const void* lv:  (expected 1 call, called 0 times)
EXPECTED calls that WERE fulfilled:

I search on stackoverflow and I found this

I tried to use --wrap like that

```<code>--wrap=InpGetAndChk
</code>```

but it's doesn't work I have the same error.

Thanks for reading me.

Cheers

Body:
I'm trying to test some cpp code with cpputest. There is the code I would test:

void TA_MotRunng(rte_MotRunng_t_iArgs_t *args)
{
MotRunngLocalVariables_t lv;

InpGetAndChk(args, &lv);
std::cout << "lv.ip.drvEna_HW = " << lv.ip.drvEna_HW << std::endl;

/* motor running */
if ((ON            == lv.ip.drvEna_HW) &&
    (ON            == lv.ip.drvEnaSW) &&
    ((drv_ENABLED    == lv.ip.drvSts) || (drv_RESTARTING == lv.ip.drvSts)) &&
    (lv.ip.drvSpd   > 500.0f))
{
    lv.sts.motRunng_sts = ON;
}

/* motor not running */
if ((OFF           == lv.ip.drvEna_HW) ||
    (OFF           == lv.ip.drvEnaSW) ||
    ((drv_ENABLED != lv.ip.drvSts  ) && (drv_RESTARTING != lv.ip.drvSts)) ||
    (lv.ip.drvSpd < 50.0f       ))
{
    lv.sts.motRunng_sts = OFF;
}

// write output
lv.op.motRunng = lv.sts.motRunng_sts;

SetOutp(args, &lv);

}

And I wrote a test code like this

#include "../includes/TestMotRunng.hpp"
#include <iostream>

TEST_GROUP(TA_MotRunngTest)
{
    TA_MotRunngTest test;
    void setup()
    {
        test.setUp();
    }
    void teardown()
    {
        test.tearDown();
    }
};

TEST(TA_MotRunngTest, testMotRunning)
{
    test.testMotRunning();
}

TEST(TA_MotRunngTest, testMotNotRunning)
{
    test.testMotNotRunning();
}

TA_MotRunngTest::TA_MotRunngTest() {}

void TA_MotRunngTest::setUp()
{
    // Set up
    // ...
    mock().clear();
}

void TA_MotRunngTest::tearDown()
{
    std::cout << "teardown" << std::endl;
    mock().checkExpectations();
    mock().clear();
}

void TA_MotRunngTest::testMotRunning()
{
    rte_MotRunng_t_iArgs_t args;
    MotRunngLocalVariables_t lv;
    MockSupport mock;

    // Set the input values to make the motor running
    lv.ip.drvEna_HW = ON;
    lv.ip.drvEnaSW = ON;
    lv.ip.drvSts = drv_ENABLED;
    lv.ip.drvSpd = 501.0f;
    mock.expectOneCall("InpGetAndChk")
    .withOutputParameterReturning("args", &args, sizeof(args))
    .withOutputParameterReturning("lv", &lv, sizeof(lv));
    TA_MotRunng(&args);

    // Verify that the output value for motor running is ON
    mock.checkExpectations();
    CHECK_EQUAL(ON, lv.sts.motRunng_sts);

}

void TA_MotRunngTest::testMotNotRunning()
{
}

static void __wrap_InpGetAndChk(rte_MotRunng_t_iArgs_t const *args,
MotRunngLocalVariables_t *lv)
{
    // mock the InpGetAndChk function and set the input values
    mock().actualCall("InpGetAndChk").withOutputParameter("args",
    (void*)args).withOutputParameter("lv", lv);
    lv->ip.drvEna_HW = ON;
    lv->ip.drvEnaSW = ON;
    lv->ip.drvSts = drv_ENABLED;
    lv->ip.drvSpd = 600.0f;
}

I'm trying to mock the inpGetAndChk function but I've an error:

/usr/src/app/tests/src/TestMotRunng.cpp:17: error: Failure in TEST(TA_MotRunngTest, testMotRunning)
Mock Failure: Expected call WAS NOT fulfilled.
EXPECTED calls that WERE NOT fulfilled:
InpGetAndChk -> const void* args: , const void* lv:  (expected 1 call, called 0 times)
EXPECTED calls that WERE fulfilled:

I search on stackoverflow and I found this

I tried to use --wrap like that

--wrap=InpGetAndChk

but it's doesn't work I have the same error.

Thanks for reading me.

Cheers


问:
Error in npm run build in apache superset plugin
**your textFollowing the steps:
https://preset.io/blog/building-custom-viz-plugins-in-superset-v2/

While running npm run build in the plugin, it is throwing error:

superset-plugin-chart-hello-world@0.1.0 build-esm
BABEL_OUTPUT=esm babel src --extensions ".ts,.tsx,.js,.jsx" --copy-files --out-dir esm

```<code>'BABEL_OUTPUT' is not recognized as an internal or external command,
 operable program or batch file.
</code>```

and the esm folder is not created.

On running

```<code>    BABEL_OUTPUT=esm babel src --extensions ".ts,.tsx,.js,.jsx" --copy-files --out-dir esm
</code>```

It is throwing error:

Am I missing something?

followed the exact steps

Tried
npm ci
npm run build

But no luck.
esm folder is not created and failing build**

Body:
**your textFollowing the steps:
https://preset.io/blog/building-custom-viz-plugins-in-superset-v2/

While running npm run build in the plugin, it is throwing error:

superset-plugin-chart-hello-world@0.1.0 build-esm
BABEL_OUTPUT=esm babel src --extensions ".ts,.tsx,.js,.jsx" --copy-files --out-dir esm

'BABEL_OUTPUT' is not recognized as an internal or external command,
 operable program or batch file.

and the esm folder is not created.

On running

    BABEL_OUTPUT=esm babel src --extensions ".ts,.tsx,.js,.jsx" --copy-files --out-dir esm

It is throwing error:

Am I missing something?

followed the exact steps

Tried
npm ci
npm run build

But no luck.
esm folder is not created and failing build**


问:
Github delete branch after merged on main
I've read this answer:

https://stackoverflow.com/a/57328204/3541320

But that's unclear to me because it says:

What I need is to delete a branch only when has been merged to a specific branch, in this case, to main.

What I know is the HEAD branch if the reference branch pointing in .git/HEAD/ but that's not necessary main, so

How can I do what I need? just with main


问:
Pearson correlation function for multidimensional array
I want to compute the pearson correlation for an array of signals. So, for instance, if I have a list of 10 signals with 50 points and I want to compare it to my reference signal with also 50 points, how can I do that without using a for loop?
It's important for me to avoid using a loop for computational cost purposes.

```<code>for i in range of (0, 10):
    correlation[i] = pearsonr(signals[i], reference_signal)[0]
</code>```

my goal is to have a correlation list (length = 10) with the correlation between each signal and the reference signal.

Thank you in advance for the help.

Body:
I want to compute the pearson correlation for an array of signals. So, for instance, if I have a list of 10 signals with 50 points and I want to compare it to my reference signal with also 50 points, how can I do that without using a for loop?
It's important for me to avoid using a loop for computational cost purposes.

for i in range of (0, 10):
    correlation[i] = pearsonr(signals[i], reference_signal)[0]

my goal is to have a correlation list (length = 10) with the correlation between each signal and the reference signal.

Thank you in advance for the help.


问:
How can I reformat my matrix in R so that?
I currently have a matrix of 17 rows (subjects) and 3 columns (conditions), like so:

```<code>      V1    V2    V3
#1
#2
#3
...
#17
</code>```

However, I would like to change this to 51 rows and 2 columns, like so:

```<code>Condition       Observation
V1              N/A
V2              N/A
V3              ...
V1
V2
...
</code>```

Haven't tried anything yet as I can't find any info on this. Alternatively, giving an overall header to V1, V2, and V3 as "conditions" would work- this is all so that I can use the $ operator for ANOVA and pairwise t-tests with Bonferroni correction.

Body:
I currently have a matrix of 17 rows (subjects) and 3 columns (conditions), like so:

      V1    V2    V3
#1
#2
#3
...
#17

However, I would like to change this to 51 rows and 2 columns, like so:

Condition       Observation
V1              N/A
V2              N/A
V3              ...
V1
V2
...

Haven't tried anything yet as I can't find any info on this. Alternatively, giving an overall header to V1, V2, and V3 as "conditions" would work- this is all so that I can use the $ operator for ANOVA and pairwise t-tests with Bonferroni correction.


问:
How to display a view on top of every view including a sheet in SwiftUI
Goal: I'm trying to create a custom sheet that behaves more or less like a normal sheet.

How: I'm using an overlay on top of my main view and changing its content to the view I need to display.

Like so:

```<code>MainView()
    .overlay {
        CustomSheet(content: SomeView())
    }
</code>```

Problem: When I open a normal sheet, the sheet goes on top of everything, including the overlay that's on the main view.

Question: How can I make the overlay open on top of every view (including a sheet and a fullScreenCover) the same way a normal sheet does?

The solution has to work on iOS 15 and above

Thanks :)

Body:
Goal: I'm trying to create a custom sheet that behaves more or less like a normal sheet.

How: I'm using an overlay on top of my main view and changing its content to the view I need to display.

Like so:

MainView()
    .overlay {
        CustomSheet(content: SomeView())
    }

Problem: When I open a normal sheet, the sheet goes on top of everything, including the overlay that's on the main view.

Question: How can I make the overlay open on top of every view (including a sheet and a fullScreenCover) the same way a normal sheet does?

The solution has to work on iOS 15 and above

Thanks :)