问:
How can I call data from a Model class which in List<Model> ? Flutter
Here I am face a issue , When I am trying to get data from api with Model class I can't find the model class object. When I am use object.first/last.object then I can Found the api data.
Like this....

please check this image

and Without first/last I don't get any class data :
here the issue:::

enter image description here

When I am remove  name from a model then I found the class object.

Please help me How can I solve the issue. Thanks Dear.

Here is the code SubCategoryPage.dart Code::::

```<code>import 'package:Darucheeni/src/models/categoryListModel.dart';
import 'package:Darucheeni/src/pages/childCategoryPage.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ionicons/ionicons.dart';
import '../configs/appColors.dart';
import '../configs/appConfigs.dart';
import '../widgets/customBackButton.dart';
import '../widgets/kText.dart';

class SubCategoryPage extends StatelessWidget {
  final int? id;
  final CategoryListModel categoryModel;

  SubCategoryPage({
    required this.id,
    required this.categoryModel,
  });

  @override
  Widget build(BuildContext context) {
    print(categoryModel.subcategories!.length);
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Row(
          children: [
            customBackButton(),
            SizedBox(width: 10),
            KText(
              text: 'All Sub Categories',
              fontSize: 20,
              color: black,
              fontFamily: segoeBoldFonts,
            ),
          ],
        ),
      ),
      body: ListView(
        children: [
          ListView.builder(
            itemCount: categoryModel.subcategories!.length,
            shrinkWrap: true,
            primary: false,
            itemBuilder: (context, index) {
              return ListTile(
                onTap: () => Get.to(ChildCategoryPage()),
                leading: Icon(Ionicons.list_outline),
                title: KText(
                  text: categoryModel.subcategories!.first.subcategoryName
                      .toString(),
                  color: black,
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}
</code>```

Here is Model Class Code :

```<code>class AllCategoryProductModel {
  Products? products;
  Category? category;
  List<Subcategories>? subcategories;

  AllCategoryProductModel({this.products, this.category, this.subcategories});

  AllCategoryProductModel.fromJson(Map<String, dynamic> json) {
    products = json['products'] != null
        ? new Products.fromJson(json['products'])
        : null;
    category = json['category'] != null
        ? new Category.fromJson(json['category'])
        : null;
    if (json['subcategories'] != null) {
      subcategories = <Subcategories>[];
      json['subcategories'].forEach((v) {
        subcategories!.add(new Subcategories.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.products != null) {
      data['products'] = this.products!.toJson();
    }
    if (this.category != null) {
      data['category'] = this.category!.toJson();
    }
    if (this.subcategories != null) {
      data['subcategories'] =
          this.subcategories!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Products {
  int? currentPage;
  List<Data>? data;
  String? firstPageUrl;
  int? from;
  int? lastPage;
  String? lastPageUrl;
  Null? nextPageUrl;
  String? path;
  int? perPage;
  Null? prevPageUrl;
  int? to;
  int? total;

  Products(
      {this.currentPage,
      this.data,
      this.firstPageUrl,
      this.from,
      this.lastPage,
      this.lastPageUrl,
      this.nextPageUrl,
      this.path,
      this.perPage,
      this.prevPageUrl,
      this.to,
      this.total});

  Products.fromJson(Map<String, dynamic> json) {
    currentPage = json['current_page'];
    if (json['data'] != null) {
      data = <Data>[];
      json['data'].forEach((v) {
        data!.add(new Data.fromJson(v));
      });
    }
    firstPageUrl = json['first_page_url'];
    from = json['from'];
    lastPage = json['last_page'];
    lastPageUrl = json['last_page_url'];
    nextPageUrl = json['next_page_url'];
    path = json['path'];
    perPage = json['per_page'];
    prevPageUrl = json['prev_page_url'];
    to = json['to'];
    total = json['total'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['current_page'] = this.currentPage;
    if (this.data != null) {
      data['data'] = this.data!.map((v) => v.toJson()).toList();
    }
    data['first_page_url'] = this.firstPageUrl;
    data['from'] = this.from;
    data['last_page'] = this.lastPage;
    data['last_page_url'] = this.lastPageUrl;
    data['next_page_url'] = this.nextPageUrl;
    data['path'] = this.path;
    data['per_page'] = this.perPage;
    data['prev_page_url'] = this.prevPageUrl;
    data['to'] = this.to;
    data['total'] = this.total;
    return data;
  }
}

class Data {
  int? id;
  String? proCategory;
  String? proSubcategory;
  String? proChildCategory;
  Null? proBrand;
  Null? proShop;
  String? proName;
  String? slug;
  String? proPurchaseprice;
  String? proOldprice;
  String? proNewprice;
  Null? proCode;
  Null? proLimit;
  String? proDescription;
  String? shortDescription;
  String? proQuantity;
  Null? aditionalshipping;
  Null? combo;
  Null? offer;
  Null? video;
  String? unit;
  Null? deliveryarea;
  Null? homedelivery;
  Null? returnwarranty;
  Null? codavailable;
  Null? warranty;
  String? proLocation;
  String? ratting;
  String? status;
  String? createdAt;
  String? updatedAt;
  String? reviewsCount;
  Image? image;

  Data(
      {this.id,
      this.proCategory,
      this.proSubcategory,
      this.proChildCategory,
      this.proBrand,
      this.proShop,
      this.proName,
      this.slug,
      this.proPurchaseprice,
      this.proOldprice,
      this.proNewprice,
      this.proCode,
      this.proLimit,
      this.proDescription,
      this.shortDescription,
      this.proQuantity,
      this.aditionalshipping,
      this.combo,
      this.offer,
      this.video,
      this.unit,
      this.deliveryarea,
      this.homedelivery,
      this.returnwarranty,
      this.codavailable,
      this.warranty,
      this.proLocation,
      this.ratting,
      this.status,
      this.createdAt,
      this.updatedAt,
      this.reviewsCount,
      this.image});

  Data.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    proCategory = json['proCategory'];
    proSubcategory = json['proSubcategory'];
    proChildCategory = json['proChildCategory'];
    proBrand = json['proBrand'];
    proShop = json['proShop'];
    proName = json['proName'];
    slug = json['slug'];
    proPurchaseprice = json['proPurchaseprice'];
    proOldprice = json['proOldprice'];
    proNewprice = json['proNewprice'];
    proCode = json['proCode'];
    proLimit = json['proLimit'];
    proDescription = json['proDescription'];
    shortDescription = json['shortDescription'];
    proQuantity = json['proQuantity'];
    aditionalshipping = json['aditionalshipping'];
    combo = json['combo'];
    offer = json['offer'];
    video = json['video'];
    unit = json['unit'];
    deliveryarea = json['deliveryarea'];
    homedelivery = json['homedelivery'];
    returnwarranty = json['returnwarranty'];
    codavailable = json['codavailable'];
    warranty = json['warranty'];
    proLocation = json['proLocation'];
    ratting = json['ratting'];
    status = json['status'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
    reviewsCount = json['reviews_count'];
    image = json['image'] != null ? new Image.fromJson(json['image']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['proCategory'] = this.proCategory;
    data['proSubcategory'] = this.proSubcategory;
    data['proChildCategory'] = this.proChildCategory;
    data['proBrand'] = this.proBrand;
    data['proShop'] = this.proShop;
    data['proName'] = this.proName;
    data['slug'] = this.slug;
    data['proPurchaseprice'] = this.proPurchaseprice;
    data['proOldprice'] = this.proOldprice;
    data['proNewprice'] = this.proNewprice;
    data['proCode'] = this.proCode;
    data['proLimit'] = this.proLimit;
    data['proDescription'] = this.proDescription;
    data['shortDescription'] = this.shortDescription;
    data['proQuantity'] = this.proQuantity;
    data['aditionalshipping'] = this.aditionalshipping;
    data['combo'] = this.combo;
    data['offer'] = this.offer;
    data['video'] = this.video;
    data['unit'] = this.unit;
    data['deliveryarea'] = this.deliveryarea;
    data['homedelivery'] = this.homedelivery;
    data['returnwarranty'] = this.returnwarranty;
    data['codavailable'] = this.codavailable;
    data['warranty'] = this.warranty;
    data['proLocation'] = this.proLocation;
    data['ratting'] = this.ratting;
    data['status'] = this.status;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    data['reviews_count'] = this.reviewsCount;
    if (this.image != null) {
      data['image'] = this.image!.toJson();
    }
    return data;
  }
}

class Image {
  String? image;
  String? productId;
  int? id;

  Image({this.image, this.productId, this.id});

  Image.fromJson(Map<String, dynamic> json) {
    image = json['image'];
    productId = json['product_id'];
    id = json['id'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['image'] = this.image;
    data['product_id'] = this.productId;
    data['id'] = this.id;
    return data;
  }
}

class Category {
  int? id;
  String? name;
  String? slug;
  String? image;
  String? frontProduct;
  Null? level;
  String? status;
  String? createdAt;
  String? updatedAt;

  Category(
      {this.id,
      this.name,
      this.slug,
      this.image,
      this.frontProduct,
      this.level,
      this.status,
      this.createdAt,
      this.updatedAt});

  Category.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    slug = json['slug'];
    image = json['image'];
    frontProduct = json['frontProduct'];
    level = json['level'];
    status = json['status'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['slug'] = this.slug;
    data['image'] = this.image;
    data['frontProduct'] = this.frontProduct;
    data['level'] = this.level;
    data['status'] = this.status;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    return data;
  }
}

class Subcategories {
  int? id;
  String? subcategoryName;
  String? slug;
  String? image;
  String? banner;
  String? categoryId;
  String? status;
  String? createdAt;
  String? updatedAt;
  List<Productcount>? productcount;

  Subcategories(
      {this.id,
      this.subcategoryName,
      this.slug,
      this.image,
      this.banner,
      this.categoryId,
      this.status,
      this.createdAt,
      this.updatedAt,
      this.productcount});

  Subcategories.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    subcategoryName = json['subcategoryName'];
    slug = json['slug'];
    image = json['image'];
    banner = json['banner'];
    categoryId = json['category_id'];
    status = json['status'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
    if (json['productcount'] != null) {
      productcount = <Productcount>[];
      json['productcount'].forEach((v) {
        productcount!.add(new Productcount.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['subcategoryName'] = this.subcategoryName;
    data['slug'] = this.slug;
    data['image'] = this.image;
    data['banner'] = this.banner;
    data['category_id'] = this.categoryId;
    data['status'] = this.status;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    if (this.productcount != null) {
      data['productcount'] = this.productcount!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Productcount {
  int? id;
  String? proCategory;
  String? proSubcategory;
  String? proChildCategory;
  Null? proBrand;
  Null? proShop;
  String? proName;
  String? slug;
  String? proPurchaseprice;
  String? proOldprice;
  String? proNewprice;
  Null? proCode;
  Null? proLimit;
  String? proDescription;
  String? shortDescription;
  String? proQuantity;
  Null? aditionalshipping;
  Null? combo;
  Null? offer;
  Null? video;
  String? unit;
  Null? deliveryarea;
  Null? homedelivery;
  Null? returnwarranty;
  Null? codavailable;
  Null? warranty;
  String? proLocation;
  String? ratting;
  String? status;
  String? createdAt;
  String? updatedAt;

  Productcount(
      {this.id,
      this.proCategory,
      this.proSubcategory,
      this.proChildCategory,
      this.proBrand,
      this.proShop,
      this.proName,
      this.slug,
      this.proPurchaseprice,
      this.proOldprice,
      this.proNewprice,
      this.proCode,
      this.proLimit,
      this.proDescription,
      this.shortDescription,
      this.proQuantity,
      this.aditionalshipping,
      this.combo,
      this.offer,
      this.video,
      this.unit,
      this.deliveryarea,
      this.homedelivery,
      this.returnwarranty,
      this.codavailable,
      this.warranty,
      this.proLocation,
      this.ratting,
      this.status,
      this.createdAt,
      this.updatedAt});

  Productcount.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    proCategory = json['proCategory'];
    proSubcategory = json['proSubcategory'];
    proChildCategory = json['proChildCategory'];
    proBrand = json['proBrand'];
    proShop = json['proShop'];
    proName = json['proName'];
    slug = json['slug'];
    proPurchaseprice = json['proPurchaseprice'];
    proOldprice = json['proOldprice'];
    proNewprice = json['proNewprice'];
    proCode = json['proCode'];
    proLimit = json['proLimit'];
    proDescription = json['proDescription'];
    shortDescription = json['shortDescription'];
    proQuantity = json['proQuantity'];
    aditionalshipping = json['aditionalshipping'];
    combo = json['combo'];
    offer = json['offer'];
    video = json['video'];
    unit = json['unit'];
    deliveryarea = json['deliveryarea'];
    homedelivery = json['homedelivery'];
    returnwarranty = json['returnwarranty'];
    codavailable = json['codavailable'];
    warranty = json['warranty'];
    proLocation = json['proLocation'];
    ratting = json['ratting'];
    status = json['status'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['proCategory'] = this.proCategory;
    data['proSubcategory'] = this.proSubcategory;
    data['proChildCategory'] = this.proChildCategory;
    data['proBrand'] = this.proBrand;
    data['proShop'] = this.proShop;
    data['proName'] = this.proName;
    data['slug'] = this.slug;
    data['proPurchaseprice'] = this.proPurchaseprice;
    data['proOldprice'] = this.proOldprice;
    data['proNewprice'] = this.proNewprice;
    data['proCode'] = this.proCode;
    data['proLimit'] = this.proLimit;
    data['proDescription'] = this.proDescription;
    data['shortDescription'] = this.shortDescription;
    data['proQuantity'] = this.proQuantity;
    data['aditionalshipping'] = this.aditionalshipping;
    data['combo'] = this.combo;
    data['offer'] = this.offer;
    data['video'] = this.video;
    data['unit'] = this.unit;
    data['deliveryarea'] = this.deliveryarea;
    data['homedelivery'] = this.homedelivery;
    data['returnwarranty'] = this.returnwarranty;
    data['codavailable'] = this.codavailable;
    data['warranty'] = this.warranty;
    data['proLocation'] = this.proLocation;
    data['ratting'] = this.ratting;
    data['status'] = this.status;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    return data;
  }
}
</code>```

答:
as you have created a list of subcategories   in AllCategoryProductModel

```<code> List<Subcategories>? subcategories;
</code>```

it's simple, use the index variable from the  itemBuilder in ListView.builder

```<code> itemBuilder: (context, index)
</code>```

to get the data variables inside the subcategories. ie :

```<code>subcategoryName=categoryModel.subcategories!.[index].subcategoryName.toString();
</code>```

full code, just replace your code with the code down below . hope you got it

```<code>import 'package:Darucheeni/src/models/categoryListModel.dart';
import 'package:Darucheeni/src/pages/childCategoryPage.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ionicons/ionicons.dart';
import '../configs/appColors.dart';
import '../configs/appConfigs.dart';
import '../widgets/customBackButton.dart';
import '../widgets/kText.dart';

class SubCategoryPage extends StatelessWidget {
  final int? id;
  final CategoryListModel categoryModel;

  SubCategoryPage({
    required this.id,
    required this.categoryModel,
  });

  @override
  Widget build(BuildContext context) {
    print(categoryModel.subcategories!.length);
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Row(
          children: [
            customBackButton(),
            SizedBox(width: 10),
            KText(
              text: 'All Sub Categories',
              fontSize: 20,
              color: black,
              fontFamily: segoeBoldFonts,
            ),
          ],
        ),
      ),
      body: ListView(
        children: [
          ListView.builder(
            itemCount: categoryModel.subcategories!.length,
            shrinkWrap: true,
            primary: false,
            itemBuilder: (context, index) {
              return ListTile(
                onTap: () => Get.to(ChildCategoryPage()),
                leading: Icon(Ionicons.list_outline),
                title: KText(
                  text: categoryModel.subcategories!.[index].subcategoryName
                      .toString(),
                  color: black,
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}
</code>```

Body:
Here I am face a issue , When I am trying to get data from api with Model class I can't find the model class object. When I am use object.first/last.object then I can Found the api data.
Like this....

please check this image

and Without first/last I don't get any class data :
here the issue:::

enter image description here

When I am remove  name from a model then I found the class object.

Please help me How can I solve the issue. Thanks Dear.

Here is the code SubCategoryPage.dart Code::::

import 'package:Darucheeni/src/models/categoryListModel.dart';
import 'package:Darucheeni/src/pages/childCategoryPage.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ionicons/ionicons.dart';
import '../configs/appColors.dart';
import '../configs/appConfigs.dart';
import '../widgets/customBackButton.dart';
import '../widgets/kText.dart';

class SubCategoryPage extends StatelessWidget {
  final int? id;
  final CategoryListModel categoryModel;

  SubCategoryPage({
    required this.id,
    required this.categoryModel,
  });

  @override
  Widget build(BuildContext context) {
    print(categoryModel.subcategories!.length);
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Row(
          children: [
            customBackButton(),
            SizedBox(width: 10),
            KText(
              text: 'All Sub Categories',
              fontSize: 20,
              color: black,
              fontFamily: segoeBoldFonts,
            ),
          ],
        ),
      ),
      body: ListView(
        children: [
          ListView.builder(
            itemCount: categoryModel.subcategories!.length,
            shrinkWrap: true,
            primary: false,
            itemBuilder: (context, index) {
              return ListTile(
                onTap: () => Get.to(ChildCategoryPage()),
                leading: Icon(Ionicons.list_outline),
                title: KText(
                  text: categoryModel.subcategories!.first.subcategoryName
                      .toString(),
                  color: black,
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}

Here is Model Class Code :

class AllCategoryProductModel {
  Products? products;
  Category? category;
  List<Subcategories>? subcategories;

  AllCategoryProductModel({this.products, this.category, this.subcategories});

  AllCategoryProductModel.fromJson(Map<String, dynamic> json) {
    products = json['products'] != null
        ? new Products.fromJson(json['products'])
        : null;
    category = json['category'] != null
        ? new Category.fromJson(json['category'])
        : null;
    if (json['subcategories'] != null) {
      subcategories = <Subcategories>[];
      json['subcategories'].forEach((v) {
        subcategories!.add(new Subcategories.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.products != null) {
      data['products'] = this.products!.toJson();
    }
    if (this.category != null) {
      data['category'] = this.category!.toJson();
    }
    if (this.subcategories != null) {
      data['subcategories'] =
          this.subcategories!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Products {
  int? currentPage;
  List<Data>? data;
  String? firstPageUrl;
  int? from;
  int? lastPage;
  String? lastPageUrl;
  Null? nextPageUrl;
  String? path;
  int? perPage;
  Null? prevPageUrl;
  int? to;
  int? total;

  Products(
      {this.currentPage,
      this.data,
      this.firstPageUrl,
      this.from,
      this.lastPage,
      this.lastPageUrl,
      this.nextPageUrl,
      this.path,
      this.perPage,
      this.prevPageUrl,
      this.to,
      this.total});

  Products.fromJson(Map<String, dynamic> json) {
    currentPage = json['current_page'];
    if (json['data'] != null) {
      data = <Data>[];
      json['data'].forEach((v) {
        data!.add(new Data.fromJson(v));
      });
    }
    firstPageUrl = json['first_page_url'];
    from = json['from'];
    lastPage = json['last_page'];
    lastPageUrl = json['last_page_url'];
    nextPageUrl = json['next_page_url'];
    path = json['path'];
    perPage = json['per_page'];
    prevPageUrl = json['prev_page_url'];
    to = json['to'];
    total = json['total'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['current_page'] = this.currentPage;
    if (this.data != null) {
      data['data'] = this.data!.map((v) => v.toJson()).toList();
    }
    data['first_page_url'] = this.firstPageUrl;
    data['from'] = this.from;
    data['last_page'] = this.lastPage;
    data['last_page_url'] = this.lastPageUrl;
    data['next_page_url'] = this.nextPageUrl;
    data['path'] = this.path;
    data['per_page'] = this.perPage;
    data['prev_page_url'] = this.prevPageUrl;
    data['to'] = this.to;
    data['total'] = this.total;
    return data;
  }
}

class Data {
  int? id;
  String? proCategory;
  String? proSubcategory;
  String? proChildCategory;
  Null? proBrand;
  Null? proShop;
  String? proName;
  String? slug;
  String? proPurchaseprice;
  String? proOldprice;
  String? proNewprice;
  Null? proCode;
  Null? proLimit;
  String? proDescription;
  String? shortDescription;
  String? proQuantity;
  Null? aditionalshipping;
  Null? combo;
  Null? offer;
  Null? video;
  String? unit;
  Null? deliveryarea;
  Null? homedelivery;
  Null? returnwarranty;
  Null? codavailable;
  Null? warranty;
  String? proLocation;
  String? ratting;
  String? status;
  String? createdAt;
  String? updatedAt;
  String? reviewsCount;
  Image? image;

  Data(
      {this.id,
      this.proCategory,
      this.proSubcategory,
      this.proChildCategory,
      this.proBrand,
      this.proShop,
      this.proName,
      this.slug,
      this.proPurchaseprice,
      this.proOldprice,
      this.proNewprice,
      this.proCode,
      this.proLimit,
      this.proDescription,
      this.shortDescription,
      this.proQuantity,
      this.aditionalshipping,
      this.combo,
      this.offer,
      this.video,
      this.unit,
      this.deliveryarea,
      this.homedelivery,
      this.returnwarranty,
      this.codavailable,
      this.warranty,
      this.proLocation,
      this.ratting,
      this.status,
      this.createdAt,
      this.updatedAt,
      this.reviewsCount,
      this.image});

  Data.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    proCategory = json['proCategory'];
    proSubcategory = json['proSubcategory'];
    proChildCategory = json['proChildCategory'];
    proBrand = json['proBrand'];
    proShop = json['proShop'];
    proName = json['proName'];
    slug = json['slug'];
    proPurchaseprice = json['proPurchaseprice'];
    proOldprice = json['proOldprice'];
    proNewprice = json['proNewprice'];
    proCode = json['proCode'];
    proLimit = json['proLimit'];
    proDescription = json['proDescription'];
    shortDescription = json['shortDescription'];
    proQuantity = json['proQuantity'];
    aditionalshipping = json['aditionalshipping'];
    combo = json['combo'];
    offer = json['offer'];
    video = json['video'];
    unit = json['unit'];
    deliveryarea = json['deliveryarea'];
    homedelivery = json['homedelivery'];
    returnwarranty = json['returnwarranty'];
    codavailable = json['codavailable'];
    warranty = json['warranty'];
    proLocation = json['proLocation'];
    ratting = json['ratting'];
    status = json['status'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
    reviewsCount = json['reviews_count'];
    image = json['image'] != null ? new Image.fromJson(json['image']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['proCategory'] = this.proCategory;
    data['proSubcategory'] = this.proSubcategory;
    data['proChildCategory'] = this.proChildCategory;
    data['proBrand'] = this.proBrand;
    data['proShop'] = this.proShop;
    data['proName'] = this.proName;
    data['slug'] = this.slug;
    data['proPurchaseprice'] = this.proPurchaseprice;
    data['proOldprice'] = this.proOldprice;
    data['proNewprice'] = this.proNewprice;
    data['proCode'] = this.proCode;
    data['proLimit'] = this.proLimit;
    data['proDescription'] = this.proDescription;
    data['shortDescription'] = this.shortDescription;
    data['proQuantity'] = this.proQuantity;
    data['aditionalshipping'] = this.aditionalshipping;
    data['combo'] = this.combo;
    data['offer'] = this.offer;
    data['video'] = this.video;
    data['unit'] = this.unit;
    data['deliveryarea'] = this.deliveryarea;
    data['homedelivery'] = this.homedelivery;
    data['returnwarranty'] = this.returnwarranty;
    data['codavailable'] = this.codavailable;
    data['warranty'] = this.warranty;
    data['proLocation'] = this.proLocation;
    data['ratting'] = this.ratting;
    data['status'] = this.status;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    data['reviews_count'] = this.reviewsCount;
    if (this.image != null) {
      data['image'] = this.image!.toJson();
    }
    return data;
  }
}

class Image {
  String? image;
  String? productId;
  int? id;

  Image({this.image, this.productId, this.id});

  Image.fromJson(Map<String, dynamic> json) {
    image = json['image'];
    productId = json['product_id'];
    id = json['id'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['image'] = this.image;
    data['product_id'] = this.productId;
    data['id'] = this.id;
    return data;
  }
}

class Category {
  int? id;
  String? name;
  String? slug;
  String? image;
  String? frontProduct;
  Null? level;
  String? status;
  String? createdAt;
  String? updatedAt;

  Category(
      {this.id,
      this.name,
      this.slug,
      this.image,
      this.frontProduct,
      this.level,
      this.status,
      this.createdAt,
      this.updatedAt});

  Category.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    slug = json['slug'];
    image = json['image'];
    frontProduct = json['frontProduct'];
    level = json['level'];
    status = json['status'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['slug'] = this.slug;
    data['image'] = this.image;
    data['frontProduct'] = this.frontProduct;
    data['level'] = this.level;
    data['status'] = this.status;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    return data;
  }
}

class Subcategories {
  int? id;
  String? subcategoryName;
  String? slug;
  String? image;
  String? banner;
  String? categoryId;
  String? status;
  String? createdAt;
  String? updatedAt;
  List<Productcount>? productcount;

  Subcategories(
      {this.id,
      this.subcategoryName,
      this.slug,
      this.image,
      this.banner,
      this.categoryId,
      this.status,
      this.createdAt,
      this.updatedAt,
      this.productcount});

  Subcategories.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    subcategoryName = json['subcategoryName'];
    slug = json['slug'];
    image = json['image'];
    banner = json['banner'];
    categoryId = json['category_id'];
    status = json['status'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
    if (json['productcount'] != null) {
      productcount = <Productcount>[];
      json['productcount'].forEach((v) {
        productcount!.add(new Productcount.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['subcategoryName'] = this.subcategoryName;
    data['slug'] = this.slug;
    data['image'] = this.image;
    data['banner'] = this.banner;
    data['category_id'] = this.categoryId;
    data['status'] = this.status;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    if (this.productcount != null) {
      data['productcount'] = this.productcount!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Productcount {
  int? id;
  String? proCategory;
  String? proSubcategory;
  String? proChildCategory;
  Null? proBrand;
  Null? proShop;
  String? proName;
  String? slug;
  String? proPurchaseprice;
  String? proOldprice;
  String? proNewprice;
  Null? proCode;
  Null? proLimit;
  String? proDescription;
  String? shortDescription;
  String? proQuantity;
  Null? aditionalshipping;
  Null? combo;
  Null? offer;
  Null? video;
  String? unit;
  Null? deliveryarea;
  Null? homedelivery;
  Null? returnwarranty;
  Null? codavailable;
  Null? warranty;
  String? proLocation;
  String? ratting;
  String? status;
  String? createdAt;
  String? updatedAt;

  Productcount(
      {this.id,
      this.proCategory,
      this.proSubcategory,
      this.proChildCategory,
      this.proBrand,
      this.proShop,
      this.proName,
      this.slug,
      this.proPurchaseprice,
      this.proOldprice,
      this.proNewprice,
      this.proCode,
      this.proLimit,
      this.proDescription,
      this.shortDescription,
      this.proQuantity,
      this.aditionalshipping,
      this.combo,
      this.offer,
      this.video,
      this.unit,
      this.deliveryarea,
      this.homedelivery,
      this.returnwarranty,
      this.codavailable,
      this.warranty,
      this.proLocation,
      this.ratting,
      this.status,
      this.createdAt,
      this.updatedAt});

  Productcount.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    proCategory = json['proCategory'];
    proSubcategory = json['proSubcategory'];
    proChildCategory = json['proChildCategory'];
    proBrand = json['proBrand'];
    proShop = json['proShop'];
    proName = json['proName'];
    slug = json['slug'];
    proPurchaseprice = json['proPurchaseprice'];
    proOldprice = json['proOldprice'];
    proNewprice = json['proNewprice'];
    proCode = json['proCode'];
    proLimit = json['proLimit'];
    proDescription = json['proDescription'];
    shortDescription = json['shortDescription'];
    proQuantity = json['proQuantity'];
    aditionalshipping = json['aditionalshipping'];
    combo = json['combo'];
    offer = json['offer'];
    video = json['video'];
    unit = json['unit'];
    deliveryarea = json['deliveryarea'];
    homedelivery = json['homedelivery'];
    returnwarranty = json['returnwarranty'];
    codavailable = json['codavailable'];
    warranty = json['warranty'];
    proLocation = json['proLocation'];
    ratting = json['ratting'];
    status = json['status'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['proCategory'] = this.proCategory;
    data['proSubcategory'] = this.proSubcategory;
    data['proChildCategory'] = this.proChildCategory;
    data['proBrand'] = this.proBrand;
    data['proShop'] = this.proShop;
    data['proName'] = this.proName;
    data['slug'] = this.slug;
    data['proPurchaseprice'] = this.proPurchaseprice;
    data['proOldprice'] = this.proOldprice;
    data['proNewprice'] = this.proNewprice;
    data['proCode'] = this.proCode;
    data['proLimit'] = this.proLimit;
    data['proDescription'] = this.proDescription;
    data['shortDescription'] = this.shortDescription;
    data['proQuantity'] = this.proQuantity;
    data['aditionalshipping'] = this.aditionalshipping;
    data['combo'] = this.combo;
    data['offer'] = this.offer;
    data['video'] = this.video;
    data['unit'] = this.unit;
    data['deliveryarea'] = this.deliveryarea;
    data['homedelivery'] = this.homedelivery;
    data['returnwarranty'] = this.returnwarranty;
    data['codavailable'] = this.codavailable;
    data['warranty'] = this.warranty;
    data['proLocation'] = this.proLocation;
    data['ratting'] = this.ratting;
    data['status'] = this.status;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    return data;
  }
}

Body:
as you have created a list of subcategories   in AllCategoryProductModel

 List<Subcategories>? subcategories;

it's simple, use the index variable from the  itemBuilder in ListView.builder

 itemBuilder: (context, index)

to get the data variables inside the subcategories. ie :

subcategoryName=categoryModel.subcategories!.[index].subcategoryName.toString();

full code, just replace your code with the code down below . hope you got it

import 'package:Darucheeni/src/models/categoryListModel.dart';
import 'package:Darucheeni/src/pages/childCategoryPage.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ionicons/ionicons.dart';
import '../configs/appColors.dart';
import '../configs/appConfigs.dart';
import '../widgets/customBackButton.dart';
import '../widgets/kText.dart';

class SubCategoryPage extends StatelessWidget {
  final int? id;
  final CategoryListModel categoryModel;

  SubCategoryPage({
    required this.id,
    required this.categoryModel,
  });

  @override
  Widget build(BuildContext context) {
    print(categoryModel.subcategories!.length);
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Row(
          children: [
            customBackButton(),
            SizedBox(width: 10),
            KText(
              text: 'All Sub Categories',
              fontSize: 20,
              color: black,
              fontFamily: segoeBoldFonts,
            ),
          ],
        ),
      ),
      body: ListView(
        children: [
          ListView.builder(
            itemCount: categoryModel.subcategories!.length,
            shrinkWrap: true,
            primary: false,
            itemBuilder: (context, index) {
              return ListTile(
                onTap: () => Get.to(ChildCategoryPage()),
                leading: Icon(Ionicons.list_outline),
                title: KText(
                  text: categoryModel.subcategories!.[index].subcategoryName
                      .toString(),
                  color: black,
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}


来源: stackexchange

问:
javascript date object :Error while using addDays function
I was trying to execute the below code in my javascript and got some exception

```<code> var now3 = new Date();
 now3.addDays(-4);
</code>```

Error throwed is
Microsoft JScript runtime error: Object doesn't support this property or method

I m using jQuery 1.3.2 in my page .

Whats wrong with this? Please help

答:
Well, you could add the addDays to the Date prototype:

```<code>Date.prototype.addDays = function(days) {
  this.setDate( this.getDate()  + days);
  return this;
};
</code>```

This should work fine.

ContentLicense: CC BY-SA 3.0

Body:
I was trying to execute the below code in my javascript and got some exception

 var now3 = new Date();
 now3.addDays(-4);

Error throwed is
Microsoft JScript runtime error: Object doesn't support this property or method

I m using jQuery 1.3.2 in my page .

Whats wrong with this? Please help

Body:
Well, you could add the addDays to the Date prototype:

Date.prototype.addDays = function(days) {
  this.setDate( this.getDate()  + days);
  return this;
};

This should work fine.


问:
type 'double' is not a subtype of type 'int' when decoding data from json + returns null
Every time the data has to be decoded it returns null and the exception type 'double' is not a subtype of type 'int'. The problem is the method attached below.

```<code>Future<void> fetchProducts() async {
    final url = Uri.parse(
        'https://recipier-e1139-default-rtdb.europe-west1.firebasedatabase.app/recipes.json');
    final response = await http.get(url);
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    print(extractedData['title']);
    if (extractedData.isEmpty || extractedData['error'] != null) {
      return;
    }
    List<Recipe> loadedRecipes = [];
    extractedData.forEach(
      (id, data) {
        loadedRecipes.add(
          Recipe(
            title: data['title'],
            description: data['description'],
            id: id,
            ingredients: data['ingredients'].cast<String>(),
            steps: data['steps'].cast<String>(),
            kcal: data['kcal'],
            p: data['p'],
            c: data['c'],
            f: data['f'],
            servings: data['servings'],
          ),
        );
      },
    );
    _recipes = loadedRecipes;
    notifyListeners();
  }
</code>```

Here is my recipe model

```<code>class Recipe with ChangeNotifier {
  String title;
  String id;
  String description;
  File? image;
  bool favorite;
  List<String> ingredients;
  List<String> steps;
  int servings;
  int kcal;
  int p;
  int c;
  int f;

  Recipe({
    required this.title,
    required this.description,
    this.favorite = false,
    required this.id,
    this.image,
    required this.ingredients,
    required this.steps,
    required this.c,
    required this.kcal,
    required this.f,
    required this.p,
    required this.servings,
  });
</code>```

I/flutter (31885): null E/flutter (31885):
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type
'double' is not a subtype of type 'int' E/flutter (31885): #0

RecipeProvider.fetchProducts.
package:recipier/providers/recipes_provider.dart:39 E/flutter (31885):
#1      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8) E/flutter (31885): #2
RecipeProvider.fetchProducts
package:recipier/providers/recipes_provider.dart:30 E/flutter (31885):

答:
One of the fields in your Recipe class is int but the json value for that corresponding field is returning a double.

You can solve it by finding the field and using .toInt()

Not sure which one of these is the int field but I'll use servings as an example.

```<code>            kcal: data['kcal'],
            p: data['p'],
            c: data['c'],
            f: data['f'],
            servings: data['servings'].toInt(),
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Every time the data has to be decoded it returns null and the exception type 'double' is not a subtype of type 'int'. The problem is the method attached below.

Future<void> fetchProducts() async {
    final url = Uri.parse(
        'https://recipier-e1139-default-rtdb.europe-west1.firebasedatabase.app/recipes.json');
    final response = await http.get(url);
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    print(extractedData['title']);
    if (extractedData.isEmpty || extractedData['error'] != null) {
      return;
    }
    List<Recipe> loadedRecipes = [];
    extractedData.forEach(
      (id, data) {
        loadedRecipes.add(
          Recipe(
            title: data['title'],
            description: data['description'],
            id: id,
            ingredients: data['ingredients'].cast<String>(),
            steps: data['steps'].cast<String>(),
            kcal: data['kcal'],
            p: data['p'],
            c: data['c'],
            f: data['f'],
            servings: data['servings'],
          ),
        );
      },
    );
    _recipes = loadedRecipes;
    notifyListeners();
  }

Here is my recipe model

class Recipe with ChangeNotifier {
  String title;
  String id;
  String description;
  File? image;
  bool favorite;
  List<String> ingredients;
  List<String> steps;
  int servings;
  int kcal;
  int p;
  int c;
  int f;

  Recipe({
    required this.title,
    required this.description,
    this.favorite = false,
    required this.id,
    this.image,
    required this.ingredients,
    required this.steps,
    required this.c,
    required this.kcal,
    required this.f,
    required this.p,
    required this.servings,
  });

I/flutter (31885): null E/flutter (31885):
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type
'double' is not a subtype of type 'int' E/flutter (31885): #0

RecipeProvider.fetchProducts.
package:recipier/providers/recipes_provider.dart:39 E/flutter (31885):
#1      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8) E/flutter (31885): #2
RecipeProvider.fetchProducts
package:recipier/providers/recipes_provider.dart:30 E/flutter (31885):

Body:
One of the fields in your Recipe class is int but the json value for that corresponding field is returning a double.

You can solve it by finding the field and using .toInt()

Not sure which one of these is the int field but I'll use servings as an example.

            kcal: data['kcal'],
            p: data['p'],
            c: data['c'],
            f: data['f'],
            servings: data['servings'].toInt(),


问:
Need guidance with sending files to a .NET WCF Web Service
Thank you all in advance for your assistance!

I am creating a .NET WCF web service (C#) for sending emails.. basically a central emailer service that all internal apps can use. my hurdle has been email attachments (1 or more)... I have been looking for the best practices for sending binary data to a WCF web service. The following needs to be considered:

all requests to this service will be internal

attachments are optional but may contain more than 1

for multiple attachments i need to ensure my service doesnt time out

I have read alot about converting binary to a base64 string but alot of the drawbacks with performance (especially with multiple files) scared me from accepting this approach. So i kept searching and found some MTOM topics which are supposed to be more efficient for binary file transfers.

Basically i need guidance on what approach is the best practice for this type of functionality and ideally some sample code to send me on my way.

Thanks again in advance for your time!

答:
quashBox,

I just went through this exercise just last week, the key is to stream the MTOM attachments, this seems to be the most efficient way of sending larger attachments. Here are a few resources that I just dug up and found to be extremely helpful...

MSDN - How to Enable Streaming
http://msdn.microsoft.com/en-us/library/ms789010.aspx

Transfer large messages in WCF blog
http://nagavitalp.blogspot.com/2011/04/transfer-large-messages-in-wcf-part-1.html

WCF Streaming: Upload files over HTTP
http://kjellsj.blogspot.com/2007/02/wcf-streaming-upload-files-over-http.html

A few high-level keys:

your message contracts need to have a single Stream body member, all other elements need to be placed in the message header, like (sorry for the VB.NET, but the shop I'm currently in uses it):

```<code><MessageContract()>
Public Class StreamAttachmentRequest

<MessageHeader(MustUnderstand:=True)>
Public Property AttachmentName As String

<MessageBodyMember(Order:=1)>
Public Property Attachment As Stream

End Class
</code>```

your binding has to be configured for streaming MTOM. like...

```<code>   <bindings>

    <basicHttpBinding>

    <binding name="TestCaseBasicBinding"

    messageEncoding="Mtom"

    transferMode="StreamedRequest"

    maxReceivedMessageSize="2147483647"

    closeTimeout="00:30:00"

    openTimeout="00:30:00"

    receiveTimeout="00:30:00"

    sendTimeout="00:30:00">
</code>```

you may have to set the max request length if you're transferring really large attachments

```<code> <httpRuntime executionTimeout="1800" maxRequestLength="2097151" />
</code>```

Good luck with it,
Patrick

Body:
quashBox,

I just went through this exercise just last week, the key is to stream the MTOM attachments, this seems to be the most efficient way of sending larger attachments. Here are a few resources that I just dug up and found to be extremely helpful...

MSDN - How to Enable Streaming
http://msdn.microsoft.com/en-us/library/ms789010.aspx

Transfer large messages in WCF blog
http://nagavitalp.blogspot.com/2011/04/transfer-large-messages-in-wcf-part-1.html

WCF Streaming: Upload files over HTTP
http://kjellsj.blogspot.com/2007/02/wcf-streaming-upload-files-over-http.html

A few high-level keys:

your message contracts need to have a single Stream body member, all other elements need to be placed in the message header, like (sorry for the VB.NET, but the shop I'm currently in uses it):

<MessageContract()>
Public Class StreamAttachmentRequest

<MessageHeader(MustUnderstand:=True)>
Public Property AttachmentName As String

<MessageBodyMember(Order:=1)>
Public Property Attachment As Stream

End Class

your binding has to be configured for streaming MTOM. like...

   <bindings>

    <basicHttpBinding>

    <binding name="TestCaseBasicBinding"

    messageEncoding="Mtom"

    transferMode="StreamedRequest"

    maxReceivedMessageSize="2147483647"

    closeTimeout="00:30:00"

    openTimeout="00:30:00"

    receiveTimeout="00:30:00"

    sendTimeout="00:30:00">

you may have to set the max request length if you're transferring really large attachments

 <httpRuntime executionTimeout="1800" maxRequestLength="2097151" />

Good luck with it,
Patrick


问:
Complete order based on specific order note in WooCommerce
I want to create a code snippet that completes a Woocommerce order based on a specific order note (“Budbee order status: Delivered”). I am using a hook to do this and I have some code but it doesn’t work. Can anyone please help me? PHP is not my “native” language, so I am not sure if and where I made mistakes.

Two main questions are:

Am I using the right hook woocommerce_new_customer_note?

Is my PHP code correct?

Below is the code:

```<code>add_action( 'woocommerce_new_customer_note', 'auto_complete_budbee_delivered' );

function auto_complete_budbee_delivered( $order_id, $customer_note ) {
    if ($customer_note == "Budbee order status: Delivered") {
        $order = wc_get_order( $order_id );
        $order->update_status( 'completed' );
    }
}
</code>```

Thanks a million!!

UPDATE

I think I choose the wrong hook (customer note, instead of order note). It might should be:

```<code>/**
         * Action hook fired after an order note is added.
         *
         * @param int      $order_note_id Order note ID.
         * @param WC_Order $order         Order data.
         *
         * @since 4.4.0
         */
        do_action( 'woocommerce_order_note_added', $comment_id, $this );

        return $comment_id;
</code>```

The problem here is that you only get the comment_id back, and not the message or the order_id. Any edea how it would work to obtain the order_id and content of the note? This is from the same doc that was shared by @LuicTheAztec. Is $this the object containing all the order info?

答:
For contain word

// order complete note contain strings

```<code> add_action( 'woocommerce_order_note_added', 'auto_complete_budbee_delivered', 10, 2 );
    function auto_complete_budbee_delivered( $comment_id, $order ) {
        $comment_obj   = get_comment( $comment_id );
        $customer_note = $comment_obj->comment_content;

        $word = "Order complete";
        $mystring = $customer_note;

        if (strpos($mystring, $word) !== false) {
            $order->update_status( 'completed' );
        }
    }
</code>```

Body:
I want to create a code snippet that completes a Woocommerce order based on a specific order note (“Budbee order status: Delivered”). I am using a hook to do this and I have some code but it doesn’t work. Can anyone please help me? PHP is not my “native” language, so I am not sure if and where I made mistakes.

Two main questions are:

Am I using the right hook woocommerce_new_customer_note?

Is my PHP code correct?

Below is the code:

add_action( 'woocommerce_new_customer_note', 'auto_complete_budbee_delivered' );

function auto_complete_budbee_delivered( $order_id, $customer_note ) {
    if ($customer_note == "Budbee order status: Delivered") {
        $order = wc_get_order( $order_id );
        $order->update_status( 'completed' );
    }
}

Thanks a million!!

UPDATE

I think I choose the wrong hook (customer note, instead of order note). It might should be:

/**
         * Action hook fired after an order note is added.
         *
         * @param int      $order_note_id Order note ID.
         * @param WC_Order $order         Order data.
         *
         * @since 4.4.0
         */
        do_action( 'woocommerce_order_note_added', $comment_id, $this );

        return $comment_id;

The problem here is that you only get the comment_id back, and not the message or the order_id. Any edea how it would work to obtain the order_id and content of the note? This is from the same doc that was shared by @LuicTheAztec. Is $this the object containing all the order info?

Body:
For contain word

// order complete note contain strings

 add_action( 'woocommerce_order_note_added', 'auto_complete_budbee_delivered', 10, 2 );
    function auto_complete_budbee_delivered( $comment_id, $order ) {
        $comment_obj   = get_comment( $comment_id );
        $customer_note = $comment_obj->comment_content;

        $word = "Order complete";
        $mystring = $customer_note;

        if (strpos($mystring, $word) !== false) {
            $order->update_status( 'completed' );
        }
    }


问:
How to convert multiple rows with same ID to single rows
I have a dataset1 which is as follows (table 1) :

```<code>structure(list(TCODE = c("T1", "T1", "T1", "T2", "T2", "T2",
"T2", "T2", "T3", "T4", "T4", "T4", "T4"), MATERIAL = c("M105",
"M100", "M102", "M345", "M400", "M100", "M220", "M260", "M400",
"M390", "M400", "M100", "M700")), class = "data.frame", row.names = c(NA,
-13L))

   TCODE MATERIAL
1     T1     M105
2     T1     M100
3     T1     M102
4     T2     M345
5     T2     M400
6     T2     M100
7     T2     M220
8     T2     M260
9     T3     M400
10    T4     M390
11    T4     M400
12    T4     M100
13    T4     M700
</code>```

How to convert multiple rows into a single row based on first column?
The desired output is : table 2

1     2       3       4       5

1   M105,   M100,   M102

2   M345,   M400,   M100,   M220,   M260

3   M400

4   M390,   M400,   M100,   M700

Thanks.

答:
You can do:

```<code>df <- structure(list(TCODE = c("T1", "T1", "T1", "T2", "T2", "T2",
"T2", "T2", "T3", "T4", "T4", "T4", "T4"), MATERIAL = c("M105",
"M100", "M102", "M345", "M400", "M100", "M220", "M260", "M400",
"M390", "M400", "M100", "M700")), class = "data.frame", row.names = c(NA,
-13L))

library(tidyverse)
df %>%
  group_by(TCODE) %>%
  summarize(MATERIAL= paste0(MATERIAL, collapse = ', '))

# A tibble: 4 x 2
  TCODE MATERIAL
  <chr> <chr>
1 T1    M105, M100, M102
2 T2    M345, M400, M100, M220, M260
3 T3    M400
4 T4    M390, M400, M100, M700
</code>```

If you want to have 5 columns, pivot_wider:

```<code>df %>%
  group_by(TCODE) %>%
  mutate(id = 1:n()) %>%
  ungroup() %>%
  pivot_wider(values_from = MATERIAL,
              names_from  = id,
              names_prefix = 'id_')

# A tibble: 4 x 6
  TCODE id_1  id_2  id_3  id_4  id_5
  <chr> <chr> <chr> <chr> <chr> <chr>
1 T1    M105  M100  M102  <NA>  <NA>
2 T2    M345  M400  M100  M220  M260
3 T3    M400  <NA>  <NA>  <NA>  <NA>
4 T4    M390  M400  M100  M700  <NA>
</code>```

Body:
I have a dataset1 which is as follows (table 1) :

structure(list(TCODE = c("T1", "T1", "T1", "T2", "T2", "T2",
"T2", "T2", "T3", "T4", "T4", "T4", "T4"), MATERIAL = c("M105",
"M100", "M102", "M345", "M400", "M100", "M220", "M260", "M400",
"M390", "M400", "M100", "M700")), class = "data.frame", row.names = c(NA,
-13L))

   TCODE MATERIAL
1     T1     M105
2     T1     M100
3     T1     M102
4     T2     M345
5     T2     M400
6     T2     M100
7     T2     M220
8     T2     M260
9     T3     M400
10    T4     M390
11    T4     M400
12    T4     M100
13    T4     M700

How to convert multiple rows into a single row based on first column?
The desired output is : table 2

1     2       3       4       5

1   M105,   M100,   M102

2   M345,   M400,   M100,   M220,   M260

3   M400

4   M390,   M400,   M100,   M700

Thanks.

Body:
You can do:

df <- structure(list(TCODE = c("T1", "T1", "T1", "T2", "T2", "T2",
"T2", "T2", "T3", "T4", "T4", "T4", "T4"), MATERIAL = c("M105",
"M100", "M102", "M345", "M400", "M100", "M220", "M260", "M400",
"M390", "M400", "M100", "M700")), class = "data.frame", row.names = c(NA,
-13L))

library(tidyverse)
df %>%
  group_by(TCODE) %>%
  summarize(MATERIAL= paste0(MATERIAL, collapse = ', '))

# A tibble: 4 x 2
  TCODE MATERIAL
  <chr> <chr>
1 T1    M105, M100, M102
2 T2    M345, M400, M100, M220, M260
3 T3    M400
4 T4    M390, M400, M100, M700

If you want to have 5 columns, pivot_wider:

df %>%
  group_by(TCODE) %>%
  mutate(id = 1:n()) %>%
  ungroup() %>%
  pivot_wider(values_from = MATERIAL,
              names_from  = id,
              names_prefix = 'id_')

# A tibble: 4 x 6
  TCODE id_1  id_2  id_3  id_4  id_5
  <chr> <chr> <chr> <chr> <chr> <chr>
1 T1    M105  M100  M102  <NA>  <NA>
2 T2    M345  M400  M100  M220  M260
3 T3    M400  <NA>  <NA>  <NA>  <NA>
4 T4    M390  M400  M100  M700  <NA>


问:
How do I make an awaitable blocking till a condition is true? (without using while loop)
How do I make it so that I am stuck awaiting something if the value of it isn't true?
for example :

await stuff() # Gets executed
await continueif(x, True) # This only returns when x is True
await morestuff() # Will get to this part when the above statement is executed, which only happens if the condition is true
...
```
<p>without using while loop</p>
<p>So, ideally</p>
<pre class="lang-py prettyprint-override"><code>x = True
continueif(x, True)
</code>```

Should immediately let us pass through
but,

x = False
continueif(x, True)
```

Should never let us pass through until or unless the value of x becomes True sometime during the execution of the program.

答:
I've created something around your code sample to create something minimally run-able. I've used asyncio.Queue, however if your requirement is for a single event asyncio.Event may be a better choice.

It's worth keeping in mind that asyncio is not multi-processing, rather there is one event loop that shares a single thread while some IO (typically) is blocking.

```<code>import asyncio
from time import perf_counter

async def make_true(myx: asyncio.Queue):
    await asyncio.sleep(1.0)
    await myx.put(False)
    await asyncio.sleep(1.0)
    await myx.put('hi')
    await asyncio.sleep(1.0)
    await myx.put(True)

async def stuff():
    print(f'{perf_counter()} doing stuff')

async def continueif(myx: asyncio.Queue, condition: bool):
    while True:
        msg = await myx.get()
        if msg == condition:
            print(f'{perf_counter()} {msg} is {condition}')
            break
        else:
            print(f'{perf_counter()} {msg} is not {condition}')

async def morestuff():
    print(f'{perf_counter()} doing more stuff')

async def main():
    x = asyncio.Queue()
    asyncio.create_task(make_true(x))
    await stuff()
    await continueif(x, True)
    await morestuff()

if __name__ == '__main__':
    asyncio.run(main())
</code>```

Output is:

```<code>249083.3551413 doing stuff
249084.3697383 False is not True
249085.3773555 hi is not True
249086.3854538 True is True
249086.385835 doing more stuff
</code>```

By the way, the while True is only required to parse multiple messages from the asyncio.Queue. If True is the only message the while True: can be omitted.

Body:
How do I make it so that I am stuck awaiting something if the value of it isn't true?
for example :

await stuff() # Gets executed
await continueif(x, True) # This only returns when x is True
await morestuff() # Will get to this part when the above statement is executed, which only happens if the condition is true
...

without using while loop

So, ideally

x = True
continueif(x, True)

Should immediately let us pass through
but,

x = False
continueif(x, True)

Should never let us pass through until or unless the value of x becomes True sometime during the execution of the program.

Body:
I've created something around your code sample to create something minimally run-able. I've used asyncio.Queue, however if your requirement is for a single event asyncio.Event may be a better choice.

It's worth keeping in mind that asyncio is not multi-processing, rather there is one event loop that shares a single thread while some IO (typically) is blocking.

import asyncio
from time import perf_counter

async def make_true(myx: asyncio.Queue):
    await asyncio.sleep(1.0)
    await myx.put(False)
    await asyncio.sleep(1.0)
    await myx.put('hi')
    await asyncio.sleep(1.0)
    await myx.put(True)

async def stuff():
    print(f'{perf_counter()} doing stuff')

async def continueif(myx: asyncio.Queue, condition: bool):
    while True:
        msg = await myx.get()
        if msg == condition:
            print(f'{perf_counter()} {msg} is {condition}')
            break
        else:
            print(f'{perf_counter()} {msg} is not {condition}')

async def morestuff():
    print(f'{perf_counter()} doing more stuff')

async def main():
    x = asyncio.Queue()
    asyncio.create_task(make_true(x))
    await stuff()
    await continueif(x, True)
    await morestuff()

if __name__ == '__main__':
    asyncio.run(main())

Output is:

249083.3551413 doing stuff
249084.3697383 False is not True
249085.3773555 hi is not True
249086.3854538 True is True
249086.385835 doing more stuff

By the way, the while True is only required to parse multiple messages from the asyncio.Queue. If True is the only message the while True: can be omitted.


问:
Import file problem when using python tools/test.py command
I want to import some functions using code

```<code>from mmdet.datasets.builder import (build_dataloader, build_dataset)
</code>```

the path mmdet.datasets.builder is under my project file, but when running the code, it seems the system import functions from lustre/home/acct-medcb/medcb-cb1/.conda/envs/Swin/lib/python3.7/site-packages/mmdet/datasets/builder.py,this is in my conda environment.

How can I modify my code to import functions right from the path I specified instead of using the same function from conda environment?

答:
You can use the sys.path to add the path that you want to import from:

```<code>import sys

sys.path.insert(1, '<your specified path>')
from builder import (build_dataloader, build_dataset)
</code>```

Body:
I want to import some functions using code

from mmdet.datasets.builder import (build_dataloader, build_dataset)

the path mmdet.datasets.builder is under my project file, but when running the code, it seems the system import functions from lustre/home/acct-medcb/medcb-cb1/.conda/envs/Swin/lib/python3.7/site-packages/mmdet/datasets/builder.py,this is in my conda environment.

How can I modify my code to import functions right from the path I specified instead of using the same function from conda environment?

Body:
You can use the sys.path to add the path that you want to import from:

import sys

sys.path.insert(1, '<your specified path>')
from builder import (build_dataloader, build_dataset)


问:
TypeError: expected bytes-like object, not str
I know this question has been asked much times, but please look once in my problem.

I am sending base64 image data from angular to python flask but when I am processing that base64 data on flask server(python3) then it is giving me the error

TypeError: expected bytes-like object, not str

My Javascript code is:

```<code>window['__CANVAS'].toDataURL("image/png");
</code>```

Output of the above line is:

```<code>"data:image/png;base64,iVBORw0KGgoAAAANSUhEUg....."
</code>```

I am receiving same data on flask server as string.

Code on python server that is using above base 64 data is:

```<code>def convert_to_image(base64_code):
  image_64_decode = base64.decodebytes(base64_code)
  image_result = open('baseimage.jpg', 'wb')
  image_result.write(image_64_decode)
  img_rgb = cv2.imread('baseimage.jpg')
  return img_rgb
</code>```

then it is giving the following error trace:

```<code>File "/home/shubham/py-projects/DX/Web/app/base64toimage.py", line 10, in convert_to_image
  image_64_decode = base64.decodebytes(base64_code)
File "/usr/lib/python3.5/base64.py", line 552, in decodebytes
  _input_type_check(s)
File "/usr/lib/python3.5/base64.py", line 521, in _input_type_check
  raise TypeError(msg) from err
TypeError: expected bytes-like object, not str
</code>```

above python function working fine if I am converting the image using this function

```<code>import base64

with open("t.png", "rb") as imageFile:
  str = base64.b64encode(imageFile.read())
  print str
</code>```

please help me to solve this question? I am new to python.

答:
Encoded bytes will do.</p>
```<code>bytes(base64_code, encoding='utf-8')
</code>```

Body:
I know this question has been asked much times, but please look once in my problem.

I am sending base64 image data from angular to python flask but when I am processing that base64 data on flask server(python3) then it is giving me the error

TypeError: expected bytes-like object, not str

My Javascript code is:

window['__CANVAS'].toDataURL("image/png");

Output of the above line is:

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUg....."

I am receiving same data on flask server as string.

Code on python server that is using above base 64 data is:

def convert_to_image(base64_code):
  image_64_decode = base64.decodebytes(base64_code)
  image_result = open('baseimage.jpg', 'wb')
  image_result.write(image_64_decode)
  img_rgb = cv2.imread('baseimage.jpg')
  return img_rgb

then it is giving the following error trace:

File "/home/shubham/py-projects/DX/Web/app/base64toimage.py", line 10, in convert_to_image
  image_64_decode = base64.decodebytes(base64_code)
File "/usr/lib/python3.5/base64.py", line 552, in decodebytes
  _input_type_check(s)
File "/usr/lib/python3.5/base64.py", line 521, in _input_type_check
  raise TypeError(msg) from err
TypeError: expected bytes-like object, not str

above python function working fine if I am converting the image using this function

import base64

with open("t.png", "rb") as imageFile:
  str = base64.b64encode(imageFile.read())
  print str

please help me to solve this question? I am new to python.

Body:
Encoded bytes will do.

bytes(base64_code, encoding='utf-8')


问:
Minimum replacements in a string to make all 'X' chars to the left of all 'Y chars
Hey everyone had this problem in an interview and can't seem to figure out the best way to do it. Any help would be much appreciated.

Problem:

You are given a string S. Each character of the string is either 'W' or 'R'.

W represents a white-colored flower.

R represents a red-colored flower

A string is considered beautiful if all the white-colored flowers are on the left of all the red-colored flowers. You can replace any white-colored flower with a red-colored flower and vice versa.

Your task is to find the minimum number of replacements that must be made to make string S beautiful.

sample cases:

1.) input: "RWRW"

output: 2 ("WWRR" or "WWWW" or “RRRR”)

2.) input: "RRRR"

output: 0 ("RRRR")

3.) input: "RWWWRR"

output: 1 ("WWWWRR")

答:
This can be solved in a single pass through the array keeping O(1) state.

We do this by finding the best place to split the array so that in the solution all the flowers to the left are white and all the flowers to the right are red. That's the same as finding i from 0 to N that minimizes the number of red flowers to the left of i plus the number of white flowers to the right of i, because that's the numbers of flowers we'd have to change to split the array at i.

Suppose the length of the array is N, there's R total red flowers (so N-R red flowers), and let r[i] be the number of red flowers to the left of i, r'[i] the number of red flowers to the right of i, and the same for white flowers with w[i] and w'[i].

We want to find i such that r[i] + w'[i] is minimized (the number of red flowers to the left of i plus the number of white flowers to the right of i -- these are the ones we'd have to change).
But w'[i] + w[i] = (N-R), and r[i] + w[i] = i, so r[i] + w'[i] = r[i] + (N-i)-(R-r[i]) = 2r[i] - i + (N - R).

Thus we need to find i that minimizes 2r[i] - i + (N - R). Since N-R is constant, that's the same as finding i such that 2r[i] - i is minimized. By the time we've processed the whole array, we have the value for R, and can construct the return value.

Here's some python code that uses this method, along with some test cases.

```<code>def min_changes(A):
    best, besti = 1e12, -1
    r = 0
    for i in range(len(A)+1):
        v = 2 * r - i
        if v < best:
            besti, best = i, v
        if i < len(A):
            r += A[i] == 'R'
    return best + len(A) - r, 'W' * besti + 'R' * (len(A) - besti)

tests = [("RWRW", 2, "RRRR"), ("RRRR", 0, "RRRR"), ("RWWWRR", 1, "WWWWRR")]
for s, n, r in tests:
    gotn, gotr = min_changes(s)
    if gotn != n or gotr != r:
        print("FAILED",)
    print(s, gotn, gotr)
</code>```

Body:
This can be solved in a single pass through the array keeping O(1) state.

We do this by finding the best place to split the array so that in the solution all the flowers to the left are white and all the flowers to the right are red. That's the same as finding i from 0 to N that minimizes the number of red flowers to the left of i plus the number of white flowers to the right of i, because that's the numbers of flowers we'd have to change to split the array at i.

Suppose the length of the array is N, there's R total red flowers (so N-R red flowers), and let r[i] be the number of red flowers to the left of i, r'[i] the number of red flowers to the right of i, and the same for white flowers with w[i] and w'[i].

We want to find i such that r[i] + w'[i] is minimized (the number of red flowers to the left of i plus the number of white flowers to the right of i -- these are the ones we'd have to change).
But w'[i] + w[i] = (N-R), and r[i] + w[i] = i, so r[i] + w'[i] = r[i] + (N-i)-(R-r[i]) = 2r[i] - i + (N - R).

Thus we need to find i that minimizes 2r[i] - i + (N - R). Since N-R is constant, that's the same as finding i such that 2r[i] - i is minimized. By the time we've processed the whole array, we have the value for R, and can construct the return value.

Here's some python code that uses this method, along with some test cases.

def min_changes(A):
    best, besti = 1e12, -1
    r = 0
    for i in range(len(A)+1):
        v = 2 * r - i
        if v < best:
            besti, best = i, v
        if i < len(A):
            r += A[i] == 'R'
    return best + len(A) - r, 'W' * besti + 'R' * (len(A) - besti)

tests = [("RWRW", 2, "RRRR"), ("RRRR", 0, "RRRR"), ("RWWWRR", 1, "WWWWRR")]
for s, n, r in tests:
    gotn, gotr = min_changes(s)
    if gotn != n or gotr != r:
        print("FAILED",)
    print(s, gotn, gotr)


答:
You could tackle this problem in 2 steps (and a last optional step):

Align the values in "date" column with the target value (the one in the next row)

Calculate the difference between both dates

(Optional) Convert the time delta to a relevant time unit (for example, minutes)

So, how could we do this?

For the first step, we'll shift the values using the pandas.Series.shift method.

```<code>df["date2"] = df["date"].shift(1)
</code>```

This will add a "date2" column with the values of the "date" column shifted by adding an empty value at the top. To fill this space, we'll use the first value again (you requested the first value to be zero and we'll use difference next so...)

```<code>df.loc[0, "date2"] = df.loc[0, "date"]
</code>```

For the second step, we'll just take the difference between our columns. Because both "date" and "date2" are datetime64[ns] columns, we are able to perform this operation:

```<code>df["diff"] = df["date"] - df["date2"]
</code>```

This is how your DataFrame first 5 rows looks now:

```<code>                 date  id               date2            diff
0 2015-04-02 02:34:00   1 2015-04-02 02:34:00 0 days 00:00:00
1 2015-04-06 12:34:00   2 2015-04-02 02:34:00 4 days 10:00:00
2 2015-04-09 23:03:00   3 2015-04-06 12:34:00 3 days 10:29:00
3 2015-04-12 01:00:00   4 2015-04-09 23:03:00 2 days 01:57:00
4 2015-04-15 07:12:00   5 2015-04-12 01:00:00 3 days 06:12:00
</code>```

Please consider that the "diff" column has timedelta64[ns] type. If you ant to transform this unit to minutes...

```<code>df["diff"].dt.total_seconds().div(60).astype(int)
</code>```

Same first 5 rows of your DataFrame with the last optional step:

```<code>                 date  id               date2  diff
0 2015-04-02 02:34:00   1 2015-04-02 02:34:00     0
1 2015-04-06 12:34:00   2 2015-04-02 02:34:00  6360
2 2015-04-09 23:03:00   3 2015-04-06 12:34:00  4949
3 2015-04-12 01:00:00   4 2015-04-09 23:03:00  2997
4 2015-04-15 07:12:00   5 2015-04-12 01:00:00  4692
</code>```

Title: Changing datetime to hour or minute difference using pandas

Body:
I have a dataframe that has a column in datetime type such as:

                date  id
0   02/04/2015 02:34   1
1   06/04/2015 12:34   2
2   09/04/2015 23:03   3
3   12/04/2015 01:00   4
4   15/04/2015 07:12   5
5   21/04/2015 12:59   6
6   29/04/2015 17:33   7
7   04/05/2015 10:44   8
8   06/05/2015 11:12   9
9   10/05/2015 08:52  10
10  12/05/2015 14:19  11
11  19/05/2015 19:22  12
12  27/05/2015 22:31  13
13  01/06/2015 11:09  14
14  04/06/2015 12:57  15
15  10/06/2015 04:00  16
16  15/06/2015 03:23  17
17  19/06/2015 05:37  18
18  23/06/2015 13:41  19
19  27/06/2015 15:43  20

I would like to change the date column reference such that
the first value 02/04/2015 02:34 will be 0, and the second one will be the difference between 06/04/2015 12:34 - 02/04/2015 02:34 = 6360 minutes or 106 Hours.

and so on. How can I change the column in pandas to something similar to the above explanation.

Thanks

Body:
You could tackle this problem in 2 steps (and a last optional step):

Align the values in "date" column with the target value (the one in the next row)

Calculate the difference between both dates

(Optional) Convert the time delta to a relevant time unit (for example, minutes)

So, how could we do this?

For the first step, we'll shift the values using the pandas.Series.shift method.

df["date2"] = df["date"].shift(1)

This will add a "date2" column with the values of the "date" column shifted by adding an empty value at the top. To fill this space, we'll use the first value again (you requested the first value to be zero and we'll use difference next so...)

df.loc[0, "date2"] = df.loc[0, "date"]

For the second step, we'll just take the difference between our columns. Because both "date" and "date2" are datetime64[ns] columns, we are able to perform this operation:

df["diff"] = df["date"] - df["date2"]

This is how your DataFrame first 5 rows looks now:

                 date  id               date2            diff
0 2015-04-02 02:34:00   1 2015-04-02 02:34:00 0 days 00:00:00
1 2015-04-06 12:34:00   2 2015-04-02 02:34:00 4 days 10:00:00
2 2015-04-09 23:03:00   3 2015-04-06 12:34:00 3 days 10:29:00
3 2015-04-12 01:00:00   4 2015-04-09 23:03:00 2 days 01:57:00
4 2015-04-15 07:12:00   5 2015-04-12 01:00:00 3 days 06:12:00

Please consider that the "diff" column has timedelta64[ns] type. If you ant to transform this unit to minutes...

df["diff"].dt.total_seconds().div(60).astype(int)

Same first 5 rows of your DataFrame with the last optional step:

                 date  id               date2  diff
0 2015-04-02 02:34:00   1 2015-04-02 02:34:00     0
1 2015-04-06 12:34:00   2 2015-04-02 02:34:00  6360
2 2015-04-09 23:03:00   3 2015-04-06 12:34:00  4949
3 2015-04-12 01:00:00   4 2015-04-09 23:03:00  2997
4 2015-04-15 07:12:00   5 2015-04-12 01:00:00  4692


问:
Django model field custom validator returned value not saved
I have the following implementation for the phone number custom validation. It does the validation correctly, but the returned value (formatted) is not saved in the model instance. I don't use a custom form and data is entered from admin panel.

custom validator

```<code>def phone_number_validator(value):
    if value:
        value = value.strip()
        value = value.replace(' ', '')

        digits = []
        non_digits = []
        for c in value:
            if c.isdigit():
                digits.append(c)
            else:
                non_digits.append(c)

        if len(non_digits):
            raise ValidationError('Only numbers and spaces are allowed for this field.')
        elif len(digits) < 10 or len(digits) > 10:
            raise ValidationError('Phone number should be exactly 10 digits.')
        elif (not value.startswith('07')) and (not value.startswith('0')):
            raise ValidationError('Invalid phone number.')

        if value.startswith('07'):  # mobile number
            value = f'{value[0:3]} {value[3:6]} {value[6:]}'
        elif value.startswith('0'):  # landline
            value = f'{value[0:3]} {value[3:4]} {value[4:7]} {value[7:]}'
        print(value) #### here the correct format is displayed
        return value
</code>```

models.py

```<code>hotline = models.CharField(max_length=PHONE_NUMBER_LENGTH, validators=[phone_number_validator])
</code>```

答:
This was already answered here (and from the docs).

If you want to use a validate_or_process-function, i have an approach in my own question

Body:
I have the following implementation for the phone number custom validation. It does the validation correctly, but the returned value (formatted) is not saved in the model instance. I don't use a custom form and data is entered from admin panel.

custom validator

def phone_number_validator(value):
    if value:
        value = value.strip()
        value = value.replace(' ', '')

        digits = []
        non_digits = []
        for c in value:
            if c.isdigit():
                digits.append(c)
            else:
                non_digits.append(c)

        if len(non_digits):
            raise ValidationError('Only numbers and spaces are allowed for this field.')
        elif len(digits) < 10 or len(digits) > 10:
            raise ValidationError('Phone number should be exactly 10 digits.')
        elif (not value.startswith('07')) and (not value.startswith('0')):
            raise ValidationError('Invalid phone number.')

        if value.startswith('07'):  # mobile number
            value = f'{value[0:3]} {value[3:6]} {value[6:]}'
        elif value.startswith('0'):  # landline
            value = f'{value[0:3]} {value[3:4]} {value[4:7]} {value[7:]}'
        print(value) #### here the correct format is displayed
        return value

models.py

hotline = models.CharField(max_length=PHONE_NUMBER_LENGTH, validators=[phone_number_validator])


问:
Show as Html on vuejs
i have json file for translate ( en.json ) and this line :

```<code>{
  "cancel order": "Hi, How can i <b> Cancel </b> ?",
}

      <div class="d-flex align-items-center justify-content-center align-content-center mb-4">
    <span class="description col-sm-11 col-md-7 col-lg-10">

    {{ $t('cancel order') }}

    </span>
  </div>
</code>```

now my result is  " Hi, How can i  Cancel  "

The problem is that the html code does not apply like this  code and the tags are displayed exactly without being applied.

答:
One observation : Using camelCase in property names consider as a best practice. Hence, use cancel order instead of cancel order.

To render your translation as an HTML message and not a static string. You can use v-html.

Template :

```<code><span class="description col-sm-11 col-md-7 col-lg-10" v-html="$t('cancelOrder')"></span>
</code>```

Title: Show as Html on vuejs

Body:
i have json file for translate ( en.json ) and this line :

{
  "cancel order": "Hi, How can i  Cancel  ?",
}

    {{ $t('cancel order') }}

now my result is  " Hi, How can i  Cancel  "

The problem is that the html code does not apply like this  code and the tags are displayed exactly without being applied.

Body:
One observation : Using camelCase in property names consider as a best practice. Hence, use cancel order instead of cancel order.

To render your translation as an HTML message and not a static string. You can use v-html.

Template :

<span class="description col-sm-11 col-md-7 col-lg-10" v-html="$t('cancelOrder')"></span>


问:
Add filled circles (markers) at SwiftUI path points
I'm trying to draw a line with markers at each point by using a Shape view in SwiftUI. I want the line to have a filled circle at each CGPoint on the line. The closest to this that I've gotten is by adding an arc at each point. Instead of using the arc, how can I add a Circle() shape at each point? I'm open to other approaches to accomplish this. My only requirements are to use SwiftUI and have the ability to interact with the markers.

import SwiftUI

struct LineShape: Shape {

    let values: [Double]

    func path(in rect: CGRect) -> Path {
        let xStep = rect.width / CGFloat(values.count - 1)

        var path = Path()
        path.move(to: CGPoint(x: 0.0, y: (1 - values[0]) * Double(rect.height)))

        for i in 1..<values.count {
            let pt = CGPoint(x: Double(i) * Double(xStep), y: (1 - values[i]) * Double(rect.height))
            path.addLine(to: pt)
            path.addArc(center: pt, radius: 8, startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 360), clockwise: false)
        }

        return path
    }
}

struct ContentView: View {
    var body: some View {
        LineShape(values: [0.2, 0.4, 0.3, 0.8, 0.5])
            .stroke(.red, lineWidth: 2.0)
            .padding()
            .frame(width: 400, height: 300)
    }
}
```

答:
You can make two different shapes, one for the line and one for the markers, and overlay them. Then you can also control their coloring individually:

```<code>struct LineShape: Shape {

    let values: [Double]

    func path(in rect: CGRect) -> Path {
        let xStep = rect.width / CGFloat(values.count - 1)

        var path = Path()
        path.move(to: CGPoint(x: 0.0, y: (1 - values[0]) * Double(rect.height)))

        for i in 1..<values.count {
            let pt = CGPoint(x: Double(i) * Double(xStep), y: (1 - values[i]) * Double(rect.height))
            path.addLine(to: pt)
        }

        return path
    }
}

struct MarkersShape: Shape {

    let values: [Double]

    func path(in rect: CGRect) -> Path {
        let xStep = rect.width / CGFloat(values.count - 1)

        var path = Path()

        for i in 1..<values.count {
            let pt = CGPoint(x: Double(i) * Double(xStep), y: (1 - values[i]) * Double(rect.height))
            path.addEllipse(in: CGRect(x: pt.x - 8, y: pt.y - 8, width: 16, height: 16))
        }

        return path
    }
}

struct ContentView: View {
    var body: some View {

        LineShape(values: [0.2, 0.4, 0.3, 0.8, 0.5])
            .stroke(.red, lineWidth: 2.0)
            .overlay(
                MarkersShape(values: [0.2, 0.4, 0.3, 0.8, 0.5])
                    .fill(.blue)
            )
            .frame(width: 350, height: 300)
    }
}
</code>```

Body:
You can make two different shapes, one for the line and one for the markers, and overlay them. Then you can also control their coloring individually:

struct LineShape: Shape {

    let values: [Double]

    func path(in rect: CGRect) -> Path {
        let xStep = rect.width / CGFloat(values.count - 1)

        var path = Path()
        path.move(to: CGPoint(x: 0.0, y: (1 - values[0]) * Double(rect.height)))

        for i in 1..<values.count {
            let pt = CGPoint(x: Double(i) * Double(xStep), y: (1 - values[i]) * Double(rect.height))
            path.addLine(to: pt)
        }

        return path
    }
}

struct MarkersShape: Shape {

    let values: [Double]

    func path(in rect: CGRect) -> Path {
        let xStep = rect.width / CGFloat(values.count - 1)

        var path = Path()

        for i in 1..<values.count {
            let pt = CGPoint(x: Double(i) * Double(xStep), y: (1 - values[i]) * Double(rect.height))
            path.addEllipse(in: CGRect(x: pt.x - 8, y: pt.y - 8, width: 16, height: 16))
        }

        return path
    }
}

struct ContentView: View {
    var body: some View {

        LineShape(values: [0.2, 0.4, 0.3, 0.8, 0.5])
            .stroke(.red, lineWidth: 2.0)
            .overlay(
                MarkersShape(values: [0.2, 0.4, 0.3, 0.8, 0.5])
                    .fill(.blue)
            )
            .frame(width: 350, height: 300)
    }
}


问:
If else in Jquery
i am a noob to jquery and i want to know how to make use of if else for the following:

on the server side there is a  if for number of rows is equal to 0 and else some JSON part.

```<code>$age= mysql_query("SELECT title FROM parent WHERE id ='$name'");
$age_num_rows = mysql_num_rows($age);
  if ($age_num_rows==0)
  {
   echo "true";
  }
  else
  {
$sql ="SELECT * FROM parentid WHERE id = '$name'"; //$name is value from html
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
     {
$abc_output = array('title' => $row['title'],'age' => $row['age']);
     }
echo json_encode($abc_output);
  }
</code>```

Now coming to Jquery part :

If the above PHP code go to if part then i want to display an alert box or if it goes to else part it needs to insert some values into the forms.
Here is something i tried but it did not work.

```<code>   $(document).ready(function(){
      $("#button1").click(function(){
        $.getJSON('script_1.php',function(data){
            if (data=='true') {
                 alert ('hello')
            }
            else {
                $.post('script_1.php',
                    { id: $('input[name="id"]', '#myForm').val() },
                    function(json) {
                        $("input[name='title']").val(json.title);
                        $("input[name='age']").val(json.age);
                    },
                    "json");
            }
      });
  });
</code>```

Edited:

```<code>  $(document).ready(function(){
$("#button1").click(function(){
    $.post(
        'script.php',
        { id: $('input[name="id"]', '#myForm').val() },
        function(json) {
            var data = JSON.parse(json);
            if (data.length === 0){
             alert('no data');
            }
            else{
            $("input[name='title']").val(json.title);
                    $("input[name='age']").val(json.age);

            }},
        "json"
    );
});
});
</code>```

PHP side

```<code>$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if ($row) {
$row=  array('title' => $row['title'],'age' => $row['age']);
echo json_encode($row);
} else {
echo json_encode(array());
}
</code>```

答:
You need to parse the JSON before you can use it like that. Modern browsers will have built in support for JSON.parse(yourJSON), but to account for those that don't, you should use Douglas Crockford's JavaScript JSON library. Including it will provide JSON.parse() if the browser doesn't have it already.

For the if-else stuff you're doing in the PHP, the common practice is to echo out an empty JSON object or array, so you don't have to test for things like no rows on the server side. You could do something as simple as this, later accounting for your database column names:

```<code>$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row) {
  echo json_encode($row);
} else {
  echo json_encode(array());
}
</code>```

Back in the JavaScript, you could then do something like this:

```<code>var data = JSON.parse(json);
if (data.length === 0) {
  alert('no data');
} else {
  $("input[name='title']").val(data.title);
  $("input[name='age']").val(data.age);
}
</code>```

jeroen is right though, you only need to use one AJAX call.

Title: If else in Jquery

Body:
i am a noob to jquery and i want to know how to make use of if else for the following:

on the server side there is a  if for number of rows is equal to 0 and else some JSON part.

$age= mysql_query("SELECT title FROM parent WHERE id ='$name'");
$age_num_rows = mysql_num_rows($age);
  if ($age_num_rows==0)
  {
   echo "true";
  }
  else
  {
$sql ="SELECT * FROM parentid WHERE id = '$name'"; //$name is value from html
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
     {
$abc_output = array('title' => $row['title'],'age' => $row['age']);
     }
echo json_encode($abc_output);
  }

Now coming to Jquery part :

If the above PHP code go to if part then i want to display an alert box or if it goes to else part it needs to insert some values into the forms.
Here is something i tried but it did not work.

   $(document).ready(function(){
      $("#button1").click(function(){
        $.getJSON('script_1.php',function(data){
            if (data=='true') {
                 alert ('hello')
            }
            else {
                $.post('script_1.php',
                    { id: $('input[name="id"]', '#myForm').val() },
                    function(json) {
                        $("input[name='title']").val(json.title);
                        $("input[name='age']").val(json.age);
                    },
                    "json");
            }
      });
  });

Edited:

  $(document).ready(function(){
$("#button1").click(function(){
    $.post(
        'script.php',
        { id: $('input[name="id"]', '#myForm').val() },
        function(json) {
            var data = JSON.parse(json);
            if (data.length === 0){
             alert('no data');
            }
            else{
            $("input[name='title']").val(json.title);
                    $("input[name='age']").val(json.age);

            }},
        "json"
    );
});
});

PHP side

$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if ($row) {
$row=  array('title' => $row['title'],'age' => $row['age']);
echo json_encode($row);
} else {
echo json_encode(array());
}

Body:
You need to parse the JSON before you can use it like that. Modern browsers will have built in support for JSON.parse(yourJSON), but to account for those that don't, you should use Douglas Crockford's JavaScript JSON library. Including it will provide JSON.parse() if the browser doesn't have it already.

For the if-else stuff you're doing in the PHP, the common practice is to echo out an empty JSON object or array, so you don't have to test for things like no rows on the server side. You could do something as simple as this, later accounting for your database column names:

$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row) {
  echo json_encode($row);
} else {
  echo json_encode(array());
}

Back in the JavaScript, you could then do something like this:

var data = JSON.parse(json);
if (data.length === 0) {
  alert('no data');
} else {
  $("input[name='title']").val(data.title);
  $("input[name='age']").val(data.age);
}

jeroen is right though, you only need to use one AJAX call.


问:
Filter DataFrame using within-group expression
Assuming I already have a predicate expression, how do I filter with that predicate, but apply it only within groups? For example, the predicate might be to keep all rows equal to the maximum or within a group. (There could be multiple rows kept in a group if there is a tie.)

With my dplyr experience, I thought that I could just .groupby and then .filter, but that does not work.

import polars as pl
df = pl.DataFrame(dict(x=[0, 0, 1, 1], y=[1, 2, 3, 3]))
expression = pl.col("y") == pl.col("y").max()

df.groupby("x").filter(expression)
# AttributeError: 'GroupBy' object has no attribute 'filter'
```
<p>I then thought I could apply <code>.over</code> to the expression, but that does not work either.</p>
<pre class="lang-py prettyprint-override"><code>import polars as pl
df = pl.DataFrame(dict(x=[0, 0, 1, 1], y=[1, 2, 3, 3]))
expression = pl.col("y") == pl.col("y").max()

df.filter(expression.over("x"))
# RuntimeError: Any(ComputeError("this binary expression is not an aggregation:
# [(col(\"y\")) == (col(\"y\").max())]
# pherhaps you should add an aggregation like, '.sum()', '.min()', '.mean()', etc.
# if you really want to collect this binary expression, use `.list()`"))
</code>```

For this particular problem, I can invoke .over on the max, but I don't know how to apply this to an arbitrary predicate I don't have control over.

import polars as pl
df = pl.DataFrame(dict(x=[0, 0, 1, 1], y=[1, 2, 3, 3]))
expression = pl.col("y") == pl.col("y").max().over("x")
df.filter(expression)
# shape: (3, 2)
# ┌─────┬─────┐
# │ x   ┆ y   │
# │ --- ┆ --- │
# │ i64 ┆ i64 │
# ╞═════╪═════╡
# │ 0   ┆ 2   │
# ├╌╌╌╌╌┼╌╌╌╌╌┤
# │ 1   ┆ 3   │
# ├╌╌╌╌╌┼╌╌╌╌╌┤
# │ 1   ┆ 3   │
# └─────┴─────┘
```

答:
If you had updated to polars>=0.13.0 your second try would have worked. :)

df = pl.DataFrame(dict(
    x=[0, 0, 1, 1],
    y=[1, 2, 3, 3])
)

df.filter((pl.col("y") == pl.max("y").over("x")))
```
```shape: (3, 2)
┌─────┬─────┐
│ x   ┆ y   │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 0   ┆ 2   │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 1   ┆ 3   │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 1   ┆ 3   │
└─────┴─────┘

```

Body:
Assuming I already have a predicate expression, how do I filter with that predicate, but apply it only within groups? For example, the predicate might be to keep all rows equal to the maximum or within a group. (There could be multiple rows kept in a group if there is a tie.)

With my dplyr experience, I thought that I could just .groupby and then .filter, but that does not work.

import polars as pl
df = pl.DataFrame(dict(x=[0, 0, 1, 1], y=[1, 2, 3, 3]))
expression = pl.col("y") == pl.col("y").max()

df.groupby("x").filter(expression)
# AttributeError: 'GroupBy' object has no attribute 'filter'

I then thought I could apply .over to the expression, but that does not work either.

import polars as pl
df = pl.DataFrame(dict(x=[0, 0, 1, 1], y=[1, 2, 3, 3]))
expression = pl.col("y") == pl.col("y").max()

df.filter(expression.over("x"))
# RuntimeError: Any(ComputeError("this binary expression is not an aggregation:
# [(col(\"y\")) == (col(\"y\").max())]
# pherhaps you should add an aggregation like, '.sum()', '.min()', '.mean()', etc.
# if you really want to collect this binary expression, use `.list()`"))

For this particular problem, I can invoke .over on the max, but I don't know how to apply this to an arbitrary predicate I don't have control over.

import polars as pl
df = pl.DataFrame(dict(x=[0, 0, 1, 1], y=[1, 2, 3, 3]))
expression = pl.col("y") == pl.col("y").max().over("x")
df.filter(expression)
# shape: (3, 2)
# ┌─────┬─────┐
# │ x   ┆ y   │
# │ --- ┆ --- │
# │ i64 ┆ i64 │
# ╞═════╪═════╡
# │ 0   ┆ 2   │
# ├╌╌╌╌╌┼╌╌╌╌╌┤
# │ 1   ┆ 3   │
# ├╌╌╌╌╌┼╌╌╌╌╌┤
# │ 1   ┆ 3   │
# └─────┴─────┘

Body:
If you had updated to polars>=0.13.0 your second try would have worked. :)

df = pl.DataFrame(dict(
    x=[0, 0, 1, 1],
    y=[1, 2, 3, 3])
)

df.filter((pl.col("y") == pl.max("y").over("x")))

shape: (3, 2)
┌─────┬─────┐
│ x   ┆ y   │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 0   ┆ 2   │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 1   ┆ 3   │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 1   ┆ 3   │
└─────┴─────┘