问:
How can I improve the accuracy of detecting if a tap event with ARCore hits an already added 3d model?
My goal is for taps and drags to be able to identify if a 3d model has been hit using motionEvents.

The current implementation works, but it is not very accurate. Most of the time tapping the model results in tappedOnModel being false, while dragging seems to work quite decently. Is there a way to improve the accuracy without using Sceneform or SceneView?

```<code>arCore.filament.view.pick(
  (filament.surfaceView.width.toFloat() * modelEvent.screenPosition.x).toInt(),
  (filament.surfaceView.height.toFloat() * modelEvent.screenPosition.y).toInt(),
  Handler(Looper.getMainLooper())
) {
  tappedModelRenderable = it.renderable
  tappedOnModel = modelRenderables.any {
    it.any {
      it == tappedModelRenderable
    }
  }
}

if (tappedOnModel) {
  for (i in modelRenderables.indices) {
    for (j in modelRenderables[i]) {
      if (j == tappedModelRenderable) {
        selectedModelIndex = i
        break
      }
    }
  }
}
</code>```

Body:
My goal is for taps and drags to be able to identify if a 3d model has been hit using motionEvents.

The current implementation works, but it is not very accurate. Most of the time tapping the model results in tappedOnModel being false, while dragging seems to work quite decently. Is there a way to improve the accuracy without using Sceneform or SceneView?

arCore.filament.view.pick(
  (filament.surfaceView.width.toFloat() * modelEvent.screenPosition.x).toInt(),
  (filament.surfaceView.height.toFloat() * modelEvent.screenPosition.y).toInt(),
  Handler(Looper.getMainLooper())
) {
  tappedModelRenderable = it.renderable
  tappedOnModel = modelRenderables.any {
    it.any {
      it == tappedModelRenderable
    }
  }
}

if (tappedOnModel) {
  for (i in modelRenderables.indices) {
    for (j in modelRenderables[i]) {
      if (j == tappedModelRenderable) {
        selectedModelIndex = i
        break
      }
    }
  }
}


来源: stackexchange

问:
Using CEC-Signal to reboot raspberry pi?
is it possible to let a Rasberry listen on CEC-Signals to trigger reboot? I use a rasberry as Info screen and being able to reboot it via TV Remote would be nice.

I want to trigger reboot on Volume up and trigger a script on Volume down.

I use CEC to start/stop the TV (single command that gets fired such as sudo -u pi echo 'standby 0.0.0.0' | cec-client -s -d 1 but can I also listen for Signals instead of sending them?

ContentLicense: CC BY-SA 4.0


问:
How given a date and a forecast model, predict the sum of the all target variable for the next month?
So let's imagine I have a forecast model that given a date and some exogenous variables can predict  the number of sales of that day.

```<code>      Exog1  Exog2     Number of sales
date
2000-06-01  0.040457  0.326594  4
2000-06-02  0.279323  0.877446  7
2000-06-03  0.328068  0.837669  8
2000-06-04  0.107959  0.678297  12
2000-06-05  0.131555  0.418380  3
2000-06-06  0.999961  0.619517  4
2000-06-07  0.129270  0.024533  8
2000-06-08  0.441010  0.741781  9
2000-06-09  0.682101  0.375660  2
2000-06-10  0.754488  0.352293  9
</code>```

Then I have other dataframe with the id of each store

```<code>Store_ID     date      Exog1    Exog2    Number of sales

    45    2000-06-01  0.040457  0.326594  4
    87    2000-06-02  0.279323  0.877446  7
    34   2000-06-03  0.328068  0.837669  8
    25   2000-06-04  0.107959  0.678297  12
    23   2000-06-05  0.131555  0.418380  3
    85   2000-06-06  0.999961  0.619517  4
    92   2000-06-07  0.129270  0.024533  8
    51   2000-06-08  0.441010  0.741781  9
    37   2000-06-09  0.682101  0.375660  2
    50   2000-06-10  0.754488  0.352293  9
</code>```

Now I want predict for each store, the estimated number of sales according to the forecaster for the next month. For example for the first value, "45    2000-06-01  0.040457  0.326594  4", I want to be able to calculate for each day form 2000-06-01 to 2000-07-01 (with the same duplicated exogenous variables 0.040457 and 0.3265) the estimated number of sales and then add it all up so that way I can get the total amount of estimated sells for the next month.

The only thing I got is how to calculate a range of days between two days.

pandas.date_range(date, date+ DateOffset(months=1),freq='d')

PD: We can say the the first Exog1 variable is the ratio between like and dislikes of a store for example

Body:
So let's imagine I have a forecast model that given a date and some exogenous variables can predict  the number of sales of that day.

      Exog1  Exog2     Number of sales
date
2000-06-01  0.040457  0.326594  4
2000-06-02  0.279323  0.877446  7
2000-06-03  0.328068  0.837669  8
2000-06-04  0.107959  0.678297  12
2000-06-05  0.131555  0.418380  3
2000-06-06  0.999961  0.619517  4
2000-06-07  0.129270  0.024533  8
2000-06-08  0.441010  0.741781  9
2000-06-09  0.682101  0.375660  2
2000-06-10  0.754488  0.352293  9

Then I have other dataframe with the id of each store

Store_ID     date      Exog1    Exog2    Number of sales

    45    2000-06-01  0.040457  0.326594  4
    87    2000-06-02  0.279323  0.877446  7
    34   2000-06-03  0.328068  0.837669  8
    25   2000-06-04  0.107959  0.678297  12
    23   2000-06-05  0.131555  0.418380  3
    85   2000-06-06  0.999961  0.619517  4
    92   2000-06-07  0.129270  0.024533  8
    51   2000-06-08  0.441010  0.741781  9
    37   2000-06-09  0.682101  0.375660  2
    50   2000-06-10  0.754488  0.352293  9

Now I want predict for each store, the estimated number of sales according to the forecaster for the next month. For example for the first value, "45    2000-06-01  0.040457  0.326594  4", I want to be able to calculate for each day form 2000-06-01 to 2000-07-01 (with the same duplicated exogenous variables 0.040457 and 0.3265) the estimated number of sales and then add it all up so that way I can get the total amount of estimated sells for the next month.

The only thing I got is how to calculate a range of days between two days.

pandas.date_range(date, date+ DateOffset(months=1),freq='d')

PD: We can say the the first Exog1 variable is the ratio between like and dislikes of a store for example


问:
How to use .tflite and .txt files in android studio for EMG signal classification?
I have .tflite and .txt files for my trained model of EMG signals. How should I proceed for developing an app to android studio? The examples which I getting over the internet are mostly for image classifier app, can anyone suggest me for 2D classification android app?</p>


问:
How to make the minimum width of SplitMenuButton's popup menu not less than the width of the button itself? (JavaFX 19)
I want the minimum width of SplitMenuButton's popup menu to be bound to the SplitMenuButton's widthProperty. When the width of the SplitMenuButton changes, the minimum width of the menu also changes. The desired effect is that the width of the menu will not be smaller than the width of the button. How to achieve it?</p>


问:
is there any way to white label MAUI app?
I have project in Xamarin forms which we have to migrate to .NET MAUI we need White Labelling in that project like this White Labeling in Xamarin Forms Applications

In Xamarin forms I define constants and configuration in solution and project file and set info.plist and android manifest file. when I build project it is picking file according to configuration.


问:
Flutter there should be exactly one item with [DropdownButton]'s value: Dubai. Either zero or 2 or more [DropdownMenuItem]s were detected
I amm using two languages in my flutter, English and Arabic, when user select his city(cities will show in DropdownMenu) while registering in English language it works fine, he can update his profile by changing his city but when same user change language from English to Arabic and go to his profile section I get error.

How can I resolve this issue?

There should be exactly one item with [DropdownButton]'s value: Dubai.  Either zero or 2 or more [DropdownMenuItem]s were detected with the same value 'package:flutter/src/material/dropdown.dart': Failed assertion: line 1580 pos 15: 'items == null || items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) { return item.value == value; }).length == 1'

This error popup when English user change to Arabic language, and same when Arabic user change to English language.

Here is my Profile update code:

```<code>class Profile extends StatefulWidget {
  final Function(Map<String, dynamic>) callBack;

  const Profile(this.callBack, {Key? key}) : super(key: key);

  @override
  State<Profile> createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {

  List<String> cities = [
    LanguageStringKeys.instance.abuDhabi.tr,
    LanguageStringKeys.instance.dubai.tr,
    LanguageStringKeys.instance.sharjah.tr,
    LanguageStringKeys.instance.ajman.tr,
    LanguageStringKeys.instance.ummAlQuwain.tr,
    LanguageStringKeys.instance.rasAlKhaimah.tr,
    LanguageStringKeys.instance.fujairah.tr,
  ];

  String selectedCity = Get.put(AppController()).loginResponse?.data?.user?.address;

  var nameController = TextEditingController();
  var tradeController = TextEditingController();
  var phoneController = TextEditingController();
  var bioController = TextEditingController();

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      nameController.text = Get.put(AppController()).loginResponse?.data?.user?.firstName ?? "";
      tradeController.text = Get.put(AppController()).loginResponse?.data?.user?.tradeLicense ?? "";
      phoneController.text = Get.put(AppController()).loginResponse?.data?.user?.phone ?? "";
      selectedCity = Get.put(AppController()).loginResponse?.data?.user?.address ?? "";
      bioController.text = Get.put(AppController()).loginResponse?.data?.user?.bio ?? "";

    });
  }

  @override
  Widget build(BuildContext context) {
    return BackgroundImage(
      image: const AssetImage('assets/images/enjyback.png'),
      child: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: Scaffold(

          backgroundColor: Colors.transparent,
          body: Center(
            child: SingleChildScrollView(
              physics: const BouncingScrollPhysics(),
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: Dimensions.width20, vertical: Dimensions.height10),
                child: Column(
                  children: [
                   AppTextField(
                      textController: nameController,
                      labelText: LanguageStringKeys.instance.name.tr,
                      labelColor: Colors.white,
                      borderColor: Colors.white,
                      textColor: Colors.white,
                      inputType: TextInputType.name,
                    ),
                    SizedBox(height: Dimensions.height15),
                    AppTextField(
                      textController: tradeController,
                      labelText: LanguageStringKeys.instance.tradeLicenseNo.tr,
                      labelColor: Colors.white,
                      borderColor: Colors.white,
                      textInputFormatter: 7,
                      textColor: Colors.white,
                      inputType: TextInputType.number,
                    ),
                    SizedBox(height: Dimensions.height15),
                    AppTextField(
                      textController: phoneController,
                      labelText: LanguageStringKeys.instance.phoneNumber.tr,
                      labelColor: Colors.white,
                      borderColor: Colors.white,
                      textColor: Colors.white,
                      inputType: TextInputType.number,
                    ),
                    SizedBox(height: Dimensions.height15),
                    ButtonTheme(
                      alignedDropdown: true,
                      child: DropdownButtonFormField(
                          isExpanded: true,
                          borderRadius: BorderRadius.circular(Dimensions.height10),
                          iconEnabledColor: Colors.white,
                          selectedItemBuilder: (BuildContext context) {
                            return cities
                                .map((e) => Text(
                                      selectedCity,
                                      style: const TextStyle(color: Colors.white),
                                    ))
                                .toList();
                          },
                          decoration: textFormFieldsDecoration(
                            LanguageStringKeys.instance.city.tr,
                            Colors.white,
                            Colors.white,
                          ),
                          items: cities
                              .map((item) => DropdownMenuItem(
                                    value: item,
                                    child: SmallText(text: item, color: Colors.black),
                                  ))
                              .toList(),
                          value: selectedCity,
                          onChanged: (item) => setState(() => selectedCity = item as String)),
                    ),
                    SizedBox(height: Dimensions.height15),
                    AppTextField(
                      textController: bioController,
                      labelText: LanguageStringKeys.instance.bio.tr,
                      labelColor: Colors.white,
                      textColor: Colors.white,
                      maxLines: 6,
                      borderColor: Colors.white,
                      inputType: TextInputType.name,
                    ),
                    SizedBox(height: Dimensions.height15),
                    ElevatedButton(
                      onPressed: () {
                        Provider.of<UserProfileService>(context, listen: false).updateUserProfile(context, {}, {
                          "name": nameController.text,
                          "trade_license": tradeController.text,
                          "phone": phoneController.text,
                          "address": selectedCity,
                          "bio": bioController.text,
                          "image": image,
                        });
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.white,
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Dimensions.radius10)),
                        minimumSize: Size.fromHeight(Dimensions.height40),
                      ),
                      child: SmallText(text: LanguageStringKeys.instance.save.tr, color: Colors.grey),
                    ),
                    SizedBox(height: Dimensions.height15),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

</code>```

Body:
I amm using two languages in my flutter, English and Arabic, when user select his city(cities will show in DropdownMenu) while registering in English language it works fine, he can update his profile by changing his city but when same user change language from English to Arabic and go to his profile section I get error.

How can I resolve this issue?

There should be exactly one item with [DropdownButton]'s value: Dubai.  Either zero or 2 or more [DropdownMenuItem]s were detected with the same value 'package:flutter/src/material/dropdown.dart': Failed assertion: line 1580 pos 15: 'items == null || items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) { return item.value == value; }).length == 1'

This error popup when English user change to Arabic language, and same when Arabic user change to English language.

Here is my Profile update code:

class Profile extends StatefulWidget {
  final Function(Map<String, dynamic>) callBack;

  const Profile(this.callBack, {Key? key}) : super(key: key);

  @override
  State<Profile> createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {

  List<String> cities = [
    LanguageStringKeys.instance.abuDhabi.tr,
    LanguageStringKeys.instance.dubai.tr,
    LanguageStringKeys.instance.sharjah.tr,
    LanguageStringKeys.instance.ajman.tr,
    LanguageStringKeys.instance.ummAlQuwain.tr,
    LanguageStringKeys.instance.rasAlKhaimah.tr,
    LanguageStringKeys.instance.fujairah.tr,
  ];

  String selectedCity = Get.put(AppController()).loginResponse?.data?.user?.address;

  var nameController = TextEditingController();
  var tradeController = TextEditingController();
  var phoneController = TextEditingController();
  var bioController = TextEditingController();

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      nameController.text = Get.put(AppController()).loginResponse?.data?.user?.firstName ?? "";
      tradeController.text = Get.put(AppController()).loginResponse?.data?.user?.tradeLicense ?? "";
      phoneController.text = Get.put(AppController()).loginResponse?.data?.user?.phone ?? "";
      selectedCity = Get.put(AppController()).loginResponse?.data?.user?.address ?? "";
      bioController.text = Get.put(AppController()).loginResponse?.data?.user?.bio ?? "";

    });
  }

  @override
  Widget build(BuildContext context) {
    return BackgroundImage(
      image: const AssetImage('assets/images/enjyback.png'),
      child: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: Scaffold(

          backgroundColor: Colors.transparent,
          body: Center(
            child: SingleChildScrollView(
              physics: const BouncingScrollPhysics(),
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: Dimensions.width20, vertical: Dimensions.height10),
                child: Column(
                  children: [
                   AppTextField(
                      textController: nameController,
                      labelText: LanguageStringKeys.instance.name.tr,
                      labelColor: Colors.white,
                      borderColor: Colors.white,
                      textColor: Colors.white,
                      inputType: TextInputType.name,
                    ),
                    SizedBox(height: Dimensions.height15),
                    AppTextField(
                      textController: tradeController,
                      labelText: LanguageStringKeys.instance.tradeLicenseNo.tr,
                      labelColor: Colors.white,
                      borderColor: Colors.white,
                      textInputFormatter: 7,
                      textColor: Colors.white,
                      inputType: TextInputType.number,
                    ),
                    SizedBox(height: Dimensions.height15),
                    AppTextField(
                      textController: phoneController,
                      labelText: LanguageStringKeys.instance.phoneNumber.tr,
                      labelColor: Colors.white,
                      borderColor: Colors.white,
                      textColor: Colors.white,
                      inputType: TextInputType.number,
                    ),
                    SizedBox(height: Dimensions.height15),
                    ButtonTheme(
                      alignedDropdown: true,
                      child: DropdownButtonFormField(
                          isExpanded: true,
                          borderRadius: BorderRadius.circular(Dimensions.height10),
                          iconEnabledColor: Colors.white,
                          selectedItemBuilder: (BuildContext context) {
                            return cities
                                .map((e) => Text(
                                      selectedCity,
                                      style: const TextStyle(color: Colors.white),
                                    ))
                                .toList();
                          },
                          decoration: textFormFieldsDecoration(
                            LanguageStringKeys.instance.city.tr,
                            Colors.white,
                            Colors.white,
                          ),
                          items: cities
                              .map((item) => DropdownMenuItem(
                                    value: item,
                                    child: SmallText(text: item, color: Colors.black),
                                  ))
                              .toList(),
                          value: selectedCity,
                          onChanged: (item) => setState(() => selectedCity = item as String)),
                    ),
                    SizedBox(height: Dimensions.height15),
                    AppTextField(
                      textController: bioController,
                      labelText: LanguageStringKeys.instance.bio.tr,
                      labelColor: Colors.white,
                      textColor: Colors.white,
                      maxLines: 6,
                      borderColor: Colors.white,
                      inputType: TextInputType.name,
                    ),
                    SizedBox(height: Dimensions.height15),
                    ElevatedButton(
                      onPressed: () {
                        Provider.of<UserProfileService>(context, listen: false).updateUserProfile(context, {}, {
                          "name": nameController.text,
                          "trade_license": tradeController.text,
                          "phone": phoneController.text,
                          "address": selectedCity,
                          "bio": bioController.text,
                          "image": image,
                        });
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.white,
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Dimensions.radius10)),
                        minimumSize: Size.fromHeight(Dimensions.height40),
                      ),
                      child: SmallText(text: LanguageStringKeys.instance.save.tr, color: Colors.grey),
                    ),
                    SizedBox(height: Dimensions.height15),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}


问:
How to use @GraphQLInterface in SPQR
I want to return list of interfaces with different implementations by calling query/mutation in grpahql spqr.

For this purpose I suppose I need to use @GraphQLInterface.
Maybe I doing something wrong, but it not works.

I have spring-boot app 2.3.3.RELEASE with graphql-spqr-spring-boot-starter 0.0.4
There is my model:

```<code>public class ResponseDto {
    ...
    List<IValidation> validations;
}

@GraphQLInterface(name = "ValidationError", implementationAutoDiscovery = true)
public interface ValidationError {

    @GraphQLQuery(name = "message")
    String getMessage();
}

@GraphQLType(name = "SimpleError")
@AllArgsConstructor
@Getter
public enum SimpleError implements ValidationError {

    ERROR("some msg");

    private String message;
}
</code>```

But when I get graphql schema there is no any info about SimpleError and field message in ValidationError.

I also tried without GraphQLType and GraphQLQuery, it not works.
And I tried with no enum implementation also, same result.

Could anyone explain what I'm doing wrong?

Thank you.

Title: How to use @GraphQLInterface in SPQR

Body:
I want to return list of interfaces with different implementations by calling query/mutation in grpahql spqr.

For this purpose I suppose I need to use @GraphQLInterface.
Maybe I doing something wrong, but it not works.

I have spring-boot app 2.3.3.RELEASE with graphql-spqr-spring-boot-starter 0.0.4
There is my model:

public class ResponseDto {
    ...
    List<IValidation> validations;
}

@GraphQLInterface(name = "ValidationError", implementationAutoDiscovery = true)
public interface ValidationError {

    @GraphQLQuery(name = "message")
    String getMessage();
}

@GraphQLType(name = "SimpleError")
@AllArgsConstructor
@Getter
public enum SimpleError implements ValidationError {

    ERROR("some msg");

    private String message;
}

But when I get graphql schema there is no any info about SimpleError and field message in ValidationError.

I also tried without GraphQLType and GraphQLQuery, it not works.
And I tried with no enum implementation also, same result.

Could anyone explain what I'm doing wrong?

Thank you.


问:
Grid component not resizing inside a Popover component in react mui
I am using material ui in react. I have a Popover component, which has a Grid component inside it. The size of the Grid component is dynamic, i.e. it's height can increase. The regular behavior of Popover is to make sure that it stays on the screen. But when I use a Grid component inside Popover , and when the height of the Grid increases, the Popover is overflowing and going below the screen.

```<code>return (
    <Popover
      open={Boolean(anchorEl)}
      anchorEl={anchorEl}
      onClose={handleClose}
      anchorOrigin={{
        vertical: 'top',
        horizontal: 'left',
      }}
      transformOrigin={{
        vertical: "top",
        horizontal: "left"
      }}
      aria-labelledby="draggable-dialog-title"
      >
       <div>
        <DemoGrid  />
      </div>

</Popover>
  );

function DemoGrid(){

  const [list,setList] = useState(["hi"]);

  return <Grid container spacing={2} >
        <button onClick={()=>setList(prev=>[...prev,"hi"])}>add new</button>
    {list.map((i,j)=><Grid item xs={8} key={i+j}>
          <p>{`${j} ${i}`}</p>
        </Grid>)}
  </Grid>;
}
</code>```

So the DemoGrid component, basically is the component which consists of a button, whose on click will add a new Grid item and thereby increase the height of the Grid component, now when the Grid items are too many, the Popover overflows below the screen as shown below.

What can I do so that the Popover stays on the screen. And why isn't the Popover retaining its properties when I use a display:flex (Grid component) inside it?

Body:
I am using material ui in react. I have a Popover component, which has a Grid component inside it. The size of the Grid component is dynamic, i.e. it's height can increase. The regular behavior of Popover is to make sure that it stays on the screen. But when I use a Grid component inside Popover , and when the height of the Grid increases, the Popover is overflowing and going below the screen.

return (
    <Popover
      open={Boolean(anchorEl)}
      anchorEl={anchorEl}
      onClose={handleClose}
      anchorOrigin={{
        vertical: 'top',
        horizontal: 'left',
      }}
      transformOrigin={{
        vertical: "top",
        horizontal: "left"
      }}
      aria-labelledby="draggable-dialog-title"
      >

        <DemoGrid  />

</Popover>
  );

function DemoGrid(){

  const [list,setList] = useState(["hi"]);

  return <Grid container spacing={2} >
        <button onClick={()=>setList(prev=>[...prev,"hi"])}>add new</button>
    {list.map((i,j)=><Grid item xs={8} key={i+j}>

{`${j} ${i}`}

        </Grid>)}
  </Grid>;
}

So the DemoGrid component, basically is the component which consists of a button, whose on click will add a new Grid item and thereby increase the height of the Grid component, now when the Grid items are too many, the Popover overflows below the screen as shown below.

What can I do so that the Popover stays on the screen. And why isn't the Popover retaining its properties when I use a display:flex (Grid component) inside it?


问:
0xc0000409 (STATUS_STACK_BUFFER_OVERRUN) issue when using symbols from a shared libs on github-actions windows image
The problem:

I'm working on continuous integration of a visualization software (C++).
We used to build all dependencies statically, then build the software, test it and ship it.
We recently moved the shipping part to a more rafined approach and want to make the CI closer to what the end user will do, building shared libs is definitely expected from our users.

However, with some or our dependencies, as soon as symbols from libs in question are used, our software crash with 0xc0000409.

This dependencies used to be linked statically and everything was working.

What did I try:

I have uploaded the artifacts and tested them on a local windows machine and it works flawlessly.

I have run dependencies.exe in github-actions and cant find anything wrong with the output (although the output is long and I may be missing something).

I tried running the software using any other way I could think of to get more info about the crash but nothing cames up.

I tried copying all the dll in the same directory to ensure anything from github-actions windows image is not used, but no changes.

As this point I'm stumped and have no idea how to move forward and we are considering just keeping the deps static for now.

What I'm looking for:

Is there a way to ask Windows nicely to give more info about what is not working ?
Maybe a way to use a debugger from the command line, if thats even a thing with visual studio debugger ?

My guess is that a lib used by these dependencies have an issue somehow, or is loading dynamically and is not present. That would explain why it is not an issue when linking statically.

More details:

If you want more info about which lib are crashing, here it is:

VTK linked statically into my software + mesa-dist-win dlls dropped alongside my software: no issue

VTK linked dynamically into my software + mesa-dist-win dlls dropped alongside my software: Issue as soon as I start rendering anything (using mesa)

OpenCascade linked statically into my software : no issue

OpenCascade linked dynamically into my software : issue as soon as I start using opencascade symbols


问:
How to get Entity Framework to create a "char" from an enum
I'm working on a C# application, based on Entity Framework.

In order to create the database, this is what I do:

```<code>context.Database.EnsureCreated();
context.Database.Migrate();
</code>```

, where context is an object, inherited from Microsoft.EntityFrameworkCore.DbContext.

One of my objects, has an attribute Type from the following type:

```<code>public enum ObjectType
{
    After='A',
    Before='B'
}
</code>```

I would expect the Entity Framework to generate the SQL-Server database with that attribute being a char, but instead, it's an integer, containing the ASCII code of that char (65 and 66, which is not very readable):

My SQL-Server session gives me the following result (I'm sure I'm referring to the correct object):

```<code>SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
  WHERE COLUMN_NAME LIKE '%Type%'
</code>```

Result:

```<code>DATA_TYPE
int
</code>```

I would like Entity Framework to generate my database with that column being of the type char.

How can I achieve that?

Thanks in advance

Body:
I'm working on a C# application, based on Entity Framework.

In order to create the database, this is what I do:

context.Database.EnsureCreated();
context.Database.Migrate();

, where context is an object, inherited from Microsoft.EntityFrameworkCore.DbContext.

One of my objects, has an attribute Type from the following type:

public enum ObjectType
{
    After='A',
    Before='B'
}

I would expect the Entity Framework to generate the SQL-Server database with that attribute being a char, but instead, it's an integer, containing the ASCII code of that char (65 and 66, which is not very readable):

My SQL-Server session gives me the following result (I'm sure I'm referring to the correct object):

SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
  WHERE COLUMN_NAME LIKE '%Type%'

Result:

DATA_TYPE
int

I would like Entity Framework to generate my database with that column being of the type char.

How can I achieve that?

Thanks in advance


问:
M-Estimation with Non-linear Constraints in R
Consider an "example" objective function:

```<code>> x1 <- rnorm(100); x2 <- rnorm(100); x3 <- rnorm(100)
> obj <- function(par) {
        res <- (x1 * par[1] - x2 * par[2]) * par[3]
        return(res)
}
</code>```

Here, suppose that we want to find the value of par maximizing the objective function obj with a non-linear constraint, ((par[1] - par[2]) / par[3]) - par[2] = 0.

Then, how can we do inference for the parameters, par[1], par[2], par[3]?

I know that it is easy to estimate the parameters because we can rewrite the objective function as

```<code>obj_constrained <- function(par) {
        res <- (x1 * ((par[2] * par[3]) + par[2]) - x2 * par[2]) * par[3]
        return(res)
}
</code>```

and just utilize an user-written function maxLik:

```<code>tmp <- maxLik(obj_constrained, rep(0, 2))
</code>```

However, in this case, it is impossible to get the gradient and Hessian matrix evaluated at par[1], par[2], par[3] (we can just get those of par[2], par[3]).

Thus, I want to estimate the three parameters with the non-linear constraints so that I can easily get the gradient and Hessian matrix.

How can I do that?

Body:
Consider an "example" objective function:

> x1 <- rnorm(100); x2 <- rnorm(100); x3 <- rnorm(100)
> obj <- function(par) {
        res <- (x1 * par[1] - x2 * par[2]) * par[3]
        return(res)
}

Here, suppose that we want to find the value of par maximizing the objective function obj with a non-linear constraint, ((par[1] - par[2]) / par[3]) - par[2] = 0.

Then, how can we do inference for the parameters, par[1], par[2], par[3]?

I know that it is easy to estimate the parameters because we can rewrite the objective function as

obj_constrained <- function(par) {
        res <- (x1 * ((par[2] * par[3]) + par[2]) - x2 * par[2]) * par[3]
        return(res)
}

and just utilize an user-written function maxLik:

tmp <- maxLik(obj_constrained, rep(0, 2))

However, in this case, it is impossible to get the gradient and Hessian matrix evaluated at par[1], par[2], par[3] (we can just get those of par[2], par[3]).

Thus, I want to estimate the three parameters with the non-linear constraints so that I can easily get the gradient and Hessian matrix.

How can I do that?


问:
Error when installing ExtendedSelenium2library

C:\Users\Sachini>pip install robotframework-extendedselenium2library
Collecting robotframework-extendedselenium2library
Using cached robotframework-extendedselenium2library-0.9.2.tar.gz (107 kB)
Preparing metadata (setup.py) ... done
Collecting selenium>=2.46.1
Using cached selenium-4.7.2-py3-none-any.whl (6.3 MB)
Collecting robotframework-selenium2library==1.8.0
Using cached robotframework-selenium2library-1.8.0.tar.gz (118 kB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error
× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─> [32 lines of output]
Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.14.tar.gz
Traceback (most recent call last):
File


问:
Django 'ModuleNotFoundError: No module named 'my_app''
I have been working for some time in a project. One of the apps inside of it, 'my_app' has its models, views, forms, etc. working fine. It is included in INSTALLED_APPS as well.

Now I try to create a new file inside the my_app folder to write some logic but can't import the models. I tried:

```<code>from my_app.models import MyModel
</code>```

But I get this error: ModuleNotFoundError: No module named 'my_app'

Also tried this one as I was doing the imports in, for example, views.py:

```<code>from .models import MyModel
</code>```

But this time I get this error:

```<code>ImportError: attempted relative import with no known parent package
</code>```

These imports are working fine in other files in the same folder. Recently I deployed the app to Railway, maybe that has something to do with this error? Why suddenly this error happened?

EDIT:

my_app/apps.py file:

```<code>from django.apps import AppConfig

class My_appConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'my_app'
</code>```

Also, recently started using Celery and my_project_folder/celery.py looks like this:

```<code>from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings')

app = Celery('my_project')
</code>```

Body:
I have been working for some time in a project. One of the apps inside of it, 'my_app' has its models, views, forms, etc. working fine. It is included in INSTALLED_APPS as well.

Now I try to create a new file inside the my_app folder to write some logic but can't import the models. I tried:

from my_app.models import MyModel

But I get this error: ModuleNotFoundError: No module named 'my_app'

Also tried this one as I was doing the imports in, for example, views.py:

from .models import MyModel

But this time I get this error:

ImportError: attempted relative import with no known parent package

These imports are working fine in other files in the same folder. Recently I deployed the app to Railway, maybe that has something to do with this error? Why suddenly this error happened?

EDIT:

my_app/apps.py file:

from django.apps import AppConfig

class My_appConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'my_app'

Also, recently started using Celery and my_project_folder/celery.py looks like this:

from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings')

app = Celery('my_project')


问:
Can't figure out how to add rbenv shims to $PATH
I'm having difficulty getting rbenv to change my ruby version. I've reviewed the question here but still struggling: rbenv not changing ruby version

Then ran rbenv init after install, then ran env | grep PATH but don't see any reference to rbenv.

THe documentation (https://github.com/rbenv/rbenv#how-rbenv-hooks-into-your-shell) states that rbenv init adds the necessary text to your PATH automatically.

I am using zsh. I don't know how to edit my PATH file. If someone provides an answer on how to add what I need to PATH, please be explicit with instructions to do so.


问:
How to overlay a plot with an image using matplotlib?
I have an image and i have a plot. The plot is a seaborn heatmap. Now i want to overlay this heatmap with an image. How can i do this? IMPORTANT: I don't want to plot the heatmap over the image, i want to overlay the image over the heatmap.

My code looks like this:

```<code># image
img = Image.open(getMinimapPath(map))
minimapExtent = getMinimapExtent(map)

# set seaborn style
sns.set_style("white")

data[data == 0] = np.nan

sns.heatmap(data=data, vmin=np.nanmin(data), vmax=np.nanmax(data), cmap="RdYlGn", cbar=False, zorder=-1)
plt.imshow(img, extent=minimapExtent)

plt.axis("off")
plt.savefig("bot/data/img/heatmap.png", dpi=500, bbox_inches="tight")
plt.close()
</code>```

Body:
I have an image and i have a plot. The plot is a seaborn heatmap. Now i want to overlay this heatmap with an image. How can i do this? IMPORTANT: I don't want to plot the heatmap over the image, i want to overlay the image over the heatmap.

My code looks like this:

# image
img = Image.open(getMinimapPath(map))
minimapExtent = getMinimapExtent(map)

# set seaborn style
sns.set_style("white")

data[data == 0] = np.nan

sns.heatmap(data=data, vmin=np.nanmin(data), vmax=np.nanmax(data), cmap="RdYlGn", cbar=False, zorder=-1)
plt.imshow(img, extent=minimapExtent)

plt.axis("off")
plt.savefig("bot/data/img/heatmap.png", dpi=500, bbox_inches="tight")
plt.close()


问:
ChunkLoadError: Loading chunk - module federation (Apache Superset)
entryFile in the request status 200. But during imports, error:

entryFile.js:231 Uncaught (in promise) ChunkLoadError: Loading chunk src_constTest_ts failed. (missing: http://localhost:3000/static/assets/src_constTest_ts.84972c0c.chunk.js) while loading "./constants" from 1 at __webpack_require__.f.j (entryFile.js:231:29) at entryFile.js:106:40 at Array.reduce (\<anonymous\>) at __webpack_require__.e (entryFile.js:105:67) at ./constants (entryFile.js:22:30) at get (entryFile.js:29:23) at u (remotes loading:33:20) at i (remotes loading:45:62) at remotes loading:35:54 at async Promise.all (:3000/index 0)

This chunk file was loading but content type showing as text/html instead of application/javascript when file loads in network tab response header.

export. webpack.config. Application (apache superset)

```<code>const output = {
  path: BUILD_DIR,
  publicPath: `${ASSET_BASE_URL}/static/assets/`,
};

new ModuleFederationPlugin({
    name: 'superset',
    filename: 'entryFile.js',
    exposes: {
      './constants': './src/constTest.ts',
    },
  })
</code>```

import. webpack.config. Application (create react app)

```<code>new ModuleFederationPlugin({
  name: "cra",
  remotes: {
     Superset: "superset@http://localhost:8088/static/assets/entryFile.js",
  },
});

module.exports = function (webpackEnv) {
   output: {
      path: paths.appBuild,
      pathinfo: isEnvDevelopment,
      filename: isEnvProduction
        ? "static/js/[name].[contenthash:8].js"
        : isEnvDevelopment && "static/js/bundle.js",
      // There are also additional JS chunk files if you use code splitting.
      chunkFilename: isEnvProduction
        ? "static/js/[name].[contenthash:8].chunk.js"
        : isEnvDevelopment && "static/js/[name].chunk.js",
      assetModuleFilename: "static/media/[name].[hash][ext]",
      publicPath: "auto",
    },
}
</code>```

import. Application (create react app). App.tsx

import("Superset/constants").then((data) => console.log(data));

Body:
entryFile in the request status 200. But during imports, error:

entryFile.js:231 Uncaught (in promise) ChunkLoadError: Loading chunk src_constTest_ts failed. (missing: http://localhost:3000/static/assets/src_constTest_ts.84972c0c.chunk.js) while loading "./constants" from 1 at __webpack_require__.f.j (entryFile.js:231:29) at entryFile.js:106:40 at Array.reduce (\<anonymous\>) at __webpack_require__.e (entryFile.js:105:67) at ./constants (entryFile.js:22:30) at get (entryFile.js:29:23) at u (remotes loading:33:20) at i (remotes loading:45:62) at remotes loading:35:54 at async Promise.all (:3000/index 0)

This chunk file was loading but content type showing as text/html instead of application/javascript when file loads in network tab response header.

export. webpack.config. Application (apache superset)

const output = {
  path: BUILD_DIR,
  publicPath: `${ASSET_BASE_URL}/static/assets/`,
};

new ModuleFederationPlugin({
    name: 'superset',
    filename: 'entryFile.js',
    exposes: {
      './constants': './src/constTest.ts',
    },
  })

import. webpack.config. Application (create react app)

new ModuleFederationPlugin({
  name: "cra",
  remotes: {
     Superset: "superset@http://localhost:8088/static/assets/entryFile.js",
  },
});

module.exports = function (webpackEnv) {
   output: {
      path: paths.appBuild,
      pathinfo: isEnvDevelopment,
      filename: isEnvProduction
        ? "static/js/[name].[contenthash:8].js"
        : isEnvDevelopment && "static/js/bundle.js",
      // There are also additional JS chunk files if you use code splitting.
      chunkFilename: isEnvProduction
        ? "static/js/[name].[contenthash:8].chunk.js"
        : isEnvDevelopment && "static/js/[name].chunk.js",
      assetModuleFilename: "static/media/[name].[hash][ext]",
      publicPath: "auto",
    },
}

import. Application (create react app). App.tsx

import("Superset/constants").then((data) => console.log(data));


问:
How can I write custom client certificate validation script with CloudFlare Access?
I use CloudFlare Access as a reverse proxy for my server, to protect it against denial of service attack and other benefits. I would like to protect access with mTLS which can be configured with CloudFlare. However, the verification options there are quite limited. I can filter for common name, ask for a valid certificate.

One thing I could do is use CloudFlare Worker alone to built a custom proxy, however I lose other benefits like the authentication from CloudFlare to my server using CloudFlare-signed JWT cookies.

How can I write a custom certificate validator without loss of any other functionality?


问:
Autosave script in Excel once in a while couldn't save the file
On remote desktop I have turned on Excel file 24/7 with working script in the loop. Everything works fine, however sometimes macro couldn't be saved (I got this information only when I check wheter file was saved).
I Have no idea why this happen. File is opened on remote machine all the time without closing it, additionally file is secured with password and no one is opening it in "write" mode, only in "read" - many people use this file.
Screen with error is attached,
Code below(works fine):

```<code>Private Sub Workbook_Open()
    Application.OnTime TimeValue("08:08:00"), "Module1.MyMacro", TimeValue("08:21:00")
    Application.OnTime TimeValue("12:08:00"), "Module1.MyMacro", TimeValue("12:21:00")
    Application.OnTime TimeValue("16:08:00"), "Module1.MyMacro", TimeValue("16:21:00")
    Application.OnTime TimeValue("22:08:00"), "Module1.MyMacro", TimeValue("22:21:00")
End Sub

Sub MyMacro()
ActiveWorkbook.RefreshAll
Application.Wait (Now + TimeValue("0:05:00"))
Filename = "XXXXX" & Format(Now, "DD_MM_YYYY") & "_XXXX"
ActiveWorkbook.Save
Application.DisplayAlerts = False
ActiveWorkbook.SaveCopyAs Filename:=Filename & ".xlsm"
Application.DisplayAlerts = True
Call Workbook_Open
End Sub
</code>```

Screen with error attached.

My theory is following, if someone with "Write" authorization is in file, while the file is being saved, then this person gets the precedence over this file. My knowledge about application workflow is however minor.

Body:
On remote desktop I have turned on Excel file 24/7 with working script in the loop. Everything works fine, however sometimes macro couldn't be saved (I got this information only when I check wheter file was saved).
I Have no idea why this happen. File is opened on remote machine all the time without closing it, additionally file is secured with password and no one is opening it in "write" mode, only in "read" - many people use this file.
Screen with error is attached,
Code below(works fine):

Private Sub Workbook_Open()
    Application.OnTime TimeValue("08:08:00"), "Module1.MyMacro", TimeValue("08:21:00")
    Application.OnTime TimeValue("12:08:00"), "Module1.MyMacro", TimeValue("12:21:00")
    Application.OnTime TimeValue("16:08:00"), "Module1.MyMacro", TimeValue("16:21:00")
    Application.OnTime TimeValue("22:08:00"), "Module1.MyMacro", TimeValue("22:21:00")
End Sub

Sub MyMacro()
ActiveWorkbook.RefreshAll
Application.Wait (Now + TimeValue("0:05:00"))
Filename = "XXXXX" & Format(Now, "DD_MM_YYYY") & "_XXXX"
ActiveWorkbook.Save
Application.DisplayAlerts = False
ActiveWorkbook.SaveCopyAs Filename:=Filename & ".xlsm"
Application.DisplayAlerts = True
Call Workbook_Open
End Sub

Screen with error attached.

My theory is following, if someone with "Write" authorization is in file, while the file is being saved, then this person gets the precedence over this file. My knowledge about application workflow is however minor.


问:
How can I click a button using Selenium and Python without a Button Class?

This is a picture of the HTML in question. I am trying to click the time slot @ 4:34PM. This one in particular is "Jump 65" and the previous timeslot is Jump 64. I'd like the ability to specify and click any of the buttons with a timeslot.


问:
Intercepting the network files in node/python
Is there any way I can get access to the files in network tab in an nodejs/react/python. screenshot attached for reference.

i'm trying to create a app where one can provide an url and it will search for the request files and give user .m3u8 filetype.


问:
Why my read token didn't work while save token is work. data store android.?
I have tried to make a session after login using data store. but i faced my read token didnt function and no idea to resolve it. please help me if you familiar with this case. and why it's work?

please help me for solve this case. i have new in android development

SplashViewModel

```<code>@HiltViewModel
class SplashViewModel @Inject constructor(
    private val datastore: AppDatastore
) : ViewModel() {

    private val _onBoardingCompleted = mutableStateOf(false)
    val onBoardingCompleted get() = _onBoardingCompleted

    private val _tokenIsEmpty = mutableStateOf("")
    val tokenIstEmpty get() = _tokenIsEmpty

    private val _startDestination: MutableState<String> = mutableStateOf(Screen.HomeScreen.route)
    val startDestination: State<String> = _startDestination

    init {
        viewModelScope.launch {
            datastore.readOnBoardingState().collect { completed ->
                if (completed) {
                    _startDestination.value = Screen.LoginScreen.route
                } else {
                    _startDestination.value = Screen.OnBoardingScreen.route
                }
                _onBoardingCompleted.value = true
            }

           datastore.readUserTokenState().collect { token ->
               if (token != ""){
                   _startDestination.value = Screen.HomeScreen.route
               }else{
                   _startDestination.value = Screen.OnBoardingScreen.route
               }
               _tokenIsEmpty.value = token
           }
        }
    }
}
</code>```

DataStore Class

```<code>class AppDatastore(context: Context) {

    companion object {
        val Context.datastore: DataStore<Preferences> by preferencesDataStore(name = "app_datastore")
        private val TOKEN = stringPreferencesKey(name = "token")
        private val ONBOARD = booleanPreferencesKey("onboard")
    }

    private val dataStore = context.datastore

    suspend fun saveOnBoardState(isCompleted: Boolean) {
        dataStore.edit { preferences ->
            preferences[ONBOARD] = isCompleted
        }
    }

    fun readOnBoardingState(): Flow<Boolean> {
        return dataStore.data
            .catch { exception ->
                if (exception is IOException) {
                    emit(emptyPreferences())
                } else {
                    throw exception
                }
            }
            .map { preferences ->
                val onBoardingState = preferences[ONBOARD] ?: false
                onBoardingState
            }
    }

    suspend fun saveUserToken(token: String) {
        dataStore.edit { preferences ->
            preferences[TOKEN] = token
        }
    }

    fun readUserTokenState(): Flow<String> {
        return dataStore.data
            .catch { exception ->
                if (exception is IOException) {
                    emit(emptyPreferences())
                } else {
                    throw exception
                }
            }
            .map { preferences ->
                val tokenState = preferences[TOKEN] ?: ""
                tokenState
            }
    }

    suspend fun deleteToken() {
        dataStore.edit { preferences ->
            preferences.remove(TOKEN)
        }
    }
}
</code>```

LoginViewModel

```<code>@HiltViewModel
class LoginViewModel @Inject constructor(
    private val loginUseCase: LoginUseCase,
    private val datastore: AppDatastore
) : ViewModel() {

    private val _loginState: MutableState<LoginState> = mutableStateOf(LoginState())
    val loginState: LoginState by _loginState

    fun login(username: String, password: String) {
        _loginState.value.isLoading
        viewModelScope.launch {
            loginUseCase.execute(LoginRequest(username, password)).collect { result ->
                when (result) {
                    is Resource.Success -> {
                        _loginState.value = LoginState().copy(
                            isLoading = false,
                            login = result.data,
                            error = null
                        )
                        saveToken(result.data?.token.toString())
                        Log.d("TAG", "login:  ${result.data?.token}")
                    }
                    is Resource.Error -> {
                        _loginState.value = LoginState().copy(
                            isLoading = false,
                            login = null,
                            error = result.message.toString()
                        )
                    }
                    is Resource.Loading -> {
                        _loginState.value = LoginState().copy(
                            isLoading = true,
                            login = null,
                            error = null
                        )
                    }
                }
            }
        }
    }

    fun saveToken(token: String) {
        viewModelScope.launch(Dispatchers.IO) {
            datastore.saveUserToken(token)
        }
    }
}
</code>```

SplashScreen

```<code>@Composable
fun SplashScreen(
    navController: NavController,
    loginViewModel: LoginViewModel = hiltViewModel(),
    splashViewModel: SplashViewModel = hiltViewModel()
) {
    var startAnimation by remember { mutableStateOf(false) }

    val alphaAnim = animateFloatAsState(
        targetValue = if (startAnimation) 0.8f else 0f,
        animationSpec = tween(
            durationMillis = 800,
            easing = {
                OvershootInterpolator(4f).getInterpolation(it)
            })
    )

    LaunchedEffect(key1 = true) {
        val token = splashViewModel.tokenIstEmpty.value
        val screen by splashViewModel.startDestination

        startAnimation = true
        delay(3000)
        navController.popBackStack()

//        if (splashViewModel.onBoardingCompleted.value){
//            val screen by splashViewModel.startDestination
//            navController.navigate(screen)
//        }
        when (token) {
            "" -> navController.navigate(screen)
            else -> navController.navigate(screen)
        }
    }
    Splash(scale = alphaAnim.value)
}
</code>```

Body:
I have tried to make a session after login using data store. but i faced my read token didnt function and no idea to resolve it. please help me if you familiar with this case. and why it's work?

please help me for solve this case. i have new in android development

SplashViewModel

@HiltViewModel
class SplashViewModel @Inject constructor(
    private val datastore: AppDatastore
) : ViewModel() {

    private val _onBoardingCompleted = mutableStateOf(false)
    val onBoardingCompleted get() = _onBoardingCompleted

    private val _tokenIsEmpty = mutableStateOf("")
    val tokenIstEmpty get() = _tokenIsEmpty

    private val _startDestination: MutableState<String> = mutableStateOf(Screen.HomeScreen.route)
    val startDestination: State<String> = _startDestination

    init {
        viewModelScope.launch {
            datastore.readOnBoardingState().collect { completed ->
                if (completed) {
                    _startDestination.value = Screen.LoginScreen.route
                } else {
                    _startDestination.value = Screen.OnBoardingScreen.route
                }
                _onBoardingCompleted.value = true
            }

           datastore.readUserTokenState().collect { token ->
               if (token != ""){
                   _startDestination.value = Screen.HomeScreen.route
               }else{
                   _startDestination.value = Screen.OnBoardingScreen.route
               }
               _tokenIsEmpty.value = token
           }
        }
    }
}

DataStore Class

class AppDatastore(context: Context) {

    companion object {
        val Context.datastore: DataStore<Preferences> by preferencesDataStore(name = "app_datastore")
        private val TOKEN = stringPreferencesKey(name = "token")
        private val ONBOARD = booleanPreferencesKey("onboard")
    }

    private val dataStore = context.datastore

    suspend fun saveOnBoardState(isCompleted: Boolean) {
        dataStore.edit { preferences ->
            preferences[ONBOARD] = isCompleted
        }
    }

    fun readOnBoardingState(): Flow<Boolean> {
        return dataStore.data
            .catch { exception ->
                if (exception is IOException) {
                    emit(emptyPreferences())
                } else {
                    throw exception
                }
            }
            .map { preferences ->
                val onBoardingState = preferences[ONBOARD] ?: false
                onBoardingState
            }
    }

    suspend fun saveUserToken(token: String) {
        dataStore.edit { preferences ->
            preferences[TOKEN] = token
        }
    }

    fun readUserTokenState(): Flow<String> {
        return dataStore.data
            .catch { exception ->
                if (exception is IOException) {
                    emit(emptyPreferences())
                } else {
                    throw exception
                }
            }
            .map { preferences ->
                val tokenState = preferences[TOKEN] ?: ""
                tokenState
            }
    }

    suspend fun deleteToken() {
        dataStore.edit { preferences ->
            preferences.remove(TOKEN)
        }
    }
}

LoginViewModel

@HiltViewModel
class LoginViewModel @Inject constructor(
    private val loginUseCase: LoginUseCase,
    private val datastore: AppDatastore
) : ViewModel() {

    private val _loginState: MutableState<LoginState> = mutableStateOf(LoginState())
    val loginState: LoginState by _loginState

    fun login(username: String, password: String) {
        _loginState.value.isLoading
        viewModelScope.launch {
            loginUseCase.execute(LoginRequest(username, password)).collect { result ->
                when (result) {
                    is Resource.Success -> {
                        _loginState.value = LoginState().copy(
                            isLoading = false,
                            login = result.data,
                            error = null
                        )
                        saveToken(result.data?.token.toString())
                        Log.d("TAG", "login:  ${result.data?.token}")
                    }
                    is Resource.Error -> {
                        _loginState.value = LoginState().copy(
                            isLoading = false,
                            login = null,
                            error = result.message.toString()
                        )
                    }
                    is Resource.Loading -> {
                        _loginState.value = LoginState().copy(
                            isLoading = true,
                            login = null,
                            error = null
                        )
                    }
                }
            }
        }
    }

    fun saveToken(token: String) {
        viewModelScope.launch(Dispatchers.IO) {
            datastore.saveUserToken(token)
        }
    }
}

SplashScreen

@Composable
fun SplashScreen(
    navController: NavController,
    loginViewModel: LoginViewModel = hiltViewModel(),
    splashViewModel: SplashViewModel = hiltViewModel()
) {
    var startAnimation by remember { mutableStateOf(false) }

    val alphaAnim = animateFloatAsState(
        targetValue = if (startAnimation) 0.8f else 0f,
        animationSpec = tween(
            durationMillis = 800,
            easing = {
                OvershootInterpolator(4f).getInterpolation(it)
            })
    )

    LaunchedEffect(key1 = true) {
        val token = splashViewModel.tokenIstEmpty.value
        val screen by splashViewModel.startDestination

        startAnimation = true
        delay(3000)
        navController.popBackStack()

//        if (splashViewModel.onBoardingCompleted.value){
//            val screen by splashViewModel.startDestination
//            navController.navigate(screen)
//        }
        when (token) {
            "" -> navController.navigate(screen)
            else -> navController.navigate(screen)
        }
    }
    Splash(scale = alphaAnim.value)
}


问:
Finding if the lcm of a list is in the set 3^d
I need to find a better way to raise the 'tes' variable in python till I can get the print out to terminate.
(Running rather slow at 700)

I propose the need for a better way of defining the 'shifts' list, and reducing redundancies since the problem is symmetric lcm(shifts(n,m))=lcm(shift(mxn))

N, M, k =3,3,0

tes =700

sides=[]

def gcd(n, m):

    if m == 0:

        return n

    return gcd(m, n % m)

for N in range(tes+1):

    M=3

    for M in range(tes+1):

        n, m, shifts = N, M, []

        while ma.floor(min (n,m)/2)>= 1:

            shifts.append(2*n+2*m-4)

            n-=2

            m-=2

        #lcm of shifts list

        lcm = 1

        for i in shifts:

            lcm = lcm * i // gcd(lcm, i)

        p = ma.log(lcm) / ma.log(3)

        # checking to see if power lcm is in {3^d} where d in Natural numbers

        if (p - int(p) == 0) and lcm>1:

                print(shifts, N, M,lcm)

        M+= 1

    N+ 1

```

So far I have attempted to come up with an equation to make composing the list more efficient (so far this pythonic manner seems to be working better). Was working with sympy but that became to cumbersome dealing with sympy.products to try and directly find the lcm of the list flat out because I couldn't get the bounds correct.

-If I could find a way to avoid redundancies, since lcm is the same f(m,n)=f(n,m).

-Need list comprehension for the shifts if not a basic formula

-Been Looking into mathematical ways to prove  if the two sets (3^d,lcm(shifts)) intersect for some natural numbers, but I need to transform lcm(shifts(n,m)) into an analytic function from the current programmatic/numerical method.

-Any resources are also helpful, because this is just a segment for the total project and any further reading I'm sure will be a help in the future for the overall project.

Body:
I need to find a better way to raise the 'tes' variable in python till I can get the print out to terminate.
(Running rather slow at 700)

I propose the need for a better way of defining the 'shifts' list, and reducing redundancies since the problem is symmetric lcm(shifts(n,m))=lcm(shift(mxn))

N, M, k =3,3,0

tes =700

sides=[]

def gcd(n, m):

    if m == 0:

        return n

    return gcd(m, n % m)

for N in range(tes+1):

    M=3

    for M in range(tes+1):

        n, m, shifts = N, M, []

        while ma.floor(min (n,m)/2)>= 1:

            shifts.append(2*n+2*m-4)

            n-=2

            m-=2

        #lcm of shifts list

        lcm = 1

        for i in shifts:

            lcm = lcm * i // gcd(lcm, i)

        p = ma.log(lcm) / ma.log(3)

        # checking to see if power lcm is in {3^d} where d in Natural numbers

        if (p - int(p) == 0) and lcm>1:

                print(shifts, N, M,lcm)

        M+= 1

    N+ 1

So far I have attempted to come up with an equation to make composing the list more efficient (so far this pythonic manner seems to be working better). Was working with sympy but that became to cumbersome dealing with sympy.products to try and directly find the lcm of the list flat out because I couldn't get the bounds correct.

-If I could find a way to avoid redundancies, since lcm is the same f(m,n)=f(n,m).

-Need list comprehension for the shifts if not a basic formula

-Been Looking into mathematical ways to prove  if the two sets (3^d,lcm(shifts)) intersect for some natural numbers, but I need to transform lcm(shifts(n,m)) into an analytic function from the current programmatic/numerical method.

-Any resources are also helpful, because this is just a segment for the total project and any further reading I'm sure will be a help in the future for the overall project.


问:
AWS Amplify - Automating Testing For A Dev Environment with Hosting
Problem: A variety of tutorials from AWS for integrating automated testing with CI/CD look to integrate the testing stage after, or within the build process by using a localhost:3000 server.

However, as AWS Amplify developers know, the local environment can sometimes offer a different user experience to deploying to a development environment, and using that environment with AWS Amplify's hosting service.

Therefore, how do I add testing not only at the build stage with localhost:3000, but also for the development environment's hosted url?

I'm looking to build all my resources (backend and front-end), with a git push to the code commit repository.

Idea of Stages:

Source

Build

Test

Deploy Cloud Formation Stacks

Test

Roll back if failure

Current amplify.yml:

Note: this currently does not work so please do not copy it for your build. Please refer to the hyperlink above.

```<code>version: 0.2
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*
test:
  phases:
    preTest:
      commands:
        - npm ci
        - npm install wait-on
        - npm install pm2
        - npm install mocha mochawesome mochawesome-merge mochawesome-report-generator
        - npx pm2 start npm -- dev
        - 'npx wait-on --timeout 300 http://localhost:3000'
    test:
      commands:
        - 'npx cypress run --reporter mochawesome --reporter-options "reportDir=cypress/report/mochawesome-report,overwrite=false,html=false,json=true,timestamp=mmddyyyy_HHMMss"'
    postTest:
      commands:
        - npx mochawesome-merge cypress/report/mochawesome-report/mochawesome*.json > cypress/report/mochawesome.json
        - npx pm2 kill
  artifacts:
    baseDirectory: cypress
    configFilePath: '**/mochawesome.json'
    files:
      - '**/*.png'
      - '**/*.mp4'
</code>```

Body:
Problem: A variety of tutorials from AWS for integrating automated testing with CI/CD look to integrate the testing stage after, or within the build process by using a localhost:3000 server.

However, as AWS Amplify developers know, the local environment can sometimes offer a different user experience to deploying to a development environment, and using that environment with AWS Amplify's hosting service.

Therefore, how do I add testing not only at the build stage with localhost:3000, but also for the development environment's hosted url?

I'm looking to build all my resources (backend and front-end), with a git push to the code commit repository.

Idea of Stages:

Source

Build

Test

Deploy Cloud Formation Stacks

Test

Roll back if failure

Current amplify.yml:

Note: this currently does not work so please do not copy it for your build. Please refer to the hyperlink above.

version: 0.2
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*
test:
  phases:
    preTest:
      commands:
        - npm ci
        - npm install wait-on
        - npm install pm2
        - npm install mocha mochawesome mochawesome-merge mochawesome-report-generator
        - npx pm2 start npm -- dev
        - 'npx wait-on --timeout 300 http://localhost:3000'
    test:
      commands:
        - 'npx cypress run --reporter mochawesome --reporter-options "reportDir=cypress/report/mochawesome-report,overwrite=false,html=false,json=true,timestamp=mmddyyyy_HHMMss"'
    postTest:
      commands:
        - npx mochawesome-merge cypress/report/mochawesome-report/mochawesome*.json > cypress/report/mochawesome.json
        - npx pm2 kill
  artifacts:
    baseDirectory: cypress
    configFilePath: '**/mochawesome.json'
    files:
      - '**/*.png'
      - '**/*.mp4'


问:
using cardview to get half discorectangle shape
half discorectangle

i need to add this shape to mu module using card view in android studio. can anyone please suggest some ideas or possible way to achieve it.

i use android studio dolphin version with java

i tried using card view but it curves on both the sides so it becomes a full discorectangle but i need half one of it.


问:
NgOnDestroy not working if close multiple browser tabs at once
This code is correct work if user close one or  two tabs of browser

```<code>@HostListener('window:beforeunload')
  async ngOnDestroy() {
    if (this.myValueSub) {
        this.myValueSub.unsubscribe();
    }

    await this.authService.logout();
  }
</code>```

But this code not work if user close  multiple browser tabs at once (five tabs or more)

What is the problem?

Can't determine the cause of the problem

Body:
This code is correct work if user close one or  two tabs of browser

@HostListener('window:beforeunload')
  async ngOnDestroy() {
    if (this.myValueSub) {
        this.myValueSub.unsubscribe();
    }

    await this.authService.logout();
  }

But this code not work if user close  multiple browser tabs at once (five tabs or more)

What is the problem?

Can't determine the cause of the problem


问:
Build failed : A problem occurred evaluating project ':@mauron85_react-native-background-geolocation-common'
FAILURE: Build failed with an exception.

Where:
Build file '/Users/User/Desktop/testApp/node_modules/@mauron85/react-native-background-geolocation/android/common/build.gradle' line: 1

What went wrong:
A problem occurred evaluating project ':@mauron85_react-native-background-geolocation-common'.

Failed to apply plugin 'com.android.internal.library'.

The option 'android.enableUnitTestBinaryResources' is deprecated.
The current default is 'false'.
It has been removed from the current version of the Android Gradle plugin.
The raw resource for unit test functionality is removed.

Steps for solution :-

Install patch-package, this will later be used to make the changes permanent. (optional - step)

Now you have to hack the node_modules. Go to node_modules@mauron85\react-native-
background-geolocation\android\common\gradle.properties  change below things:-

android.enableUnitTestBinaryResources=true # <-- remove this line

android.builder.sdkDownload=true

Run npx patch-package @mauron85/react-native-background-geolocation to save the patch.

Rebuild the app.


问:
How can I save the session in nextjs using auth0
How can I save my session in next Js using auth0. Every time I refresh the page the session is lost

I only configure auth0 to do Login and Logout, I can get the user information but once I refresh the page it is lost


问:
requestPermissions(arrayOf(Manifest.permission.BLUETOOTH_CONNECT), REQUEST_CODE) not showing pop up in Android 10 but its working in Android 12
The below code is Working for Android 12 but same not working Android 10 the problem its it showing the run time permission pop up for BLUETOOTH_CONNECT

Here is the below code i have written inside the fragment

```<code>class FirstFragment : Fragment() {

    private var _binding: FragmentFirstBinding? = null
    private var ctx: Context? = null
    val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()

    companion object {
        private const val BLUETOOTH_PERMISSION_CODE = 100
        private const val BLUETOOTH_CONNECT_PERMISSION_CODE = 101
    }

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        _binding = FragmentFirstBinding.inflate(inflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        this.ctx = view.context
        //get the devie manifrature name
        System.out.println(android.os.Build.MANUFACTURER)
        //get the type of the bluetooth device
        getBluetoothDeviceType()
        checkPermission(
            Manifest.permission.BLUETOOTH_CONNECT,
            BLUETOOTH_CONNECT_PERMISSION_CODE
        )
        binding.buttonFirst.setOnClickListener {
            findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
        }
    }

    private fun requestBluetoothPermission() {

    }

    private fun getBluetoothDeviceType() {

        if (ActivityCompat.checkSelfPermission(
                ctx!!,
                Manifest.permission.BLUETOOTH_CONNECT
            ) != PackageManager.PERMISSION_GRANTED
        ) {

            if (BluetoothClass.Device.PHONE_CELLULAR == 0x0204) {
                System.out.println("permission is granted")
            }

        } else {
            if (BluetoothClass.Device.PHONE_CELLULAR != 0x0204) {
                System.out.println("permission is not granted")
            }
        }

    }

    private fun checkPermission(permission: String, requestCode: Int) {
        if (ContextCompat.checkSelfPermission(
                ctx!! as Activity,
                permission
            ) != PackageManager.PERMISSION_GRANTED
        ) {

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                println("permission is not required")
            } else {
                requestPermissions(arrayOf(permission), requestCode)
            }

            // Requesting the permission

            //Fragment.requestPermission.launch(Manifest.permission.CAMERA)
        } else {

            Toast.makeText(ctx!! as Activity, "Permission already granted", Toast.LENGTH_SHORT)
                .show()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == BLUETOOTH_CONNECT_PERMISSION_CODE) {
            //permission granted
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (bluetoothAdapter == null) {
                    // Handle the situation where Bluetooth is not available
                } else {
                    // Get a set of currently paired devices
                    if (ContextCompat.checkSelfPermission(
                            ctx!! as Activity,
                            permissions[0]
                        ) == PackageManager.PERMISSION_GRANTED
                    ) {
                        val pairedDevices: Set<BluetoothDevice> = bluetoothAdapter.bondedDevices

                        // If there are paired devices
                        if (pairedDevices.isNotEmpty()) {
                            // Loop through paired devices
                            for (device in pairedDevices) {
                                // Check if the device is a scanner
                                if (device.bluetoothClass.majorDeviceClass == BluetoothClass.Device.Major.IMAGING) {
                                    // Device is a scanner
                                    val scannerDevice = device
                                    println("Scanner found: ${scannerDevice.name}")
                                }
                            }
                        } else {
                            // Handle the situation where there are no paired devices
                        }
                    }

                    Toast.makeText(
                        ctx!! as Activity,
                        "Bluetooth Connect Permission Granted",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            } else {
                Toast.makeText(
                    ctx!! as Activity,
                    "Bluetooth Connect Permission Denied",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
</code>```

here how below my build.gradle looks like

```<code>android {
    compileSdk 33

    defaultConfig {
        applicationId "com.demo"
        minSdk 23
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
</code>```

Body:
The below code is Working for Android 12 but same not working Android 10 the problem its it showing the run time permission pop up for BLUETOOTH_CONNECT

Here is the below code i have written inside the fragment

class FirstFragment : Fragment() {

    private var _binding: FragmentFirstBinding? = null
    private var ctx: Context? = null
    val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()

    companion object {
        private const val BLUETOOTH_PERMISSION_CODE = 100
        private const val BLUETOOTH_CONNECT_PERMISSION_CODE = 101
    }

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        _binding = FragmentFirstBinding.inflate(inflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        this.ctx = view.context
        //get the devie manifrature name
        System.out.println(android.os.Build.MANUFACTURER)
        //get the type of the bluetooth device
        getBluetoothDeviceType()
        checkPermission(
            Manifest.permission.BLUETOOTH_CONNECT,
            BLUETOOTH_CONNECT_PERMISSION_CODE
        )
        binding.buttonFirst.setOnClickListener {
            findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
        }
    }

    private fun requestBluetoothPermission() {

    }

    private fun getBluetoothDeviceType() {

        if (ActivityCompat.checkSelfPermission(
                ctx!!,
                Manifest.permission.BLUETOOTH_CONNECT
            ) != PackageManager.PERMISSION_GRANTED
        ) {

            if (BluetoothClass.Device.PHONE_CELLULAR == 0x0204) {
                System.out.println("permission is granted")
            }

        } else {
            if (BluetoothClass.Device.PHONE_CELLULAR != 0x0204) {
                System.out.println("permission is not granted")
            }
        }

    }

    private fun checkPermission(permission: String, requestCode: Int) {
        if (ContextCompat.checkSelfPermission(
                ctx!! as Activity,
                permission
            ) != PackageManager.PERMISSION_GRANTED
        ) {

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                println("permission is not required")
            } else {
                requestPermissions(arrayOf(permission), requestCode)
            }

            // Requesting the permission

            //Fragment.requestPermission.launch(Manifest.permission.CAMERA)
        } else {

            Toast.makeText(ctx!! as Activity, "Permission already granted", Toast.LENGTH_SHORT)
                .show()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == BLUETOOTH_CONNECT_PERMISSION_CODE) {
            //permission granted
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (bluetoothAdapter == null) {
                    // Handle the situation where Bluetooth is not available
                } else {
                    // Get a set of currently paired devices
                    if (ContextCompat.checkSelfPermission(
                            ctx!! as Activity,
                            permissions[0]
                        ) == PackageManager.PERMISSION_GRANTED
                    ) {
                        val pairedDevices: Set<BluetoothDevice> = bluetoothAdapter.bondedDevices

                        // If there are paired devices
                        if (pairedDevices.isNotEmpty()) {
                            // Loop through paired devices
                            for (device in pairedDevices) {
                                // Check if the device is a scanner
                                if (device.bluetoothClass.majorDeviceClass == BluetoothClass.Device.Major.IMAGING) {
                                    // Device is a scanner
                                    val scannerDevice = device
                                    println("Scanner found: ${scannerDevice.name}")
                                }
                            }
                        } else {
                            // Handle the situation where there are no paired devices
                        }
                    }

                    Toast.makeText(
                        ctx!! as Activity,
                        "Bluetooth Connect Permission Granted",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            } else {
                Toast.makeText(
                    ctx!! as Activity,
                    "Bluetooth Connect Permission Denied",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

here how below my build.gradle looks like

android {
    compileSdk 33

    defaultConfig {
        applicationId "com.demo"
        minSdk 23
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }


问:
Queries with inner joins in database layer or filtering on ids generated in application layer?
I have a table that describes a document with title, content, created_at, etc and a struct that describes columns to filter that table

struct Partial {
    handle: String,
    title: String,
    content: String,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
}
```
<p>which; after some transformations, I pass to the database layer and depending on who the user is, return a set of rows.</p>
<p>For example, if user is the author, user can search any columns, otherwise they can search only publicly visible documents.</p>
<p>A user can also 'share' a document with another user so if there a share from the requester to the document owner, the user should also be able to search in those documents as well.</p>
<p>There are two ways to go about that (as far as I know)</p>
<ol>
<li><p>Use inner joins and filter on columns</p>
<pre class="lang-sql prettyprint-override"><code>INNER JOIN author on document.id = author.document_id
INNER JOIN visibility on document.id = visibility.document_id
INNER JOIN share on document.id = share.document_id
...
...
...
</code>```

WHERE document.handle = $handle -- from `Partial` struct
WHERE document.title = $title -- from `Partial` struct
WHERE document.content = $content -- from `Partial` struct
WHERE author.user_id = $user_id -- from user info passed to db
WHERE visibility.scope = 'PUBLIC' -- from user info passed to db
WHERE share.shared_to = $user_id -- from user info passed to db
WHERE group.member = $user_id -- from user info passed to db
...
...
...
```
<p>This requires passing user information (<code>$user_id</code> for this example but this also sometimes includes additional info like if the user is blocked or the account is non-public, belongs to a group, etc. Around 12 properties in total) to the database layer.</p>
</li>
<li><p>generate a list of <code>id</code>s in application layer and pass it on to the database layer.</p>
<p>For example,</p>
<pre class="lang-rust prettyprint-override"><code>let public_document_ids = visibility.find(Find { visibility: Visibility::Public }).map(|visibility_row| visibility_row.document_id).collect();
let authored_document_ids = author.find(Find { document_author: user_id }).map(|authored_row| authored_row.document_id).collect();
let shared_document_ids = share.find(Find { shared_to: user_id }).map(|share_row| share_row.document_id).collect();
</code>```

and then pass sum of all of these ids to database

WHERE document.handle = $handle -- from `Partial` struct
WHERE document.title = $title -- from `Partial` struct
WHERE document.content = $content -- from `Partial` struct
WHERE document.id IN $ids -- from `ids` passed to db
...
...
...
```

To me it seems that the first approach of using inner joins and filtering on columns in the database can

potentially be more efficient,

and a lot more easier to get right

but the second approach, generating a list of ids in the application layer, allows

a lot more flexibility and

also lets me use different (distributed) databases to store different tables (perhaps even different database drivers)

It also reduces the amount of user information passed to the database layer

but it also requires loading all the data into the application layer before filtering the results

and implementing pagination will be lot more complex

So my question - is there a way to know which approach I should go with? Perhaps there's something I haven't considered yet.

Body:
I have a table that describes a document with title, content, created_at, etc and a struct that describes columns to filter that table

struct Partial {
    handle: String,
    title: String,
    content: String,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
}

which; after some transformations, I pass to the database layer and depending on who the user is, return a set of rows.

For example, if user is the author, user can search any columns, otherwise they can search only publicly visible documents.

A user can also 'share' a document with another user so if there a share from the requester to the document owner, the user should also be able to search in those documents as well.

There are two ways to go about that (as far as I know)

Use inner joins and filter on columns

INNER JOIN author on document.id = author.document_id
INNER JOIN visibility on document.id = visibility.document_id
INNER JOIN share on document.id = share.document_id
...
...
...

WHERE document.handle = $handle -- from `Partial` struct
WHERE document.title = $title -- from `Partial` struct
WHERE document.content = $content -- from `Partial` struct
WHERE author.user_id = $user_id -- from user info passed to db
WHERE visibility.scope = 'PUBLIC' -- from user info passed to db
WHERE share.shared_to = $user_id -- from user info passed to db
WHERE group.member = $user_id -- from user info passed to db
...
...
...

This requires passing user information ($user_id for this example but this also sometimes includes additional info like if the user is blocked or the account is non-public, belongs to a group, etc. Around 12 properties in total) to the database layer.

generate a list of ids in application layer and pass it on to the database layer.

For example,

let public_document_ids = visibility.find(Find { visibility: Visibility::Public }).map(|visibility_row| visibility_row.document_id).collect();
let authored_document_ids = author.find(Find { document_author: user_id }).map(|authored_row| authored_row.document_id).collect();
let shared_document_ids = share.find(Find { shared_to: user_id }).map(|share_row| share_row.document_id).collect();

and then pass sum of all of these ids to database

WHERE document.handle = $handle -- from `Partial` struct
WHERE document.title = $title -- from `Partial` struct
WHERE document.content = $content -- from `Partial` struct
WHERE document.id IN $ids -- from `ids` passed to db
...
...
...

To me it seems that the first approach of using inner joins and filtering on columns in the database can

potentially be more efficient,

and a lot more easier to get right

but the second approach, generating a list of ids in the application layer, allows

a lot more flexibility and

also lets me use different (distributed) databases to store different tables (perhaps even different database drivers)

It also reduces the amount of user information passed to the database layer

but it also requires loading all the data into the application layer before filtering the results

and implementing pagination will be lot more complex

So my question - is there a way to know which approach I should go with? Perhaps there's something I haven't considered yet.


问:
Regarding using GPU with tensorflow
I installed tensorflow-gpu following (https://www.tensorflow.org/install/pip#step-by-step_instructions) But when I import tensorflow I got this message. When I went through stackoverflow's previous posts, it seems like the message is not an issue.

But after that when I tired to execute a code, I met with this error. Can someone help me to figure this out. I'm using ubuntu 22.04 LTS

I tried going through blog posts but non of them worked out. I'm expecting to solve this error.

Title: Regarding using GPU with tensorflow


问:
Translate text in database column - Python, SQL Server, SSIS
I have table in Excel. There is one column, where are cca 10 000 rows with short text (max one sentence). The text is written in Russian and I need to translate it into English.

I have data uploaded through SSIS to SQL Server. I can use also Python for translate the text.

Please, does anyone know how I can translate my data which have more then 10 000 characters (so Google translate library in Python does not work)? I can translate text in Python, SSIS, SQL Server or Excel.

Thank you

This is my code in Python

```<code>import googletrans
from googletrans import Translator

WD = r'PATH TO EXCEL'

for file in os.listdir(WD):
    if file.endswith('.xlsx'):
        FILE = file

        sheet_names = pd.ExcelFile(FILE).sheet_names

        for sn in sheet_names:
            OUTPUT_FILE = '{}_{}'
            df = pd.read_excel(FILE)
            print(FILE, sn)

            for col in df.columns.to_list():
                df[col] = df[col].map({True: '', False: ''}).fillna(df[col])

                translator = googletrans.Translator()
                df['NAME_COLUMN'] = df['NAME_COLUMN'].apply(translator.translate, src ='ru', dest = 'cs').apply(getattr, args=('text',))
                df
</code>```

But script is always cancelled with this error message:

httpcore._exceptions.ReadTimeout The read operation timed out

Then I tried translate text in Excel - copy text to word and translate in Microsoft web translator, bud the text is so large

Body:
I have table in Excel. There is one column, where are cca 10 000 rows with short text (max one sentence). The text is written in Russian and I need to translate it into English.

I have data uploaded through SSIS to SQL Server. I can use also Python for translate the text.

Please, does anyone know how I can translate my data which have more then 10 000 characters (so Google translate library in Python does not work)? I can translate text in Python, SSIS, SQL Server or Excel.

Thank you

This is my code in Python

import googletrans
from googletrans import Translator

WD = r'PATH TO EXCEL'

for file in os.listdir(WD):
    if file.endswith('.xlsx'):
        FILE = file

        sheet_names = pd.ExcelFile(FILE).sheet_names

        for sn in sheet_names:
            OUTPUT_FILE = '{}_{}'
            df = pd.read_excel(FILE)
            print(FILE, sn)

            for col in df.columns.to_list():
                df[col] = df[col].map({True: '', False: ''}).fillna(df[col])

                translator = googletrans.Translator()
                df['NAME_COLUMN'] = df['NAME_COLUMN'].apply(translator.translate, src ='ru', dest = 'cs').apply(getattr, args=('text',))
                df

But script is always cancelled with this error message:

httpcore._exceptions.ReadTimeout The read operation timed out

Then I tried translate text in Excel - copy text to word and translate in Microsoft web translator, bud the text is so large


问:
Excel VBA validation with more than 1 row
How do I write the code that would auto scan the last row and see if the value has been input?
eg. sometimes I have 1 row, sometimes I have 3 rows, 5 rows etc of data in the excel to do the data validation.
Below is my code but only do 1 row.</p>
```<code>Private Sub Validation()

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet
Set ws = wb.Sheets("Data")

Data_1 = ws.Cells(2, 10).Value
Data_2 = ws.Cells(2, 17).Value
Data_3 = ws.Cells(2, 18).Value

If Data_1 = "" Then
MsgBox "Data_1 is not entered", vbCritical
Exit Sub
End If

If Data_2 = "" Then
MsgBox "G_dormant_company is not entered", vbCritical
Exit Sub
End If

End Sub
</code>```

Body:
How do I write the code that would auto scan the last row and see if the value has been input?
eg. sometimes I have 1 row, sometimes I have 3 rows, 5 rows etc of data in the excel to do the data validation.
Below is my code but only do 1 row.

Private Sub Validation()

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet
Set ws = wb.Sheets("Data")

Data_1 = ws.Cells(2, 10).Value
Data_2 = ws.Cells(2, 17).Value
Data_3 = ws.Cells(2, 18).Value

If Data_1 = "" Then
MsgBox "Data_1 is not entered", vbCritical
Exit Sub
End If

If Data_2 = "" Then
MsgBox "G_dormant_company is not entered", vbCritical
Exit Sub
End If

End Sub