问:
Sensoray 826 cards driver problems with MATLAB
this is my first topic if anything wrong please advise me.
I am not a great matlab user but I need to use matlab with sensoray 826 to capture the data.
However, once I install the driver and try to run 826 Matlab demo I got the error code below.

Warning: Warnings messages were produced while parsing.  Check the functions you intend to use for correctness.  Warning text can be viewed using:
[notfound,warnings]=loadlibrary(...)

I try to find the root cause of this problem and get new error.

```<code>[notfound, warnings] = loadlibrary('C:\Program Files (x86)\Sensoray\826\API\x64\s826.dll')
Error using loadlibrary
There was an error loading the library "C:\Program Files (x86)\Sensoray\826\API\x64\s826.dll"
Unrecognized function or variable 's826_proto'.

Caused by:
    Error using feval
    Unrecognized function or variable 's826_proto'.
</code>```

At this point I believe that the error is cause from incorrect DLL file from the sensoray.
I try to contact the Sensoray but they rarely answer back to me.
If anyone know how to solve this issue please kindly reply back to me.

The code I use to run in Matlab:

```<code>% Load the 826 API and open a connection to the 826 board
dllPath = 'C:\Program Files (x86)\Sensoray\826\API\x64\s826.dll'; % Replace with the correct path to the DLL file
hdrPath = 'C:\Program Files (x86)\Sensoray\826\API\826api.h'; % Replace with the correct path to the header file
[errcode, boardflags] = s826.SystemOpen(dllPath, hdrPath);
if errcode ~= 0
    error('Error opening connection to 826 board: %d', errcode);
end

% Configure the rotary sensor
counter = 0; % Choose the counter that the rotary sensor is connected to (0-3)
s826.CounterModeWrite(counter, s826.CNTR_QUADX4); % Configure the counter for quadrature input
s826.CounterPreloadWrite(counter, 0, 0); % Reset the counter

% Read the counter value
count = s826.CounterRead(counter);

% Close the connection to the 826 board
s826.SystemClose();
</code>```

I would like to go step by step since I never use this 826 cards before.
So first just correctly call the DLL and H file is enough for me.

Body:
this is my first topic if anything wrong please advise me.
I am not a great matlab user but I need to use matlab with sensoray 826 to capture the data.
However, once I install the driver and try to run 826 Matlab demo I got the error code below.

Warning: Warnings messages were produced while parsing.  Check the functions you intend to use for correctness.  Warning text can be viewed using:
[notfound,warnings]=loadlibrary(...)

I try to find the root cause of this problem and get new error.

[notfound, warnings] = loadlibrary('C:\Program Files (x86)\Sensoray\826\API\x64\s826.dll')
Error using loadlibrary
There was an error loading the library "C:\Program Files (x86)\Sensoray\826\API\x64\s826.dll"
Unrecognized function or variable 's826_proto'.

Caused by:
    Error using feval
    Unrecognized function or variable 's826_proto'.

At this point I believe that the error is cause from incorrect DLL file from the sensoray.
I try to contact the Sensoray but they rarely answer back to me.
If anyone know how to solve this issue please kindly reply back to me.

The code I use to run in Matlab:

% Load the 826 API and open a connection to the 826 board
dllPath = 'C:\Program Files (x86)\Sensoray\826\API\x64\s826.dll'; % Replace with the correct path to the DLL file
hdrPath = 'C:\Program Files (x86)\Sensoray\826\API\826api.h'; % Replace with the correct path to the header file
[errcode, boardflags] = s826.SystemOpen(dllPath, hdrPath);
if errcode ~= 0
    error('Error opening connection to 826 board: %d', errcode);
end

% Configure the rotary sensor
counter = 0; % Choose the counter that the rotary sensor is connected to (0-3)
s826.CounterModeWrite(counter, s826.CNTR_QUADX4); % Configure the counter for quadrature input
s826.CounterPreloadWrite(counter, 0, 0); % Reset the counter

% Read the counter value
count = s826.CounterRead(counter);

% Close the connection to the 826 board
s826.SystemClose();

I would like to go step by step since I never use this 826 cards before.
So first just correctly call the DLL and H file is enough for me.


来源: stackexchange

问:
The following _TypeError was thrown building RecommendedFoodDetail (dirty): type 'Null' is not a subtype of type 'int'
I have this error code:

======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building RecommendedFoodDetail(dirty):
type 'Null' is not a subtype of type 'int'

The relevant error-causing widget was:
RecommendedFoodDetail RecommendedFoodDetail:file:///C:/Users/IMAN/StudioProjects/food_app/lib/routes/route_helper.dart:33:14
When the exception was thrown, this was the stack:
#0      PopularProductController.initProduct (package:food_app/controllers/popular_product_controller.dart:80:7)
#1      RecommendedFoodDetail.build (package:food_app/pages/food/recommended_food_detail.dart:24:42)
#2      StatelessElement.build (package:flutter/src/widgets/framework.dart:4949:49)
#3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4878:15)
#4      Element.rebuild (package:flutter/src/widgets/framework.dart:4604:5)
#5      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4859:5)
#6      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4853:5)
...     Normal element mounting (154 frames)

I'm typing the codes the same as my instructure but I don't know why I got that error.

Thanks in advance

cart_page.dart

```<code>GestureDetector(
  onTap: (){
     var popularIndex=Get.find<PopularProductController>()
         .popularProductList
         .indexOf(_cartList[index].product);
     if( popularIndex>=0){
       Get.toNamed(RouteHelper.getPopularFood(popularIndex,"cartpage"));
     }else{
       var recommendedIndex=Get.find<RecommendedProductController>()
           .recommendedProductList
           .indexOf(_cartList[index].product);
       Get.toNamed(RouteHelper.getRecommendedFood(recommendedIndex,"cartpage"));
     }
  },
  child:  Container(
    width: Dimensions.height20*5,
    height: Dimensions.height20*5,
    margin: EdgeInsets.only(bottom: Dimensions.height10),
    decoration: BoxDecoration(
      image: DecorationImage(
          fit: BoxFit.cover,
          image: NetworkImage(
              AppConnstants.BASE_URL+AppConnstants.UPLOAD_URL+cartController.getItems[index].img!
          )
      ),
      borderRadius: BorderRadius.circular(Dimensions.radius20),

    ),
  ),
),
</code>```

cart_controller.dart

```<code>

  bool existInCart(ProductModel product) {
    if (_items.containsKey(product.id)) {
      return true;
    }
    return false;
  }

  getQuantity(ProductModel product) {
    var quantity = 0;
    if (_items.containsKey(product.id)) {
      _items.forEach((key, value) {
        if (key == product.id) {
          quantity = value.quantity!;
        }
      });
    }
  }

  int get totalItems {
    var totalQuantity = 0;
    _items.forEach((key, value) {
      totalQuantity += value.quantity!;
    });
    return totalQuantity;
  }

  List<CartModel> get getItems {
   return _items.entries.map((e){
     return e.value;

    }).toList();

  }
}
</code>```

route_helper.dart

```<code>class RouteHelper{
  static const String initial="/";
  static const String popularFood="/popular-food";
  static const String recommendedFood="/recommended-food";
  static const String cartPage="/cart-page";

  static String getInitial()=>'$initial';
  static String getPopularFood(int pageId, String page)=>'$popularFood?pageId=$pageId&page=$page';
  static String getRecommendedFood(int pageId, String page )=>'$recommendedFood?pageId=$pageId&page=$page';
  static String getCartPage()=> '$cartPage';

  static List<GetPage> routes=[
    GetPage(name: initial, page: ()=>MainFoodPage()),
    GetPage(name: popularFood, page: (){
      var pageId= Get.parameters['pageId'];
      var page=Get.parameters["page"];
      return Container(
          child: PopularFoodDetail(pageId:int.parse(pageId!),page:page!));
    },
    transition: Transition.fadeIn
    ),
    GetPage(name: recommendedFood, page: (){
      var pageId= Get.parameters['pageId'];
      var page=Get.parameters["page"];
      return RecommendedFoodDetail(pageId:int.parse(pageId!),page: page!);
    },
        transition: Transition.fadeIn
    ),
    GetPage(name: cartPage, page: (){
      return CartPage();

    },
    transition: Transition.fadeIn
    )
  ];
}
</code>```

recommended_food_detail.dart

```<code>GetBuilder<PopularProductController>(
    builder: (controller){
      return GestureDetector(
        onTap: (){
          if( controller.totalItems>=1)
            Get.toNamed(RouteHelper.getCartPage());
        },
        child: Stack(
          children: [
            AppIcon(icon: Icons.shopping_cart),
            Get.find<PopularProductController>().totalItems>=1?
            Positioned(
              right:0, top:0,
                child: AppIcon(icon: Icons.circle,
                  size: 20,
                  iconColor: Colors.transparent,
                  backgroundColor:AppColors.mainColor,),
            ):
            Container(),
            Get.find<PopularProductController>().totalItems>=1?
            Positioned(
                right:3, top:3,
                child:BigText(text:Get.find<PopularProductController>().totalItems.toString(),
                  size: 12, color: Colors.white,
                )
            ):
            Container(),
          ],
        ),
      );
    }),
</code>```

popular_foor_details.dart

```<code>GestureDetector(
          onTap:(){
            if(page=="cartpage"){
              Get.toNamed(RouteHelper.getCartPage());

            }else{
              Get.toNamed(RouteHelper.getInitial());
            }

},
            child: AppIcon(icon: Icons.arrow_back_ios,)),
</code>```

.....................

ContentLicense: CC BY-SA 4.0

Body:
I have this error code:

======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building RecommendedFoodDetail(dirty):
type 'Null' is not a subtype of type 'int'

The relevant error-causing widget was:
RecommendedFoodDetail RecommendedFoodDetail:file:///C:/Users/IMAN/StudioProjects/food_app/lib/routes/route_helper.dart:33:14
When the exception was thrown, this was the stack:
#0      PopularProductController.initProduct (package:food_app/controllers/popular_product_controller.dart:80:7)
#1      RecommendedFoodDetail.build (package:food_app/pages/food/recommended_food_detail.dart:24:42)
#2      StatelessElement.build (package:flutter/src/widgets/framework.dart:4949:49)
#3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4878:15)
#4      Element.rebuild (package:flutter/src/widgets/framework.dart:4604:5)
#5      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4859:5)
#6      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4853:5)
...     Normal element mounting (154 frames)

I'm typing the codes the same as my instructure but I don't know why I got that error.

Thanks in advance

cart_page.dart

GestureDetector(
  onTap: (){
     var popularIndex=Get.find<PopularProductController>()
         .popularProductList
         .indexOf(_cartList[index].product);
     if( popularIndex>=0){
       Get.toNamed(RouteHelper.getPopularFood(popularIndex,"cartpage"));
     }else{
       var recommendedIndex=Get.find<RecommendedProductController>()
           .recommendedProductList
           .indexOf(_cartList[index].product);
       Get.toNamed(RouteHelper.getRecommendedFood(recommendedIndex,"cartpage"));
     }
  },
  child:  Container(
    width: Dimensions.height20*5,
    height: Dimensions.height20*5,
    margin: EdgeInsets.only(bottom: Dimensions.height10),
    decoration: BoxDecoration(
      image: DecorationImage(
          fit: BoxFit.cover,
          image: NetworkImage(
              AppConnstants.BASE_URL+AppConnstants.UPLOAD_URL+cartController.getItems[index].img!
          )
      ),
      borderRadius: BorderRadius.circular(Dimensions.radius20),

    ),
  ),
),

cart_controller.dart

  bool existInCart(ProductModel product) {
    if (_items.containsKey(product.id)) {
      return true;
    }
    return false;
  }

  getQuantity(ProductModel product) {
    var quantity = 0;
    if (_items.containsKey(product.id)) {
      _items.forEach((key, value) {
        if (key == product.id) {
          quantity = value.quantity!;
        }
      });
    }
  }

  int get totalItems {
    var totalQuantity = 0;
    _items.forEach((key, value) {
      totalQuantity += value.quantity!;
    });
    return totalQuantity;
  }

  List<CartModel> get getItems {
   return _items.entries.map((e){
     return e.value;

    }).toList();

  }
}

route_helper.dart

class RouteHelper{
  static const String initial="/";
  static const String popularFood="/popular-food";
  static const String recommendedFood="/recommended-food";
  static const String cartPage="/cart-page";

  static String getInitial()=>'$initial';
  static String getPopularFood(int pageId, String page)=>'$popularFood?pageId=$pageId&page=$page';
  static String getRecommendedFood(int pageId, String page )=>'$recommendedFood?pageId=$pageId&page=$page';
  static String getCartPage()=> '$cartPage';

  static List<GetPage> routes=[
    GetPage(name: initial, page: ()=>MainFoodPage()),
    GetPage(name: popularFood, page: (){
      var pageId= Get.parameters['pageId'];
      var page=Get.parameters["page"];
      return Container(
          child: PopularFoodDetail(pageId:int.parse(pageId!),page:page!));
    },
    transition: Transition.fadeIn
    ),
    GetPage(name: recommendedFood, page: (){
      var pageId= Get.parameters['pageId'];
      var page=Get.parameters["page"];
      return RecommendedFoodDetail(pageId:int.parse(pageId!),page: page!);
    },
        transition: Transition.fadeIn
    ),
    GetPage(name: cartPage, page: (){
      return CartPage();

    },
    transition: Transition.fadeIn
    )
  ];
}

recommended_food_detail.dart

GetBuilder<PopularProductController>(
    builder: (controller){
      return GestureDetector(
        onTap: (){
          if( controller.totalItems>=1)
            Get.toNamed(RouteHelper.getCartPage());
        },
        child: Stack(
          children: [
            AppIcon(icon: Icons.shopping_cart),
            Get.find<PopularProductController>().totalItems>=1?
            Positioned(
              right:0, top:0,
                child: AppIcon(icon: Icons.circle,
                  size: 20,
                  iconColor: Colors.transparent,
                  backgroundColor:AppColors.mainColor,),
            ):
            Container(),
            Get.find<PopularProductController>().totalItems>=1?
            Positioned(
                right:3, top:3,
                child:BigText(text:Get.find<PopularProductController>().totalItems.toString(),
                  size: 12, color: Colors.white,
                )
            ):
            Container(),
          ],
        ),
      );
    }),

popular_foor_details.dart

GestureDetector(
          onTap:(){
            if(page=="cartpage"){
              Get.toNamed(RouteHelper.getCartPage());

            }else{
              Get.toNamed(RouteHelper.getInitial());
            }

},
            child: AppIcon(icon: Icons.arrow_back_ios,)),

.....................


问:
optmizing queries in django
Here I have four models Category, Products, ProductOffer and CategoryOffer. The CategoryOffer is Foreignkey to Category and ProductOffer is Foreignkey to Products. And while a product have an offer and the category having the product also have an offer. I'll compare both offers and shows whichever is higher. So far everything is working but when I looked on to how much queries is getting executed. It's a lot. It's shown below:

```<code>(0.000) SELECT "accounts_account"."id", "accounts_account"."password", "accounts_account"."first_name", "accounts_account"."last_name", "accounts_account"."email", "accounts_account"."date_joined", "accounts_account"."last_login", "accounts_account"."is_admin", "accounts_account"."is_staff", "accounts_account"."is_active" FROM "accounts_account" WHERE "accounts_account"."id" = 52 LIMIT 21; args=(52,); alias=default
(0.016) SELECT "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_products" INNER JOIN "inventory_category" ON ("inventory_products"."category_id" = "inventory_category"."id") WHERE "inventory_products"."is_available"; args=(); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 5) LIMIT 21; args=(5,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active" FROM "inventory_categoryoffer" WHERE ("inventory_categoryoffer"."category_id" = 4 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(4,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_categoryoffer" INNER JOIN "inventory_category" ON ("inventory_categoryoffer"."category_id" = "inventory_category"."id") WHERE ("inventory_categoryoffer"."category_id" = 4 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(4,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 5) LIMIT 21; args=(5,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 4) LIMIT 21; args=(4,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active" FROM "inventory_categoryoffer" WHERE ("inventory_categoryoffer"."category_id" = 4 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(4,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_categoryoffer" INNER JOIN "inventory_category" ON ("inventory_categoryoffer"."category_id" = "inventory_category"."id") WHERE ("inventory_categoryoffer"."category_id" = 4 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(4,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 4) LIMIT 21; args=(4,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 3) LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active" FROM "inventory_categoryoffer" WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_categoryoffer" INNER JOIN "inventory_category" ON ("inventory_categoryoffer"."category_id" = "inventory_category"."id") WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 3) LIMIT 21; args=(3,); alias=default
(0.015) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 2) LIMIT 21; args=(2,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active" FROM "inventory_categoryoffer" WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_categoryoffer" INNER JOIN "inventory_category" ON ("inventory_categoryoffer"."category_id" = "inventory_category"."id") WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 2) LIMIT 21; args=(2,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 6) LIMIT 21; args=(6,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active" FROM "inventory_categoryoffer" WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_categoryoffer" INNER JOIN "inventory_category" ON ("inventory_categoryoffer"."category_id" = "inventory_category"."id") WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 6) LIMIT 21; args=(6,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 1) LIMIT 21; args=(1,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active" FROM "inventory_categoryoffer" WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.015) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_categoryoffer" INNER JOIN "inventory_category" ON ("inventory_categoryoffer"."category_id" = "inventory_category"."id") WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 1) LIMIT 21; args=(1,); alias=default

</code>```

I have created a class to check for offers because I had to reuse it different times.

```<code>from inventory.models import ProductOffer, CategoryOffer

class CheckOffer:
    def product_discount(self, obj):

        try:
            product_offer = ProductOffer.objects.select_related("product").get(product=obj, is_active=True)
            if product_offer:
                total_discount = product_offer.product_offer_discount()
                return total_discount
        except Exception:
            return None

    def category_discount(self, obj):

        try:
            category_offer = CategoryOffer.objects.select_related('category').get(category=obj.category, is_active=True)
            if category_offer:
                total_discount = category_offer.category_offer_discount(obj)
                return total_discount
        except Exception:
            return None

    def offer_checks(self, obj, product_offer=None, category_offer=None, final_price=0):

        try:
            product_offer = ProductOffer.objects.select_related("product").get(product=obj, is_active=True)
        except:
            pass
        try:
            category_offer = CategoryOffer.objects.get(category=obj.category, is_active=True)
        except:
            pass

        if category_offer and not product_offer:
            final_price = category_offer.category_offer_price(obj)
            return final_price

        elif not product_offer:
            return None

        elif product_offer and not category_offer:
            return product_offer.product_offer_price()

        elif product_offer and category_offer:
            if (
                product_offer.product_offer_discount()
                > category_offer.category_offer_discount(obj)
            ):
                return product_offer.product_offer_price()
            else:
                return category_offer.category_offer_price(obj)
        return None
</code>```

So I have two doubts here.

I dont know why the Accounts model is getting query here. You can see it on the first line of log statement. which is having no relationship with any of the above models I have mentioned

```<code>(0.000) SELECT "accounts_account"."id", "accounts_account"."password", "accounts_account"."first_name", "accounts_account"."last_name", "accounts_account"."email", "accounts_account"."date_joined", "accounts_account"."last_login", "accounts_account"."is_admin", "accounts_account"."is_staff", "accounts_account"."is_active" FROM "accounts_account" WHERE "accounts_account"."id" = 52 LIMIT 21; args=(52,); alias=default
</code>```

How can I reduce this much of queries. I know its because of the way I have implemented the code. I can't seem to find any other way.

Below are my serializer, models and views.

Models.py

```<code>class Category(models.Model):
    category_name = models.CharField(max_length=15, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    title = models.CharField(max_length=25)
    description = models.CharField(max_length=300)
    category_image = models.ImageField(upload_to="photos/category")

    class Meta:
        verbose_name_plural = "Category"

    def __str__(self):
        return self.category_name

class Products(models.Model):
    category = models.ForeignKey(
        Category, on_delete=models.CASCADE, related_name="products"
    )
    product_name = models.CharField(max_length=50, unique=True)
    sub_product_name = models.CharField(max_length=50, null=True, blank=True)
    sku = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    base_price = models.IntegerField()
    product_image = models.ImageField(
        upload_to="photos/products", null=True, blank=True
    )
    stock = models.IntegerField(validators=[MinValueValidator(0)])
    is_available = models.BooleanField(default=True)
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = "Products"

    def __str__(self):
        return self.product_name

    def save(self, *args, **kwargs):
        if self.stock < 1 and self.is_available == True:
            self.is_available = False
            super(Products, self).save(*args, **kwargs)
        elif self.stock > 0 and self.is_available == False:
            self.is_available = True
            super(Products, self).save(*args, **kwargs)
        else:
            super(Products, self).save(*args, **kwargs)

class CategoryOffer(models.Model):
    category = models.OneToOneField(
        Category, on_delete=models.CASCADE, related_name="category_offer"
    )
    valid_from = models.DateTimeField()
    valid_to = models.DateTimeField()
    discount = models.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(100)]
    )
    is_active = models.BooleanField(default=True)

    def __str__(self):

    def category_offer_discount(self, obj):
        return obj.base_price * self.discount / 100

class ProductOffer(models.Model):
    product = models.OneToOneField(
        Products, on_delete=models.CASCADE, related_name="product_offer"
    )
    valid_from = models.DateTimeField()
    valid_to = models.DateTimeField()
    discount = models.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(100)]
    )
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.product.product_name

    def product_offer_discount(self):
        return self.product.base_price * self.discount / 100

</code>```

#Views.py

```<code>class AllProducts(generics.ListAPIView):
    queryset = Products.objects.filter(is_available=True)
    serializer_class = ProductSerializer
</code>```

#Serializer.py

```<code>class ProductSerializer(ModelSerializer):
    product_offer_discount = SerializerMethodField()
    category_offer_discount = SerializerMethodField()
    highest_offer_price = SerializerMethodField()

    class Meta:
        model = Products
        fields = [
            "id",
            "product_name",
            "sub_product_name",
            "slug",
            "highest_offer_price",
            "category_offer_discount",
            "product_offer_discount",
            "base_price",
            "stock",
            "is_available",
            "product_image",
        ]

    def get_product_offer_discount(self, obj):
        self.product_offer_discount = CheckOffer.product_discount(self, obj)
        return self.product_offer_discount

    def get_category_offer_discount(self, obj):
        self.category_offer_discount = CheckOffer.category_discount(self, obj)
        return self.category_offer_discount

    def get_highest_offer_price(self, obj):
        self.highest_offer_price = CheckOffer.offer_checks(self, obj)
        return self.highest_offer_price

</code>```

Title: optmizing queries in django

Body:
Here I have four models Category, Products, ProductOffer and CategoryOffer. The CategoryOffer is Foreignkey to Category and ProductOffer is Foreignkey to Products. And while a product have an offer and the category having the product also have an offer. I'll compare both offers and shows whichever is higher. So far everything is working but when I looked on to how much queries is getting executed. It's a lot. It's shown below:

(0.000) SELECT "accounts_account"."id", "accounts_account"."password", "accounts_account"."first_name", "accounts_account"."last_name", "accounts_account"."email", "accounts_account"."date_joined", "accounts_account"."last_login", "accounts_account"."is_admin", "accounts_account"."is_staff", "accounts_account"."is_active" FROM "accounts_account" WHERE "accounts_account"."id" = 52 LIMIT 21; args=(52,); alias=default
(0.016) SELECT "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_products" INNER JOIN "inventory_category" ON ("inventory_products"."category_id" = "inventory_category"."id") WHERE "inventory_products"."is_available"; args=(); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 5) LIMIT 21; args=(5,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active" FROM "inventory_categoryoffer" WHERE ("inventory_categoryoffer"."category_id" = 4 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(4,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_categoryoffer" INNER JOIN "inventory_category" ON ("inventory_categoryoffer"."category_id" = "inventory_category"."id") WHERE ("inventory_categoryoffer"."category_id" = 4 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(4,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 5) LIMIT 21; args=(5,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 4) LIMIT 21; args=(4,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active" FROM "inventory_categoryoffer" WHERE ("inventory_categoryoffer"."category_id" = 4 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(4,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_categoryoffer" INNER JOIN "inventory_category" ON ("inventory_categoryoffer"."category_id" = "inventory_category"."id") WHERE ("inventory_categoryoffer"."category_id" = 4 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(4,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 4) LIMIT 21; args=(4,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 3) LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active" FROM "inventory_categoryoffer" WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_categoryoffer" INNER JOIN "inventory_category" ON ("inventory_categoryoffer"."category_id" = "inventory_category"."id") WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 3) LIMIT 21; args=(3,); alias=default
(0.015) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 2) LIMIT 21; args=(2,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active" FROM "inventory_categoryoffer" WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_categoryoffer" INNER JOIN "inventory_category" ON ("inventory_categoryoffer"."category_id" = "inventory_category"."id") WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 2) LIMIT 21; args=(2,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 6) LIMIT 21; args=(6,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active" FROM "inventory_categoryoffer" WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_categoryoffer" INNER JOIN "inventory_category" ON ("inventory_categoryoffer"."category_id" = "inventory_category"."id") WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 6) LIMIT 21; args=(6,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 1) LIMIT 21; args=(1,); alias=default
(0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active" FROM "inventory_categoryoffer" WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.015) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_categoryoffer" INNER JOIN "inventory_category" ON ("inventory_categoryoffer"."category_id" = "inventory_category"."id") WHERE ("inventory_categoryoffer"."category_id" = 3 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(3,); alias=default
(0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 1) LIMIT 21; args=(1,); alias=default

I have created a class to check for offers because I had to reuse it different times.

from inventory.models import ProductOffer, CategoryOffer

class CheckOffer:
    def product_discount(self, obj):

        try:
            product_offer = ProductOffer.objects.select_related("product").get(product=obj, is_active=True)
            if product_offer:
                total_discount = product_offer.product_offer_discount()
                return total_discount
        except Exception:
            return None

    def category_discount(self, obj):

        try:
            category_offer = CategoryOffer.objects.select_related('category').get(category=obj.category, is_active=True)
            if category_offer:
                total_discount = category_offer.category_offer_discount(obj)
                return total_discount
        except Exception:
            return None

    def offer_checks(self, obj, product_offer=None, category_offer=None, final_price=0):

        try:
            product_offer = ProductOffer.objects.select_related("product").get(product=obj, is_active=True)
        except:
            pass
        try:
            category_offer = CategoryOffer.objects.get(category=obj.category, is_active=True)
        except:
            pass

        if category_offer and not product_offer:
            final_price = category_offer.category_offer_price(obj)
            return final_price

        elif not product_offer:
            return None

        elif product_offer and not category_offer:
            return product_offer.product_offer_price()

        elif product_offer and category_offer:
            if (
                product_offer.product_offer_discount()
                > category_offer.category_offer_discount(obj)
            ):
                return product_offer.product_offer_price()
            else:
                return category_offer.category_offer_price(obj)
        return None

So I have two doubts here.

I dont know why the Accounts model is getting query here. You can see it on the first line of log statement. which is having no relationship with any of the above models I have mentioned

(0.000) SELECT "accounts_account"."id", "accounts_account"."password", "accounts_account"."first_name", "accounts_account"."last_name", "accounts_account"."email", "accounts_account"."date_joined", "accounts_account"."last_login", "accounts_account"."is_admin", "accounts_account"."is_staff", "accounts_account"."is_active" FROM "accounts_account" WHERE "accounts_account"."id" = 52 LIMIT 21; args=(52,); alias=default

How can I reduce this much of queries. I know its because of the way I have implemented the code. I can't seem to find any other way.

Below are my serializer, models and views.

Models.py

class Category(models.Model):
    category_name = models.CharField(max_length=15, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    title = models.CharField(max_length=25)
    description = models.CharField(max_length=300)
    category_image = models.ImageField(upload_to="photos/category")

    class Meta:
        verbose_name_plural = "Category"

    def __str__(self):
        return self.category_name

class Products(models.Model):
    category = models.ForeignKey(
        Category, on_delete=models.CASCADE, related_name="products"
    )
    product_name = models.CharField(max_length=50, unique=True)
    sub_product_name = models.CharField(max_length=50, null=True, blank=True)
    sku = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    base_price = models.IntegerField()
    product_image = models.ImageField(
        upload_to="photos/products", null=True, blank=True
    )
    stock = models.IntegerField(validators=[MinValueValidator(0)])
    is_available = models.BooleanField(default=True)
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = "Products"

    def __str__(self):
        return self.product_name

    def save(self, *args, **kwargs):
        if self.stock < 1 and self.is_available == True:
            self.is_available = False
            super(Products, self).save(*args, **kwargs)
        elif self.stock > 0 and self.is_available == False:
            self.is_available = True
            super(Products, self).save(*args, **kwargs)
        else:
            super(Products, self).save(*args, **kwargs)

class CategoryOffer(models.Model):
    category = models.OneToOneField(
        Category, on_delete=models.CASCADE, related_name="category_offer"
    )
    valid_from = models.DateTimeField()
    valid_to = models.DateTimeField()
    discount = models.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(100)]
    )
    is_active = models.BooleanField(default=True)

    def __str__(self):

    def category_offer_discount(self, obj):
        return obj.base_price * self.discount / 100

class ProductOffer(models.Model):
    product = models.OneToOneField(
        Products, on_delete=models.CASCADE, related_name="product_offer"
    )
    valid_from = models.DateTimeField()
    valid_to = models.DateTimeField()
    discount = models.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(100)]
    )
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.product.product_name

    def product_offer_discount(self):
        return self.product.base_price * self.discount / 100

#Views.py

class AllProducts(generics.ListAPIView):
    queryset = Products.objects.filter(is_available=True)
    serializer_class = ProductSerializer

#Serializer.py

class ProductSerializer(ModelSerializer):
    product_offer_discount = SerializerMethodField()
    category_offer_discount = SerializerMethodField()
    highest_offer_price = SerializerMethodField()

    class Meta:
        model = Products
        fields = [
            "id",
            "product_name",
            "sub_product_name",
            "slug",
            "highest_offer_price",
            "category_offer_discount",
            "product_offer_discount",
            "base_price",
            "stock",
            "is_available",
            "product_image",
        ]

    def get_product_offer_discount(self, obj):
        self.product_offer_discount = CheckOffer.product_discount(self, obj)
        return self.product_offer_discount

    def get_category_offer_discount(self, obj):
        self.category_offer_discount = CheckOffer.category_discount(self, obj)
        return self.category_offer_discount

    def get_highest_offer_price(self, obj):
        self.highest_offer_price = CheckOffer.offer_checks(self, obj)
        return self.highest_offer_price


问:
Applying GridSearch on Catboost Regressor with Categorical Variables
I have a Catboost regressor with some input features that are categorical. I've passed them to the model using code below.

```<code>cb = CatBoostRegressor(
                       iterations=400,
                       eval_metric='RMSE',
                       loss_function='RMSE',
                       learning_rate=0.05,
                        max_depth=16,
                       random_state=1,
                       verbose=False)

pool_train = Pool(X_train, y_train,
                  cat_features = ['A', 'B',
                                  'C', 'D'])

pool_test = Pool(X_test, cat_features = ['A', 'B',
                                  'C', 'D'])

cb.fit(pool_train)
y_pred = cb.predict(pool_test)
</code>```

The idea is to use Pool method to pass categorical features. However, I can't do he same using scikit learn Gridsearch method.

How can I pass pool_train to either catboost's grid search or scikit learn's gridsearch?

Body:
I have a Catboost regressor with some input features that are categorical. I've passed them to the model using code below.

cb = CatBoostRegressor(
                       iterations=400,
                       eval_metric='RMSE',
                       loss_function='RMSE',
                       learning_rate=0.05,
                        max_depth=16,
                       random_state=1,
                       verbose=False)

pool_train = Pool(X_train, y_train,
                  cat_features = ['A', 'B',
                                  'C', 'D'])

pool_test = Pool(X_test, cat_features = ['A', 'B',
                                  'C', 'D'])

cb.fit(pool_train)
y_pred = cb.predict(pool_test)

The idea is to use Pool method to pass categorical features. However, I can't do he same using scikit learn Gridsearch method.

How can I pass pool_train to either catboost's grid search or scikit learn's gridsearch?


问:
Display loading screen with current theme while React DOM is rendering
I am building a portfolio website and would like to implement a loading screen before each and every page get loaded or rendered in the browser. In my portfolio I have implemented a theme switcher( between light/dark) using react context api. I have tried to integrate a loading screen using this stack overflow thread as reference. But I couldn't find a way around from these solution to incorporate the current theme in to the loading component. I have tried building a custom loading screen and incorporate the theme in to it but for it requires the entire DOM of the home screen to be loaded and also tried using the useEffect hook, so that solution didn't work. Please Help me solve the issue or suggest a way around. Thank you!

Currently I have implemented it using a simple query selector to update the class of a div in index.html file(within the React app's public folder) dynamically. The code is provided bellow.

index.html

<!DOCTYPE html>

    You need to enable JavaScript to run this app.

        <svg class="svgLoader" viewBox="0 0 100 100" width="10em" height="10em">
          <path ng-attr-d="{{config.pathCmd}}" ng-attr-fill="{{config.color}}" stroke="none"
            d="M10 50A40 40 0 0 0 90 50A40 42 0 0 1 10 50" fill="#515390" transform="rotate(179.719 50 51)">
            <animateTransform attributeName="transform" type="rotate" calcMode="linear" values="0 50 51;360 50 51"
              keyTimes="0;1" dur="1s" begin="0s" repeatCount="indefinite"></animateTransform>
          </path>
        </svg>

```
<p>I have take the code for the loader animation for here. actually this method worked with the help of custom script for getting the current theme from the browser defaults. But the issue comes when the actual user is toggling between the themes when they are interacting with the website. When the user toggle it manually I am not able to incorporate that change in to the loading screen's theme, since it is hard coded in the <code>index.html</code> file. I am also sharing the context that I have created for toggling between the themes in my web app.</p>
<p><strong>Theme.js</strong></p>
<pre class="lang-js prettyprint-override"><code>import { createContext, useEffect, useState } from 'react'
import PropTypes from 'prop-types'

const ThemeContext = createContext()

function ThemeProvider({ children }) {
  const [themeName, setThemeName] = useState('light')

  useEffect(() => {
    const darkMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    setThemeName(darkMediaQuery.matches ? 'dark' : 'light')
    darkMediaQuery.addEventListener('change', (e) => {
      setThemeName(e.matches ? 'dark' : 'light')
    })
  }, [])

  const toggleTheme = () => {
    const name = themeName === 'dark' ? 'light' : 'dark'
    localStorage.setItem('themeName', name)
    setThemeName(name)
  }

  return (
    // eslint-disable-next-line react/jsx-no-constructed-context-values
    <ThemeContext.Provider value={[{ themeName, toggleTheme }]}>
      {children}
    </ThemeContext.Provider>
  )
}

ThemeProvider.propTypes = {
  children: PropTypes.node.isRequired,
}

export { ThemeProvider, ThemeContext }

</code>```

Body:
I am building a portfolio website and would like to implement a loading screen before each and every page get loaded or rendered in the browser. In my portfolio I have implemented a theme switcher( between light/dark) using react context api. I have tried to integrate a loading screen using this stack overflow thread as reference. But I couldn't find a way around from these solution to incorporate the current theme in to the loading component. I have tried building a custom loading screen and incorporate the theme in to it but for it requires the entire DOM of the home screen to be loaded and also tried using the useEffect hook, so that solution didn't work. Please Help me solve the issue or suggest a way around. Thank you!

Currently I have implemented it using a simple query selector to update the class of a div in index.html file(within the React app's public folder) dynamically. The code is provided bellow.

index.html

<!DOCTYPE html>

    You need to enable JavaScript to run this app.

        <svg class="svgLoader" viewBox="0 0 100 100" width="10em" height="10em">
          <path ng-attr-d="{{config.pathCmd}}" ng-attr-fill="{{config.color}}" stroke="none"
            d="M10 50A40 40 0 0 0 90 50A40 42 0 0 1 10 50" fill="#515390" transform="rotate(179.719 50 51)">
            <animateTransform attributeName="transform" type="rotate" calcMode="linear" values="0 50 51;360 50 51"
              keyTimes="0;1" dur="1s" begin="0s" repeatCount="indefinite"></animateTransform>
          </path>
        </svg>

I have take the code for the loader animation for here. actually this method worked with the help of custom script for getting the current theme from the browser defaults. But the issue comes when the actual user is toggling between the themes when they are interacting with the website. When the user toggle it manually I am not able to incorporate that change in to the loading screen's theme, since it is hard coded in the index.html file. I am also sharing the context that I have created for toggling between the themes in my web app.

Theme.js

import { createContext, useEffect, useState } from 'react'
import PropTypes from 'prop-types'

const ThemeContext = createContext()

function ThemeProvider({ children }) {
  const [themeName, setThemeName] = useState('light')

  useEffect(() => {
    const darkMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    setThemeName(darkMediaQuery.matches ? 'dark' : 'light')
    darkMediaQuery.addEventListener('change', (e) => {
      setThemeName(e.matches ? 'dark' : 'light')
    })
  }, [])

  const toggleTheme = () => {
    const name = themeName === 'dark' ? 'light' : 'dark'
    localStorage.setItem('themeName', name)
    setThemeName(name)
  }

  return (
    // eslint-disable-next-line react/jsx-no-constructed-context-values
    <ThemeContext.Provider value={[{ themeName, toggleTheme }]}>
      {children}
    </ThemeContext.Provider>
  )
}

ThemeProvider.propTypes = {
  children: PropTypes.node.isRequired,
}

export { ThemeProvider, ThemeContext }


问:
Is Jeddict compatible for Netbeans 16?
I am unable to install the Jeddict plugin on Netbeans 16.
I tried to install the jeddict plugin and a window with broken dependencies comes up. On the website it says minimum requirements as 15 but im not sure if 16 is compatible.

This isnt code related, I'm just trying to wonder if Jeddict is compatible with netbeans 16 or are my files corrupted

I tried to look up the related dependencies to install the dependencies but couldn't anything find them. I was expecting a clean installation

openjdk version "11.0.12" 2021-07-20
OpenJDK Runtime Environment Microsoft-25199 (build 11.0.12+7)
OpenJDK 64-Bit Server VM Microsoft-25199 (build 11.0.12+7, mixed mode)

Errors encountered while installing

Some plugins require plugin Database Core to be installed.
The plugin Database Core is requested in implementation version 15-387759c96ce1b891ec45ffaf524a53499455fe1a.

The following plugin is affected:       jeddict

Some plugins require plugin Maven Embedder to be installed.
The plugin Maven Embedder is requested in implementation version 15-387759c96ce1b891ec45ffaf524a53499455fe1a.

The following plugin is affected:       jeddict
Some plugins require plugin Maven Repository Indexing to be installed.
The plugin Maven Repository Indexing is requested in implementation version 15-387759c96ce1b891ec45ffaf524a53499455fe1a.

The following
plugin is affected:       jeddict
Some plugins require plugin Maven Editor Model to be installed.
The plugin Maven Editor Model is requested in implementation version 15-387759c96ce1b891ec45ffaf524a53499455fe1a.

The following plugin is affected:       jeddict
Some plugins require plugin User Utilities to be installed.
The plugin User Utilities is requested in implementation version 15-387759c96ce1b891ec45ffaf524a53499455fe1a.

The following plugin is affected:       jeddict  Some plugins not installed to avoid potential installation problems.

As a very last resort i will do a fresh installation of openjdk and other linked stuff

Title: Is Jeddict compatible for Netbeans 16?


问:
How to return more than one line from ssh config LocalCommand when doing LocalForward
I wish to do a local forward of port 8888:localhost:8888 so that I can ssh to my home network and get redirected to my main computer and run a jupyter notebook there.
For convenience I want to make it a ssh config and have the shortcut return the token for the notebook so that I can simply go there in my browser.

My config file is

```<code>Host mystuff
  HostName mystuff.duckdns.org
  User ivar
  Port xzyx
  SessionType none
  PermitLocalCommand yes
  LocalCommand jupyter notebook list
  LocalForward 8888 localhost:8888
</code>```

This opens the tunnel but only returns
"Currently running servers:"
which is the line preceeding the notebooks running and their respective tokens.

How can I modify my config so as to see all that is being printed?

I have tried things like adding a LocalCommand sleep(1) before LocalForward

Body:
I wish to do a local forward of port 8888:localhost:8888 so that I can ssh to my home network and get redirected to my main computer and run a jupyter notebook there.
For convenience I want to make it a ssh config and have the shortcut return the token for the notebook so that I can simply go there in my browser.

My config file is

Host mystuff
  HostName mystuff.duckdns.org
  User ivar
  Port xzyx
  SessionType none
  PermitLocalCommand yes
  LocalCommand jupyter notebook list
  LocalForward 8888 localhost:8888

This opens the tunnel but only returns
"Currently running servers:"
which is the line preceeding the notebooks running and their respective tokens.

How can I modify my config so as to see all that is being printed?

I have tried things like adding a LocalCommand sleep(1) before LocalForward


问:
Woocommerce subcategories not showing with Sage 10 starter theme
I am using Woocommerce (with generoi/sage-woocommerce solution) on my Sage 10 starter theme and noticed that the subcategories are showing in my local dev environment but not on my staging environment. I have done everything according to the generoi/sage-woocommerce instructions. I also noticed that the staging environment is reading only the woocommerce plugins files but not my custom (woocommerce/archive-product.blade.php) files that come with generoi/sage-woocommerce solution.

Here are things that I’ve tried:

Changed Customize > Woocommerce > Product catalogue “Shop page
display” to “Show categories” and “Category display” to “Show
subcategories”.

Added add_theme_support(“woocommerce”) in setup.php in that case
subcategories were visible but then my styles, header and footer were
not visible.

Disabled plugins - no results

Made sure that my staging env uses same the same configuration as local env (WP and PHP versions).

Made sure that subcategories have products

I deploy with FTP and use Acorn plugin on my Wordpress staging site. I’ve used the same deployment method before for other file changes and everything has worked nicely.

In local environment I use Local by Flywheel, Bedrock, Sage

Thanks!


问:
How can I style a toastify toast in the same js file, without using the styled toastcontainer?
in my app I use the ToastContainer component to display more than one type of toast. I do not want them both to have the same style, therefore I cannot use a styled ToastContainer to achieve what I want.

I know from the documentation for toastify that a toast can have it's own className for which you can specify the color etc. in a css file. But I want to have the css in the javascript file. But I have not yet found a way for it to work.

This is what I have come up with:

```<code>const notify = () => {
      toast(customMsg, {
        className: container,
        autoClose: false,
        closeOnClick: false,
        position: toast.POSITION.BOTTOM_RIGHT,
      });
  };

const container = {
  backgroundColor: 'yellow !important',
  color: ' black !important',
  borderRadius: '10px !important',
  border: '2px solid orange',
  width: '200px'
};
</code>```

This does not work, but if I change className to "container" and put the styling in a css file it works. Is there a way for the className to be specified in the javascript file?

Body:
in my app I use the ToastContainer component to display more than one type of toast. I do not want them both to have the same style, therefore I cannot use a styled ToastContainer to achieve what I want.

I know from the documentation for toastify that a toast can have it's own className for which you can specify the color etc. in a css file. But I want to have the css in the javascript file. But I have not yet found a way for it to work.

This is what I have come up with:

const notify = () => {
      toast(customMsg, {
        className: container,
        autoClose: false,
        closeOnClick: false,
        position: toast.POSITION.BOTTOM_RIGHT,
      });
  };

const container = {
  backgroundColor: 'yellow !important',
  color: ' black !important',
  borderRadius: '10px !important',
  border: '2px solid orange',
  width: '200px'
};

This does not work, but if I change className to "container" and put the styling in a css file it works. Is there a way for the className to be specified in the javascript file?


问:
Tabs with only CSS (specifically, vertical Tabs)
I am creating my personal version of Tabs using only a CSS solution, specifically a version in which Tabs are placed aside content, in a vertical solution, so I'd need to have Tabs on the left and content on the right.

My fisrt attempt was using "Absolute positioning", to place each full content on the right side, mantaining tabs on the left. This solution runs correcly playing with opacity value of each one, as you can see in the linked example.

But... it's have a limit... Due to absolute positioning I have to "force" an height of the entire Tabs container with overflow-y:auto; rule applied to longest content. In this way, there will always be a content that will make scrollable Tabs container and not the entire page.

In an attempt to supersede these limitations, i found a possible solution using Grid layout applied to inner content, that is "animatable to auto" (please see reference here at the end of article). The specific code of the example was:

```<code>.content {
  display: grid;
  grid-template-rows: 0fr;
  transition: 1s;
  overflow: hidden;
}
.content .inside {
  min-height: 0;
}
.content.expanded {
  grid-template-rows: 1fr;
}
</code>```

Applying it to my case, would result in this HTML:

```<code><div class="tabs-css vertical">
  <div class="tab-accordion-item">
    <input id="tab-accordion_hoqc_1" type="radio" name="tab-accordion" checked="">
    <label for="tab-accordion_hoqc_1"> Intestazione Tab 1 </label>
    <div class="item-content">
      <div class="item-content-inner">
        <div class="description">
          <p>...</p>
        </div>
      </div>
    </div>
  </div>
  <div class="tab-accordion-item">
    <input id="tab-accordion_hoqc_2" type="radio" name="tab-accordion">
    <label for="tab-accordion_hoqc_2">Questa è una intestazione di prova lunga</label>
    <div class="item-content">
      <div class="item-content-inner">
        <div class="description">
          <p>...</p>
        </div>
        <div></div>
      </div>
    </div>
  </div>
</div>
</code>```

and this sCSS:

```<code>.tabs-css
{
  display:flex;
  position:relative;
  height: 300px;

    > .tab-accordion-item
    {
        $label-height:45px;

        > label
        {
          display:block;
          background: gray;
          color: white;
        }

        > .item-content
        {
          overflow-y:auto;
          position:absolute;
          z-index:1;
          top:3px;
          left:0;
          height:calc(100% - $label-height + 3px);     // Container height - Label height + Container padding-top
          width:100%;
          opacity:0;

          .item-content-inner {
            min-height: 0;
          }
        }

        > input[type=radio]
        {
            display:none;

            &:checked
            {
                + label
                {
                  z-index:2;
                  background: red;

                    + .item-content
                    {
                      opacity:1;
                      z-index:3;
                    }
                }
            }
        }
    }

    &.vertical {
        flex-direction: column;

        > .tab-accordion-item
        {
            > label
            {
                max-width: 400px;
                padding: 10px 16px;
                height: auto;
                line-height: inherit;
                white-space: normal;
            }

            > .item-content {
                top: 0;
                bottom: 0;
                left: 450px;
                width: auto;
                height: auto;
            }
        }
    }
}
</code>```

But, renouncing to absolute positioning I'm not able to replicate side Tabs layout.

I could add:

```<code>.tab-accordion-item {
  display: flex;
}
</code>```

That "seems" similar to what I'd need, placing side-by-side Tab and relative content, but the behaviour si more similar to an Accordion, instead of a Tab...

Body:
I am creating my personal version of Tabs using only a CSS solution, specifically a version in which Tabs are placed aside content, in a vertical solution, so I'd need to have Tabs on the left and content on the right.

My fisrt attempt was using "Absolute positioning", to place each full content on the right side, mantaining tabs on the left. This solution runs correcly playing with opacity value of each one, as you can see in the linked example.

But... it's have a limit... Due to absolute positioning I have to "force" an height of the entire Tabs container with overflow-y:auto; rule applied to longest content. In this way, there will always be a content that will make scrollable Tabs container and not the entire page.

In an attempt to supersede these limitations, i found a possible solution using Grid layout applied to inner content, that is "animatable to auto" (please see reference here at the end of article). The specific code of the example was:

.content {
  display: grid;
  grid-template-rows: 0fr;
  transition: 1s;
  overflow: hidden;
}
.content .inside {
  min-height: 0;
}
.content.expanded {
  grid-template-rows: 1fr;
}

Applying it to my case, would result in this HTML:

    <input id="tab-accordion_hoqc_1" type="radio" name="tab-accordion" checked="">
     Intestazione Tab 1

...

    <input id="tab-accordion_hoqc_2" type="radio" name="tab-accordion">
    Questa è una intestazione di prova lunga

...

and this sCSS:

.tabs-css
{
  display:flex;
  position:relative;
  height: 300px;

    > .tab-accordion-item
    {
        $label-height:45px;

        > label
        {
          display:block;
          background: gray;
          color: white;
        }

        > .item-content
        {
          overflow-y:auto;
          position:absolute;
          z-index:1;
          top:3px;
          left:0;
          height:calc(100% - $label-height + 3px);     // Container height - Label height + Container padding-top
          width:100%;
          opacity:0;

          .item-content-inner {
            min-height: 0;
          }
        }

        > input[type=radio]
        {
            display:none;

            &:checked
            {
                + label
                {
                  z-index:2;
                  background: red;

                    + .item-content
                    {
                      opacity:1;
                      z-index:3;
                    }
                }
            }
        }
    }

    &.vertical {
        flex-direction: column;

        > .tab-accordion-item
        {
            > label
            {
                max-width: 400px;
                padding: 10px 16px;
                height: auto;
                line-height: inherit;
                white-space: normal;
            }

            > .item-content {
                top: 0;
                bottom: 0;
                left: 450px;
                width: auto;
                height: auto;
            }
        }
    }
}

But, renouncing to absolute positioning I'm not able to replicate side Tabs layout.

I could add:

.tab-accordion-item {
  display: flex;
}

That "seems" similar to what I'd need, placing side-by-side Tab and relative content, but the behaviour si more similar to an Accordion, instead of a Tab...


问:
Prisma error on create method - Argument name and Argument location is missing
I am creating the place then I keep getting the Prisma error yet I am providing all the required data. Every time I am creating the place I get this error yet I provided all the required data. I'm not getting where I could have possibly made the error I checked and checked again my code.

```<code>Invalid `this.prisma.place.create()` invocation in
C:\Users\charm\tourism-portal\src\place\place.service.ts:12:52

   9 constructor(private prisma: PrismaService) {}
  10
  11 async createTouristicPlace(adminId: number, dto: CreatePlaceDto) {
→ 12   const touristicPlace = await this.prisma.place.create({
         data: {
           admin: {
             connect: {
               id: 35
             }
           },
       +   name: String,
       +   location: String,
       ?   createdAt?: DateTime,
       ?   updatedAt?: DateTime
         }
       })

Argument name for data.name is missing.
Argument location for data.location is missing.
</code>```

here is my code:

```<code>import { Injectable } from '@nestjs/common';
import { CreatePlaceDto, EditPlaceDto } from './dto';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class TouristicPlaceService {
  constructor(private prisma: PrismaService) {}

  async createTouristicPlace(adminId: number, dto: CreatePlaceDto) {
    const touristicPlace = await this.prisma.place.create({
      data: {
        admin: {
          connect: { id: adminId },
        },
        ...dto,
      },
    });
    console.log(dto);
    return console.log(touristicPlace);
  }
</code>```

and here is my dto

```<code>import { IsNotEmpty, IsString } from 'class-validator';

export class CreatePlaceDto {
  @IsString()
  @IsNotEmpty()
  name: string;

  @IsString()
  @IsNotEmpty()
  location: string;
}
</code>```

and my db model

```<code>generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Admin {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  adminID   String  @unique
  email     String  @unique
  firstName String
  lastName  String
  hash      String
  Places    Place[]

  @@map("admins")
}

model Place {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  name     String
  location String

  adminId Int
  admin   Admin @relation(fields: [adminId], references: [id])

  @@map("places")
}
</code>```

I am trying to create a place endpoint but I kept getting a Prisma error which I'm not really getting I am new to Prisma and NestJs.

Body:
I am creating the place then I keep getting the Prisma error yet I am providing all the required data. Every time I am creating the place I get this error yet I provided all the required data. I'm not getting where I could have possibly made the error I checked and checked again my code.

Invalid `this.prisma.place.create()` invocation in
C:\Users\charm\tourism-portal\src\place\place.service.ts:12:52

   9 constructor(private prisma: PrismaService) {}
  10
  11 async createTouristicPlace(adminId: number, dto: CreatePlaceDto) {
→ 12   const touristicPlace = await this.prisma.place.create({
         data: {
           admin: {
             connect: {
               id: 35
             }
           },
       +   name: String,
       +   location: String,
       ?   createdAt?: DateTime,
       ?   updatedAt?: DateTime
         }
       })

Argument name for data.name is missing.
Argument location for data.location is missing.

here is my code:

import { Injectable } from '@nestjs/common';
import { CreatePlaceDto, EditPlaceDto } from './dto';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class TouristicPlaceService {
  constructor(private prisma: PrismaService) {}

  async createTouristicPlace(adminId: number, dto: CreatePlaceDto) {
    const touristicPlace = await this.prisma.place.create({
      data: {
        admin: {
          connect: { id: adminId },
        },
        ...dto,
      },
    });
    console.log(dto);
    return console.log(touristicPlace);
  }

and here is my dto

import { IsNotEmpty, IsString } from 'class-validator';

export class CreatePlaceDto {
  @IsString()
  @IsNotEmpty()
  name: string;

  @IsString()
  @IsNotEmpty()
  location: string;
}

and my db model

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Admin {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  adminID   String  @unique
  email     String  @unique
  firstName String
  lastName  String
  hash      String
  Places    Place[]

  @@map("admins")
}

model Place {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  name     String
  location String

  adminId Int
  admin   Admin @relation(fields: [adminId], references: [id])

  @@map("places")
}

I am trying to create a place endpoint but I kept getting a Prisma error which I'm not really getting I am new to Prisma and NestJs.


问:
error while doing a GO WASM project, not able to import syscall/js
```<code>Command 'gopls.go_get_package' failed: Error: err: exit status 1: stderr: package syscall/js: build constraints exclude all Go files in /usr/local/go/src/syscall/js .
</code>```

this is the message that comes in the dialogue box when I try to Import the package.
ill attach an image too

I tried installing the package separately and it didn't work. I searched online and it didn't work again

Body:
Command 'gopls.go_get_package' failed: Error: err: exit status 1: stderr: package syscall/js: build constraints exclude all Go files in /usr/local/go/src/syscall/js .

this is the message that comes in the dialogue box when I try to Import the package.
ill attach an image too

I tried installing the package separately and it didn't work. I searched online and it didn't work again