问:
Flutter assertion failed Error in ListView Builder
I'm Trying learn flutter and i'm a beginner.I'm trying to list down my shopping cart items in flutter application. Below is my shopping cart code and widget.but i'm getting below error when i tried to access the cart. can someone help me to resolve this issue.

```<code>import 'dart:html';

import 'package:distribution/Providers/ShoppingCartProvider.dart';
import 'package:distribution/models/ShoppingCart/CartItem.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../widgets/ShoppingCart/ShoppingCartItem.dart';

class ShoppingCartScreen extends StatelessWidget {
  static const routeName = '/shoppingcart';
  @override
  Widget build(BuildContext context) {
    final cart = Provider.of<ShoppingCartProvider>(context);

    return Scaffold(
        appBar: AppBar(
          title: const Text('Your Cart'),
        ),
        body: Column(
          children: <Widget>[
            Card(
                margin: const EdgeInsets.all(15),
                child: Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Row(
                      children: <Widget>[
                        const Text('Total', style: TextStyle(fontSize: 20)),
                        const Spacer(),
                        Chip(
                          label: Text(
                            '\$${cart.totalAmount}',
                          ),
                          backgroundColor: Theme.of(context).primaryColor,
                        ),
                        TextButton(
                          child: Text('ORDER NOW'),
                          onPressed: () {},

                        ),
                        const SizedBox(height: 10),
                        Expanded(
                          child: ListView.builder(
                            itemCount: cart.items.length,
                            itemBuilder: (ctx, i) => ShoppingCartItem(
                              cart.items.values.toList()[i].id,
                              cart.items.keys.toList()[i],
                              cart.items.values.toList()[i].price,
                              cart.items.values.toList()[i].quantity,
                              cart.items.values.toList()[i].title,
                            ),
                          ),
                        )
                      ],
                    ))),
          ],
        ));
  }
}
</code>```

this is the part giving me problem

```<code>                  Expanded(
                      child: ListView.builder(
                        itemCount: cart.items.length,
                        itemBuilder: (ctx, i) => ShoppingCartItem(
                          cart.items.values.toList()[i].id,
                          cart.items.keys.toList()[i],
                          cart.items.values.toList()[i].price,
                          cart.items.values.toList()[i].quantity,
                          cart.items.values.toList()[i].title,
                        ),
                      ),
</code>```

my shopping cart widget code

```<code>import 'package:distribution/Providers/ShoppingCartProvider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ShoppingCartItem extends StatelessWidget {
  final String id;
  final String productId;
  final double price;
  final int quantity;
  final String title;

   ShoppingCartItem(
    this.id,
    this.productId,
    this.price,
    this.quantity,
    this.title,
  );

  @override
  Widget build(BuildContext context) {
    return Card(
        margin: const EdgeInsets.symmetric(
          horizontal: 15,
          vertical: 4,
        ),
        child: Padding(
          padding:const EdgeInsets.all(8),
          child: ListTile(
            leading: CircleAvatar(
              child: Padding(
                padding:const EdgeInsets.all(5),
                child: FittedBox(
                  child: Text('\$$price'),
                ),
              ),
            ),
            title: Text(title),
            subtitle: Text('Total: '),
            trailing: Text('x'),
          ),
        ),
      );
  }
}
</code>```

Shopping cart provider

```<code>import 'package:distribution/models/ShoppingCart/CartItem.dart';
import 'package:flutter/foundation.dart';

class ShoppingCartProvider with ChangeNotifier {
  // ignore: prefer_final_fields
  Map<String, CartItem> _items = {};

  Map<String, CartItem> get items {
    return {..._items};
  }

  void addItem(
    String productID,
    double price,
    String title,
  ) {
    if (_items.containsKey(productID)) {
      _items.update(
          productID,
          (existingitem) => CartItem(
                id: existingitem.id,
                title: existingitem.title,
                quantity: existingitem.quantity + 1,
                price: existingitem.price,
              ));
    } else {
      _items.putIfAbsent(
          productID,
          () => CartItem(
                id: DateTime.now().toString(),
                title: title,
                price: price,
                quantity: 1,
              ));
    }

    notifyListeners();
  }

  int get itemCount {
    return _items == null ? 0 :_items.length;
  }

  double get totalAmount {
    var total = 0.0;
    _items.forEach((key, cartitem) {
      total += cartitem.price * cartitem.quantity ;
    });
    return total;
  }

  void removeItem(String productId) {
    _items.remove(productId);
    notifyListeners();
  }

}
</code>```

shopping cart model

```<code>import 'package:flutter/foundation.dart';

class CartItem {
  final String id;
  final String title;
  final int quantity;
  final double price;

  CartItem({
    @required this.id,
    @required this.title,
    @required this.quantity,
    @required this.price

  });
}
</code>```

Error I'm Getting

```<code>Error: Assertion failed: file:///Users/liyanaarachchi/flutter/packages/flutter/lib/src/rendering/box.dart:1927:12
hasSize
"RenderBox was not laid out: RenderPointerListener#60a6a NEEDS-LAYOUT NEEDS-PAINT"
    at Object.throw_ [as throw] (http://localhost:64556/dart_sdk.js:5386:11)
    at Object.assertFailed (http://localhost:64556/dart_sdk.js:5308:15)
    at proxy_box.RenderPointerListener.new.get size [as size] (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4406:42)
    at proxy_box.RenderPointerListener.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:545:26)
    at http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8537:44
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at custom_layout.RenderCustomMultiChildLayoutBox.new.defaultHitTestChildren (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8533:30)
    at custom_layout.RenderCustomMultiChildLayoutBox.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/custom_layout.dart.lib.js:304:19)
    at custom_layout.RenderCustomMultiChildLayoutBox.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at material._RenderInkFeatures.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at material._RenderInkFeatures.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderPhysicalModel.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderPhysicalModel.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderPhysicalModel.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:2343:20)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderRepaintBoundary.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderRepaintBoundary.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderIgnorePointer.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderIgnorePointer.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderIgnorePointer.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3794:59)
    at http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8537:44
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at stack.RenderStack.new.defaultHitTestChildren (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8533:30)
    at stack.RenderStack.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/stack.dart.lib.js:683:19)
    at stack.RenderStack.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderDecoratedBox.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderDecoratedBox.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3327:24
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3324:21)
    at proxy_box.RenderFractionalTranslation.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3317:19)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3327:24
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3324:21)
    at proxy_box.RenderFractionalTranslation.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3317:19)
    at proxy_box.RenderRepaintBoundary.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderRepaintBoundary.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at routes._RenderFocusTrap.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at routes._RenderFocusTrap.new.hitTest (http://localhost:64556/packages/flutter/src/widgets/widget_inspector.dart.lib.js:19335:36)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderOffstage.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderOffstage.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderOffstage.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3906:59)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at http://localhost:64556/packages/flutter/src/widgets/widget_inspector.dart.lib.js:29639:42
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at overlay$._RenderTheatre.new.hitTestChildren (http://localhost:64556/packages/flutter/src/widgets/widget_inspector.dart.lib.js:29635:28)
    at overlay$._RenderTheatre.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderAbsorbPointer.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderAbsorbPointer.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderAbsorbPointer.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3989:79)
    at proxy_box.RenderPointerListener.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderPointerListener.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:546:36)
    at custom_paint.RenderCustomPaint.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at custom_paint.RenderCustomPaint.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/custom_paint.dart.lib.js:343:20)
    at custom_paint.RenderCustomPaint.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at view.RenderView.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4953:58)
    at binding$5.WidgetsFlutterBinding.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:5834:23)
    at binding$5.WidgetsFlutterBinding.new.[_handlePointerEventImmediately] (http://localhost:64556/packages/flutter/src/gestures/binding.dart.lib.js:333:14)
    at binding$5.WidgetsFlutterBinding.new.handlePointerEvent (http://localhost:64556/packages/flutter/src/gestures/binding.dart.lib.js:325:43)
    at binding$5.WidgetsFlutterBinding.new.[_flushPointerEventQueue] (http://localhost:64556/packages/flutter/src/gestures/binding.dart.lib.js:314:14)
    at binding$5.WidgetsFlutterBinding.new.[_handlePointerDataPacket] (http://localhost:64556/packages/flutter/src/gestures/binding.dart.lib.js:304:65)
    at Object.invoke1 (http://localhost:64556/dart_sdk.js:202716:7)
    at _engine.EnginePlatformDispatcher.__.invokeOnPointerDataPacket (http://localhost:64556/dart_sdk.js:182673:15)
    at _engine.PointerBinding.__.[_onPointerData] (http://localhost:64556/dart_sdk.js:183574:49)
    at http://localhost:64556/dart_sdk.js:184046:26
    at http://localhost:64556/dart_sdk.js:184011:16
    at loggedHandler (http://localhost:64556/dart_sdk.js:183684:11)
Error: Assertion failed: file:///Users/liyanaarachchi/flutter/packages/flutter/lib/src/rendering/box.dart:1927:12
hasSize
"RenderBox was not laid out: RenderPointerListener#60a6a NEEDS-LAYOUT NEEDS-PAINT"
    at Object.throw_ [as throw] (http://localhost:64556/dart_sdk.js:5386:11)
    at Object.assertFailed (http://localhost:64556/dart_sdk.js:5308:15)
    at proxy_box.RenderPointerListener.new.get size [as size] (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4406:42)
    at proxy_box.RenderPointerListener.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:545:26)
    at http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8537:44
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at custom_layout.RenderCustomMultiChildLayoutBox.new.defaultHitTestChildren (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8533:30)
    at custom_layout.RenderCustomMultiChildLayoutBox.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/custom_layout.dart.lib.js:304:19)
    at custom_layout.RenderCustomMultiChildLayoutBox.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at material._RenderInkFeatures.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at material._RenderInkFeatures.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderPhysicalModel.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderPhysicalModel.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderPhysicalModel.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:2343:20)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderRepaintBoundary.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderRepaintBoundary.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderIgnorePointer.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderIgnorePointer.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderIgnorePointer.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3794:59)
    at http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8537:44
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at stack.RenderStack.new.defaultHitTestChildren (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8533:30)
    at stack.RenderStack.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/stack.dart.lib.js:683:19)
    at stack.RenderStack.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderDecoratedBox.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderDecoratedBox.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3327:24
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3324:21)
    at proxy_box.RenderFractionalTranslation.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3317:19)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3327:24
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3324:21)
    at proxy_box.RenderFractionalTranslation.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3317:19)
    at proxy_box.RenderRepaintBoundary.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderRepaintBoundary.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at routes._RenderFocusTrap.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at routes._RenderFocusTrap.new.hitTest (http://localhost:64556/packages/flutter/src/widgets/widget_inspector.dart.lib.js:19335:36)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderOffstage.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderOffstage.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderOffstage.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3906:59)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at http://localhost:64556/packages/flutter/src/widgets/widget_inspector.dart.lib.js:29639:42
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at overlay$._RenderTheatre.new.hitTestChildren (http://localhost:64556/packages/flutter/src/widgets/widget_inspector.dart.lib.js:29635:28)

</code>```

答: this should fix it just add shrinkWrap: true to ListView

Body:
I'm Trying learn flutter and i'm a beginner.I'm trying to list down my shopping cart items in flutter application. Below is my shopping cart code and widget.but i'm getting below error when i tried to access the cart. can someone help me to resolve this issue.

import 'dart:html';

import 'package:distribution/Providers/ShoppingCartProvider.dart';
import 'package:distribution/models/ShoppingCart/CartItem.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../widgets/ShoppingCart/ShoppingCartItem.dart';

class ShoppingCartScreen extends StatelessWidget {
  static const routeName = '/shoppingcart';
  @override
  Widget build(BuildContext context) {
    final cart = Provider.of<ShoppingCartProvider>(context);

    return Scaffold(
        appBar: AppBar(
          title: const Text('Your Cart'),
        ),
        body: Column(
          children: <Widget>[
            Card(
                margin: const EdgeInsets.all(15),
                child: Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Row(
                      children: <Widget>[
                        const Text('Total', style: TextStyle(fontSize: 20)),
                        const Spacer(),
                        Chip(
                          label: Text(
                            '\$${cart.totalAmount}',
                          ),
                          backgroundColor: Theme.of(context).primaryColor,
                        ),
                        TextButton(
                          child: Text('ORDER NOW'),
                          onPressed: () {},

                        ),
                        const SizedBox(height: 10),
                        Expanded(
                          child: ListView.builder(
                            itemCount: cart.items.length,
                            itemBuilder: (ctx, i) => ShoppingCartItem(
                              cart.items.values.toList()[i].id,
                              cart.items.keys.toList()[i],
                              cart.items.values.toList()[i].price,
                              cart.items.values.toList()[i].quantity,
                              cart.items.values.toList()[i].title,
                            ),
                          ),
                        )
                      ],
                    ))),
          ],
        ));
  }
}

this is the part giving me problem

                  Expanded(
                      child: ListView.builder(
                        itemCount: cart.items.length,
                        itemBuilder: (ctx, i) => ShoppingCartItem(
                          cart.items.values.toList()[i].id,
                          cart.items.keys.toList()[i],
                          cart.items.values.toList()[i].price,
                          cart.items.values.toList()[i].quantity,
                          cart.items.values.toList()[i].title,
                        ),
                      ),

my shopping cart widget code

import 'package:distribution/Providers/ShoppingCartProvider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ShoppingCartItem extends StatelessWidget {
  final String id;
  final String productId;
  final double price;
  final int quantity;
  final String title;

   ShoppingCartItem(
    this.id,
    this.productId,
    this.price,
    this.quantity,
    this.title,
  );

  @override
  Widget build(BuildContext context) {
    return Card(
        margin: const EdgeInsets.symmetric(
          horizontal: 15,
          vertical: 4,
        ),
        child: Padding(
          padding:const EdgeInsets.all(8),
          child: ListTile(
            leading: CircleAvatar(
              child: Padding(
                padding:const EdgeInsets.all(5),
                child: FittedBox(
                  child: Text('\$$price'),
                ),
              ),
            ),
            title: Text(title),
            subtitle: Text('Total: '),
            trailing: Text('x'),
          ),
        ),
      );
  }
}

Shopping cart provider

import 'package:distribution/models/ShoppingCart/CartItem.dart';
import 'package:flutter/foundation.dart';

class ShoppingCartProvider with ChangeNotifier {
  // ignore: prefer_final_fields
  Map<String, CartItem> _items = {};

  Map<String, CartItem> get items {
    return {..._items};
  }

  void addItem(
    String productID,
    double price,
    String title,
  ) {
    if (_items.containsKey(productID)) {
      _items.update(
          productID,
          (existingitem) => CartItem(
                id: existingitem.id,
                title: existingitem.title,
                quantity: existingitem.quantity + 1,
                price: existingitem.price,
              ));
    } else {
      _items.putIfAbsent(
          productID,
          () => CartItem(
                id: DateTime.now().toString(),
                title: title,
                price: price,
                quantity: 1,
              ));
    }

    notifyListeners();
  }

  int get itemCount {
    return _items == null ? 0 :_items.length;
  }

  double get totalAmount {
    var total = 0.0;
    _items.forEach((key, cartitem) {
      total += cartitem.price * cartitem.quantity ;
    });
    return total;
  }

  void removeItem(String productId) {
    _items.remove(productId);
    notifyListeners();
  }

}

shopping cart model

import 'package:flutter/foundation.dart';

class CartItem {
  final String id;
  final String title;
  final int quantity;
  final double price;

  CartItem({
    @required this.id,
    @required this.title,
    @required this.quantity,
    @required this.price

  });
}

Error I'm Getting

Error: Assertion failed: file:///Users/liyanaarachchi/flutter/packages/flutter/lib/src/rendering/box.dart:1927:12
hasSize
"RenderBox was not laid out: RenderPointerListener#60a6a NEEDS-LAYOUT NEEDS-PAINT"
    at Object.throw_ [as throw] (http://localhost:64556/dart_sdk.js:5386:11)
    at Object.assertFailed (http://localhost:64556/dart_sdk.js:5308:15)
    at proxy_box.RenderPointerListener.new.get size [as size] (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4406:42)
    at proxy_box.RenderPointerListener.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:545:26)
    at http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8537:44
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at custom_layout.RenderCustomMultiChildLayoutBox.new.defaultHitTestChildren (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8533:30)
    at custom_layout.RenderCustomMultiChildLayoutBox.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/custom_layout.dart.lib.js:304:19)
    at custom_layout.RenderCustomMultiChildLayoutBox.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at material._RenderInkFeatures.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at material._RenderInkFeatures.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderPhysicalModel.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderPhysicalModel.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderPhysicalModel.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:2343:20)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderRepaintBoundary.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderRepaintBoundary.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderIgnorePointer.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderIgnorePointer.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderIgnorePointer.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3794:59)
    at http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8537:44
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at stack.RenderStack.new.defaultHitTestChildren (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8533:30)
    at stack.RenderStack.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/stack.dart.lib.js:683:19)
    at stack.RenderStack.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderDecoratedBox.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderDecoratedBox.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3327:24
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3324:21)
    at proxy_box.RenderFractionalTranslation.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3317:19)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3327:24
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3324:21)
    at proxy_box.RenderFractionalTranslation.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3317:19)
    at proxy_box.RenderRepaintBoundary.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderRepaintBoundary.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at routes._RenderFocusTrap.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at routes._RenderFocusTrap.new.hitTest (http://localhost:64556/packages/flutter/src/widgets/widget_inspector.dart.lib.js:19335:36)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderOffstage.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderOffstage.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderOffstage.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3906:59)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at http://localhost:64556/packages/flutter/src/widgets/widget_inspector.dart.lib.js:29639:42
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at overlay$._RenderTheatre.new.hitTestChildren (http://localhost:64556/packages/flutter/src/widgets/widget_inspector.dart.lib.js:29635:28)
    at overlay$._RenderTheatre.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderAbsorbPointer.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderAbsorbPointer.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderAbsorbPointer.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3989:79)
    at proxy_box.RenderPointerListener.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderPointerListener.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:546:36)
    at custom_paint.RenderCustomPaint.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at custom_paint.RenderCustomPaint.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/custom_paint.dart.lib.js:343:20)
    at custom_paint.RenderCustomPaint.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at view.RenderView.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4953:58)
    at binding$5.WidgetsFlutterBinding.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:5834:23)
    at binding$5.WidgetsFlutterBinding.new.[_handlePointerEventImmediately] (http://localhost:64556/packages/flutter/src/gestures/binding.dart.lib.js:333:14)
    at binding$5.WidgetsFlutterBinding.new.handlePointerEvent (http://localhost:64556/packages/flutter/src/gestures/binding.dart.lib.js:325:43)
    at binding$5.WidgetsFlutterBinding.new.[_flushPointerEventQueue] (http://localhost:64556/packages/flutter/src/gestures/binding.dart.lib.js:314:14)
    at binding$5.WidgetsFlutterBinding.new.[_handlePointerDataPacket] (http://localhost:64556/packages/flutter/src/gestures/binding.dart.lib.js:304:65)
    at Object.invoke1 (http://localhost:64556/dart_sdk.js:202716:7)
    at _engine.EnginePlatformDispatcher.__.invokeOnPointerDataPacket (http://localhost:64556/dart_sdk.js:182673:15)
    at _engine.PointerBinding.__.[_onPointerData] (http://localhost:64556/dart_sdk.js:183574:49)
    at http://localhost:64556/dart_sdk.js:184046:26
    at http://localhost:64556/dart_sdk.js:184011:16
    at loggedHandler (http://localhost:64556/dart_sdk.js:183684:11)
Error: Assertion failed: file:///Users/liyanaarachchi/flutter/packages/flutter/lib/src/rendering/box.dart:1927:12
hasSize
"RenderBox was not laid out: RenderPointerListener#60a6a NEEDS-LAYOUT NEEDS-PAINT"
    at Object.throw_ [as throw] (http://localhost:64556/dart_sdk.js:5386:11)
    at Object.assertFailed (http://localhost:64556/dart_sdk.js:5308:15)
    at proxy_box.RenderPointerListener.new.get size [as size] (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4406:42)
    at proxy_box.RenderPointerListener.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:545:26)
    at http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8537:44
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at custom_layout.RenderCustomMultiChildLayoutBox.new.defaultHitTestChildren (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8533:30)
    at custom_layout.RenderCustomMultiChildLayoutBox.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/custom_layout.dart.lib.js:304:19)
    at custom_layout.RenderCustomMultiChildLayoutBox.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at material._RenderInkFeatures.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at material._RenderInkFeatures.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderPhysicalModel.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderPhysicalModel.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderPhysicalModel.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:2343:20)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderRepaintBoundary.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderRepaintBoundary.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderIgnorePointer.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderIgnorePointer.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderIgnorePointer.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3794:59)
    at http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8537:44
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at stack.RenderStack.new.defaultHitTestChildren (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8533:30)
    at stack.RenderStack.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/stack.dart.lib.js:683:19)
    at stack.RenderStack.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderDecoratedBox.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderDecoratedBox.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3327:24
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3324:21)
    at proxy_box.RenderFractionalTranslation.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3317:19)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3327:24
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at proxy_box.RenderFractionalTranslation.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3324:21)
    at proxy_box.RenderFractionalTranslation.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3317:19)
    at proxy_box.RenderRepaintBoundary.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderRepaintBoundary.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at routes._RenderFocusTrap.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at routes._RenderFocusTrap.new.hitTest (http://localhost:64556/packages/flutter/src/widgets/widget_inspector.dart.lib.js:19335:36)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderOffstage.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderOffstage.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at proxy_box.RenderOffstage.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:3906:59)
    at proxy_box.RenderSemanticsAnnotations.new.hitTestChildren (http://localhost:64556/packages/flutter/src/rendering/proxy_box.dart.lib.js:448:56)
    at proxy_box.RenderSemanticsAnnotations.new.hitTest (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:4651:28)
    at http://localhost:64556/packages/flutter/src/widgets/widget_inspector.dart.lib.js:29639:42
    at box.BoxHitTestResult.wrap.addWithPaintOffset (http://localhost:64556/packages/flutter/src/rendering/layer.dart.lib.js:8267:19)
    at overlay$._RenderTheatre.new.hitTestChildren (http://localhost:64556/packages/flutter/src/widgets/widget_inspector.dart.lib.js:29635:28)


来源: stackexchange

问:
Break line when string reaches X characters
I created this function below to calculate when a string (name) reaches more than 35 characters then it break a line.

function getName(name) {
      let newName = name
      for (let i = 0; i < name.length; i += 1) {
        if (i % 35 === 0) {
          newName = `${newName.substr(0, i)}\n${newName.substr(i)}`
        }
      }
      return newName
}

console.log(getName("Please note that popular names below"))```
</div>
</div>
</p>
<p>Eg output:</p>
```Name = "Please note that popular names below"
function output:

Please note that popular names bel
ow
```

What I want is to instead of break a line of these two last characters "ow", I put "below" in the next line.

答:
I came up with a simple solution, you simply have to look if the 35th character is a space(' '). If yes simply cut but if it isn't go back in the string until you hit a space, and cut there. My solution puts a line break if there are no spaces in the first 35 characters. Btw your code did copy the space to the next line, then you would have a small offset at every line.

The code:

function getName(name) {
  let newName = name;
  // offsets i to match the current string
  let offset = 0;

  for (let i = 1; i < name.length; i += 1) {
    if (i % 35 === 0) {
      if(newName.charAt(i) === ' ') {
        // Your own code with the offset
        newName = newName = `${newName.substr(0, i - offset)}\n${newName.substr(i - offset + 1)}`;
      } else {
        // looking back in the string until there is a space or the string "ends"
        while(newName.charAt(i - offset) !== ' ' && offset <= 35) {
          offset++;
        }

        // Only set newName if a space was found in the last 35
        if(i - offset > 0) {
          newName = `${newName.substr(0, i - offset)}\n${newName.substr(i - offset + 1)}`;
        }
      }
    }
  }

  return newName;
}

console.log(getName("Please note that popular names below"));```

JsFiddle

I tried to explain in the comments what i did and why.

ContentLicense: CC BY-SA 4.0

Body:
I created this function below to calculate when a string (name) reaches more than 35 characters then it break a line.

function getName(name) {
      let newName = name
      for (let i = 0; i < name.length; i += 1) {
        if (i % 35 === 0) {
          newName = `${newName.substr(0, i)}\n${newName.substr(i)}`
        }
      }
      return newName
}

console.log(getName("Please note that popular names below"))

Eg output:

Name = "Please note that popular names below"
function output:

Please note that popular names bel
ow

What I want is to instead of break a line of these two last characters "ow", I put "below" in the next line.

Body:
I came up with a simple solution, you simply have to look if the 35th character is a space(' '). If yes simply cut but if it isn't go back in the string until you hit a space, and cut there. My solution puts a line break if there are no spaces in the first 35 characters. Btw your code did copy the space to the next line, then you would have a small offset at every line.

The code:

function getName(name) {
  let newName = name;
  // offsets i to match the current string
  let offset = 0;

  for (let i = 1; i < name.length; i += 1) {
    if (i % 35 === 0) {
      if(newName.charAt(i) === ' ') {
        // Your own code with the offset
        newName = newName = `${newName.substr(0, i - offset)}\n${newName.substr(i - offset + 1)}`;
      } else {
        // looking back in the string until there is a space or the string "ends"
        while(newName.charAt(i - offset) !== ' ' && offset <= 35) {
          offset++;
        }

        // Only set newName if a space was found in the last 35
        if(i - offset > 0) {
          newName = `${newName.substr(0, i - offset)}\n${newName.substr(i - offset + 1)}`;
        }
      }
    }
  }

  return newName;
}

console.log(getName("Please note that popular names below"));

JsFiddle

I tried to explain in the comments what i did and why.


问:
array only pushes first element
For some reason, the chordMidiNumbers function isn't working correctly on iOS Chrome. The expected result would be midiArray at least contains 2 or many elements for Howlerjs to play the audio. However, when I tested it on iOS device (iPhone and iPad), the console prints out the first note of the chord and never reaches the return statement. Any help will be greatly appreciated. (Edit: for our project, we uses tonal js to convert notes into midi numbers)

Here is the actual code:

```<code> /**
     * Given a chord object, return the midi numbers of the notes in the chord
     * @param {any} chordDetails - The chord details object that is returned from the getChordDetailsFromChord function.
     * @returns The midi numbers of the notes in the chord.
     */

    /*
    Example:
    if app plays C2 Major chord

    chordDetails = { ... , {"chordDetails":"note","chord":{"type":"major","tonic":"C"}}}

//This is what we had before
const chordMidiNumbers = chordNotes.map((noteName: any) => {
  return note(noteName).midi;
});
    */
    const chordMidiNumbers = (
      chordDetails: any,
      additionOctave: number = 0
    ) => {
      const type = chordDetails.chordFormat.chord.type;
      // type = "major"
      const chordNotes = getChordNotesFromChord(chordDetails.chordFormat);
      // chordNotes = ["C2", "E2", "G2"]

      let midiArray: Array<number> = [];
      const customOctave = 12 * additionOctave;
      let tempMidi: number;
      for (let i = 0; i < chordNotes.length; i++) {
        let item = chordNotes[i];
        if (type !== "major" && type !== "minor" && type !== "7") {
          item += 2; //reformatting notes so it can be translated into midi numbers, e.g C+2 = C2
        }
        tempMidi = note(item)?.midi || 0;
        console.log(`tMidi:${tempMidi}`) //36 for C2, 40 for E2, 43 for G2
        if (tempMidi === 0) continue;

        if (midiArray.length === 0) {
          midiArray.push(tempMidi + customOctave);
          console.log(JSON.stringify(midiArray));
        } else {
          if (type === "P8") {
            midiArray.push(tempMidi + 12 + customOctave);
            console.log(JSON.stringify(midiArray));
            continue;
          }
          if (midiArray.at(-1)! > tempMidi + customOctave) {
            midiArray.push(tempMidi + 12 + customOctave);
            console.log(JSON.stringify(midiArray));
          } else {
            midiArray.push(tempMidi + customOctave);
            console.log(JSON.stringify(midiArray));
          }
        }
      }
      console.log(midiArray);
      return midiArray;
    };
</code>```

Expected Outputs:

```<code>tMidi: 36
[36]
tMidi: 40
[36, 40]
tMidi: 43
[36, 40, 43]
//plays the audio
(3) [36, 40, 43]

//F Major chord
tMidi: 41
[41]
tMidi: 45
[41, 45]
tMidi: 36
[41, 45, 48]
//plays the audio
(3) [41, 45, 48]
</code>```

Actual Outputs:

```<code>tMidi: 36
[36]
tMidi: 40
//no audio being played

tMidi: 41
[41]
tMidi: 45
//no audio being played
</code>```

答: Apparently Array.at() isn't supported on iOS Chrome (Thanks to pilchard). Program returns fully functional when I replaced Array.at() with [midiArray.length - 1]

Title: array only pushes first element

Body:
For some reason, the chordMidiNumbers function isn't working correctly on iOS Chrome. The expected result would be midiArray at least contains 2 or many elements for Howlerjs to play the audio. However, when I tested it on iOS device (iPhone and iPad), the console prints out the first note of the chord and never reaches the return statement. Any help will be greatly appreciated. (Edit: for our project, we uses tonal js to convert notes into midi numbers)

Here is the actual code:

 /**
     * Given a chord object, return the midi numbers of the notes in the chord
     * @param {any} chordDetails - The chord details object that is returned from the getChordDetailsFromChord function.
     * @returns The midi numbers of the notes in the chord.
     */

    /*
    Example:
    if app plays C2 Major chord

    chordDetails = { ... , {"chordDetails":"note","chord":{"type":"major","tonic":"C"}}}

//This is what we had before
const chordMidiNumbers = chordNotes.map((noteName: any) => {
  return note(noteName).midi;
});
    */
    const chordMidiNumbers = (
      chordDetails: any,
      additionOctave: number = 0
    ) => {
      const type = chordDetails.chordFormat.chord.type;
      // type = "major"
      const chordNotes = getChordNotesFromChord(chordDetails.chordFormat);
      // chordNotes = ["C2", "E2", "G2"]

      let midiArray: Array<number> = [];
      const customOctave = 12 * additionOctave;
      let tempMidi: number;
      for (let i = 0; i < chordNotes.length; i++) {
        let item = chordNotes[i];
        if (type !== "major" && type !== "minor" && type !== "7") {
          item += 2; //reformatting notes so it can be translated into midi numbers, e.g C+2 = C2
        }
        tempMidi = note(item)?.midi || 0;
        console.log(`tMidi:${tempMidi}`) //36 for C2, 40 for E2, 43 for G2
        if (tempMidi === 0) continue;

        if (midiArray.length === 0) {
          midiArray.push(tempMidi + customOctave);
          console.log(JSON.stringify(midiArray));
        } else {
          if (type === "P8") {
            midiArray.push(tempMidi + 12 + customOctave);
            console.log(JSON.stringify(midiArray));
            continue;
          }
          if (midiArray.at(-1)! > tempMidi + customOctave) {
            midiArray.push(tempMidi + 12 + customOctave);
            console.log(JSON.stringify(midiArray));
          } else {
            midiArray.push(tempMidi + customOctave);
            console.log(JSON.stringify(midiArray));
          }
        }
      }
      console.log(midiArray);
      return midiArray;
    };

Expected Outputs:

tMidi: 36
[36]
tMidi: 40
[36, 40]
tMidi: 43
[36, 40, 43]
//plays the audio
(3) [36, 40, 43]

//F Major chord
tMidi: 41
[41]
tMidi: 45
[41, 45]
tMidi: 36
[41, 45, 48]
//plays the audio
(3) [41, 45, 48]

Actual Outputs:

tMidi: 36
[36]
tMidi: 40
//no audio being played

tMidi: 41
[41]
tMidi: 45
//no audio being played


问:
AttributeError: 'KeyedVectors' object has no attribute 'get_keras_embedding'
I want to import "Word2Vec" from "Keyed Vectors". This is my code:

```<code>from gensim.models import KeyedVectors

wv = KeyedVectors.load_word2vec_format("german.model", binary = True)

from keras.models import Sequential

model = Sequential()
model.add(wv.get_keras_embedding())
</code>```

However, I get the following error message:

AttributeError: 'KeyedVectors' object has no attribute 'get_keras_embedding'

I would be really happy if someone could help me

答: The utility function get_keras_embedding() no longer exists on KeyedVectors. You can copy its functionality yourself, in an external function, using the guidance on the Gensim wiki: https://github.com/RaRe-Technologies/gensim/wiki/Using-Gensim-Embeddings-with-Keras-and-Tensorflow

Body:
I want to import "Word2Vec" from "Keyed Vectors". This is my code:

from gensim.models import KeyedVectors

wv = KeyedVectors.load_word2vec_format("german.model", binary = True)

from keras.models import Sequential

model = Sequential()
model.add(wv.get_keras_embedding())

However, I get the following error message:

AttributeError: 'KeyedVectors' object has no attribute 'get_keras_embedding'

I would be really happy if someone could help me


问:
Show matplotlib plots (and other GUI) in Ubuntu (WSL1 & WSL2)
So it seems on ubuntu for windows (windows subsystem for linux) people are suggesting we need to use Agg backend and just save images, not show plots.

```<code>import matplotlib
matplotlib.use('Agg') # no UI backend

import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)
plt.title('About as simple as it gets, folks')

#plt.show()
plt.savefig("matplotlib.png")  #savefig, don't show
</code>```

How could we get it to where plt.show() would actually show us an image?  My current option is to override plot.show() to instead just savefig a plot-148123456.png  under /mnt/c/Users/james/plots/ in windows and just have an explorer window open viewing the images.

I suppose I could host that folder and use a browser.

My goal is to be able to run simple examples like the code above without changing the code to ftp the images somewhere etc.  I just want the plot to show up in a window.

Has anyone figured out a decent way to do it?

答:
With Windows 11 22000, Linux GUI apps are officially supported out of the box provided pre-requisites are met. No twaeks, No hacks, No firewall changes etc.

Pre-Requisites:

Windows 11 Build 22000 or higher

Installed driver for vGPU (Intel/Nvidia/AMD)

Then run the commands

wsl --update

wsl --shutdown

Done !!

Official Source : https://learn.microsoft.com/en-us/windows/wsl/tutorials/gui-apps

Body:
So it seems on ubuntu for windows (windows subsystem for linux) people are suggesting we need to use Agg backend and just save images, not show plots.

import matplotlib
matplotlib.use('Agg') # no UI backend

import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)
plt.title('About as simple as it gets, folks')

#plt.show()
plt.savefig("matplotlib.png")  #savefig, don't show

How could we get it to where plt.show() would actually show us an image?  My current option is to override plot.show() to instead just savefig a plot-148123456.png  under /mnt/c/Users/james/plots/ in windows and just have an explorer window open viewing the images.

I suppose I could host that folder and use a browser.

My goal is to be able to run simple examples like the code above without changing the code to ftp the images somewhere etc.  I just want the plot to show up in a window.

Has anyone figured out a decent way to do it?


问:
how to make application with android
I am trying to create a new android apps but it says me like this

[2011-08-18 15:27:39 - jeetu] Conversion to Dalvik format failed:
  Unable to execute dex: wrapper was not properly loaded first

What does it mean?

答: I'd say leave NotePad example aside and start with Eclipse and ADT. Its worth it.</p>

ContentLicense: CC BY-SA 3.0

Title: how to make application with android


问:
How can I determine if a webcam is in use on Windows 10 without activating the camera?
On Windows 10, how can I determine if an attached web camera is currently active without turning the camera on if it's off?

Currently, I'm able to attempt to take a photo with the camera, and if it fails, assume that the camera is in use. However, this means that the activity LED for the camera will turn on (since the camera is now in use). Since I'd like to check the status of the camera every few seconds, it's not feasible to use this method to determine if the camera is in use.

I've used both the Win32 and UWP tags, and will accept a solution that uses either API.

答:
I found a tip here that mentions that registry keys under Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\webcam\NonPackaged change when the webcam is in use.

There are keys under here that track timestamps on when an application uses the webcam. When the webcam is actively in use, it appears that the 'LastUsedTimeStop' is 0, so to tell if the webcam is actively in use we may be able to simply check if any application has a LastUsedTimeStop==0.

Here's a quick Python class to poll the registry for webcam usage:
https://gist.github.com/cobryan05/8e191ae63976224a0129a8c8f376adc6

Example usage:

```<code>import time
from webcamDetect import WebcamDetect
webcamDetect = WebcamDetect()
while True:
    print("Applications using webcam:")
    for app in webcamDetect.getActiveApps():
        print(app)
    print("---")
    time.sleep(1)
</code>```

Body:
I found a tip here that mentions that registry keys under Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\webcam\NonPackaged change when the webcam is in use.

There are keys under here that track timestamps on when an application uses the webcam. When the webcam is actively in use, it appears that the 'LastUsedTimeStop' is 0, so to tell if the webcam is actively in use we may be able to simply check if any application has a LastUsedTimeStop==0.

Here's a quick Python class to poll the registry for webcam usage:
https://gist.github.com/cobryan05/8e191ae63976224a0129a8c8f376adc6

Example usage:

import time
from webcamDetect import WebcamDetect
webcamDetect = WebcamDetect()
while True:
    print("Applications using webcam:")
    for app in webcamDetect.getActiveApps():
        print(app)
    print("---")
    time.sleep(1)


问:
How can I make one chart "span" the height / width of multiple charts in concatenated plots?
In the following example, I'd like to have exp fill the entire width of the plot (so, as wide as sin and cos combined).  By default, exp fills only one column.

How can I do this, ideally using some "auto" setting (without explicitly setting a width= to a number)?

import altair as alt
import numpy as np
import pandas as pd

x = np.linspace(0, 20, 100)
source = pd.DataFrame({
  'x': x,
  'sin': np.sin(x),
  'cos': np.cos(x),
  'exp': np.exp(x),
})

base = alt.Chart(source).mark_line().encode(x='x')
sin = base.encode(y='sin')
cos = base.encode(y='cos')
exp = base.encode(y='exp')
(sin | cos) & exp
```

答:
A similar solution for width:

```<code>w = 200
spacing = 64

base = alt.Chart(source).mark_line().encode(x='x')
sin = base.encode(y='sin').properties(width=w, height=100)
cos = base.encode(y='cos').properties(width=w, height=100)
exp = base.encode(y='exp').properties(width=2*w+spacing, height=100)

row = alt.hconcat(sin, cos).properties(
    bounds='flush',
    spacing=spacing
)

alt.vconcat(row, exp).configure_axisY(labelLimit=spacing)
</code>```

Not aligned, but maybe visually nice enough with less code:

```<code>w = 200

base = alt.Chart(source).mark_line().encode(x='x')
sin = base.encode(y='sin').properties(width=w, height=100)
cos = base.encode(y='cos').properties(width=w, height=100)
exp = base.encode(y='exp').properties(width=2*w, height=100)

row = alt.hconcat(sin, cos)
alt.vconcat(row, exp).properties(center=True)
</code>```

Body:
A similar solution for width:

w = 200
spacing = 64

base = alt.Chart(source).mark_line().encode(x='x')
sin = base.encode(y='sin').properties(width=w, height=100)
cos = base.encode(y='cos').properties(width=w, height=100)
exp = base.encode(y='exp').properties(width=2*w+spacing, height=100)

row = alt.hconcat(sin, cos).properties(
    bounds='flush',
    spacing=spacing
)

alt.vconcat(row, exp).configure_axisY(labelLimit=spacing)

Not aligned, but maybe visually nice enough with less code:

w = 200

base = alt.Chart(source).mark_line().encode(x='x')
sin = base.encode(y='sin').properties(width=w, height=100)
cos = base.encode(y='cos').properties(width=w, height=100)
exp = base.encode(y='exp').properties(width=2*w, height=100)

row = alt.hconcat(sin, cos)
alt.vconcat(row, exp).properties(center=True)


问:
Refresh token for google calendar API
Hi I am using the google calendar API for a school project and my tokens have expired and I don't know how to refresh them. Please help!!!</p>

答: Generally, when a token expires, make a new one using the same process and replace the old one in your code with the new one.</p>

Title: Refresh token for google calendar API


问:
Using the cblas_chpr function
I'm having issue when I tried to use the cblas_chpr() function from the cblas library to calculate the correlation matrix of a float complex vector.

After downloading the Lapack v3.10.0 Library from netLib.org, I compiled it and copied the libcblas.a, liblapack.a, liblapacke.a, librefblas.a and libtmglib.a files to my project and make sure that the libraries are linked correctly.

According to the description, the cblas_chpr function calculates alpha * x * conjg(x') + A and stores the result in A.

The function is defined as:

```<code>void cblas_chpr(CBLAS_LAYOUT layout, CBLAS_UPLO Uplo,
                const CBLAS_INDEX N, const float alpha, const void *X,
                const CBLAS_INDEX incX, void *A);
</code>```

Where the parameters are:

layout - this is an emun and the two possible inputs are CblasRowMajor and CblasColMajor.

Uplo - this is an enum and the two possible inputs are CblasUpper and CblasLower.

N - The order of matrix A and the number of elements in vector x.

alpha - The scaling factor that vector X is multiplied by.

X - Vector X.

incX - Stride within X. For example, if incX is 7, every 7th element is used.

A - Matrix A. Overwritten by results on return.

The body of my function is as followed:

```<code>   /* Number of elements */
   int Ne = 10;

   /* Set the parameters */
   CBLAS_LAYOUT layout = CblasColMajor;   /* Layout is column major */
   CBLAS_UPLO Uplo = CblasUpper;          /* Upper triangle of the matrix */
   CBLAS_INDEX N = Ne;                    /* Number of elements in vector X */
   float alpha = 1.0;                     /* No scaling, alpha = 1.0 */

   /* The vector X */
   float complex * X = malloc(Ne * sizeof(* X));

   /* Set values of X - for illustration purpose only */
   for(int i = 0; i < Ne; i++)
   {
      X[i] = CMPLXF(i, i + 1.0);
   }

   CBLAS_INDEX incX = 1;                  /* Use data from every element */

   /* The correlation matrix is a Ne x Ne matrix */
   float complex ** A = malloc(Ne * sizeof(*A));

   for(int i = 0; i < Ne; i++)
   {
      A[i] = malloc(Ne * sizeof(*A[i]));
   }

   cblas_chpr(layout, Uplo, N, alpha, X, incX, A);

   float complex print_val = A[0][0];
   printf("%+.10f %+.10f", crealf(print_val), cimagf(print_val));
</code>```

However, the program crashed with the No source available for "chpr_() at 0x55555555e70b" error.

I'm guessing that my input parameters are not correct. CBLAS is a wrapper for the Fortran BLAS Library.

Has anyone encountered this error before and know how to resolve it?

答:
Answering my own question in case someone else ran into the same issue. A should be a 1D array of size N * (N + 1) / 2. Also, the value each element in array A must be initialize to zero. Otherwise, the result will be wrong. Read the description for the cblas_chpr() function for why this is the case.</p>
```<code>/* Number of elements */
int Ne = 10;

/* Set the parameters */
CBLAS_LAYOUT layout = CblasColMajor;   /* Layout is column major */
CBLAS_UPLO Uplo = CblasUpper;          /* Upper triangle of the matrix */
CBLAS_INDEX N = Ne;                    /* Number of elements in vector X */
float alpha = 1.0;                     /* No scaling, alpha = 1.0 */

/* The vector X */
float complex * X = malloc(Ne * sizeof(* X));

/* Set values of X - for illustration purpose only */
for(int i = 0; i < Ne; i++)
{
  X[i] = CMPLXF(i, i + 1.0);
}

CBLAS_INDEX incX = 1;                  /* Use data from every element */

/* Initialize the array that store correlation matrix */
int size_A = Ne * (Ne + 1) / 2;
float complex * A = malloc(size_A * sizeof(*A));

for(int i = 0; i < size_A; i++)
{
    A[i] = 0.0;
}

cblas_chpr(layout, Uplo, N, alpha, X, incX, A);

/* Print the first value of the result */
float complex print_val = A[0][0];
printf("%+.10f %+.10f", crealf(print_val), cimagf(print_val));

free(X);
free(A);
</code>```

Title: Using the cblas_chpr function

Body:
I'm having issue when I tried to use the cblas_chpr() function from the cblas library to calculate the correlation matrix of a float complex vector.

After downloading the Lapack v3.10.0 Library from netLib.org, I compiled it and copied the libcblas.a, liblapack.a, liblapacke.a, librefblas.a and libtmglib.a files to my project and make sure that the libraries are linked correctly.

According to the description, the cblas_chpr function calculates alpha * x * conjg(x') + A and stores the result in A.

The function is defined as:

void cblas_chpr(CBLAS_LAYOUT layout, CBLAS_UPLO Uplo,
                const CBLAS_INDEX N, const float alpha, const void *X,
                const CBLAS_INDEX incX, void *A);

Where the parameters are:

layout - this is an emun and the two possible inputs are CblasRowMajor and CblasColMajor.

Uplo - this is an enum and the two possible inputs are CblasUpper and CblasLower.

N - The order of matrix A and the number of elements in vector x.

alpha - The scaling factor that vector X is multiplied by.

X - Vector X.

incX - Stride within X. For example, if incX is 7, every 7th element is used.

A - Matrix A. Overwritten by results on return.

The body of my function is as followed:

   /* Number of elements */
   int Ne = 10;

   /* Set the parameters */
   CBLAS_LAYOUT layout = CblasColMajor;   /* Layout is column major */
   CBLAS_UPLO Uplo = CblasUpper;          /* Upper triangle of the matrix */
   CBLAS_INDEX N = Ne;                    /* Number of elements in vector X */
   float alpha = 1.0;                     /* No scaling, alpha = 1.0 */

   /* The vector X */
   float complex * X = malloc(Ne * sizeof(* X));

   /* Set values of X - for illustration purpose only */
   for(int i = 0; i < Ne; i++)
   {
      X[i] = CMPLXF(i, i + 1.0);
   }

   CBLAS_INDEX incX = 1;                  /* Use data from every element */

   /* The correlation matrix is a Ne x Ne matrix */
   float complex ** A = malloc(Ne * sizeof(*A));

   for(int i = 0; i < Ne; i++)
   {
      A[i] = malloc(Ne * sizeof(*A[i]));
   }

   cblas_chpr(layout, Uplo, N, alpha, X, incX, A);

   float complex print_val = A[0][0];
   printf("%+.10f %+.10f", crealf(print_val), cimagf(print_val));

However, the program crashed with the No source available for "chpr_() at 0x55555555e70b" error.

I'm guessing that my input parameters are not correct. CBLAS is a wrapper for the Fortran BLAS Library.

Has anyone encountered this error before and know how to resolve it?

Body:
Answering my own question in case someone else ran into the same issue. A should be a 1D array of size N * (N + 1) / 2. Also, the value each element in array A must be initialize to zero. Otherwise, the result will be wrong. Read the description for the cblas_chpr() function for why this is the case.

/* Number of elements */
int Ne = 10;

/* Set the parameters */
CBLAS_LAYOUT layout = CblasColMajor;   /* Layout is column major */
CBLAS_UPLO Uplo = CblasUpper;          /* Upper triangle of the matrix */
CBLAS_INDEX N = Ne;                    /* Number of elements in vector X */
float alpha = 1.0;                     /* No scaling, alpha = 1.0 */

/* The vector X */
float complex * X = malloc(Ne * sizeof(* X));

/* Set values of X - for illustration purpose only */
for(int i = 0; i < Ne; i++)
{
  X[i] = CMPLXF(i, i + 1.0);
}

CBLAS_INDEX incX = 1;                  /* Use data from every element */

/* Initialize the array that store correlation matrix */
int size_A = Ne * (Ne + 1) / 2;
float complex * A = malloc(size_A * sizeof(*A));

for(int i = 0; i < size_A; i++)
{
    A[i] = 0.0;
}

cblas_chpr(layout, Uplo, N, alpha, X, incX, A);

/* Print the first value of the result */
float complex print_val = A[0][0];
printf("%+.10f %+.10f", crealf(print_val), cimagf(print_val));

free(X);
free(A);


问:
Moving data-frame columns as per defined extent
As shown below, let's assume we have a data frame with 1 'extent' column, and 10 'col' columns, of which only first 7 'cols' are filled in the beginning.

Note: Grey highlight in NA cells is just for aesthetics.

We need to move first 'extent' cells of col columns to the end by some vectorised formula or a function. The output should look like below:

I wrote following piece of code to do it, but it's not working:

```<code>df <- ifelse(df$extent > 0,
                  df[, c(1, 9:(9+df$extent), 2+df$extent:8,2:(1+df$extent),(9+df$extent):11)
                      ] ,df)
</code>```

I get the error as: "numerical expression has 3 elements: only the first used"

Please help me out.

答:
Using a for loop and a swap function :

```<code>dat <- structure(list(extent = 0:2, col1 = c("1", "A", "a"), col2 = c("2", "B", "b"), col3 = c("3", "C", "c"), col4 = c("4", "D", "d"), col5 = c("5", "E", "e"), col6 = c("6", "F", "f"), col7 = c("7", "G", "g"), col8 = c(NA, NA, NA), col9 = c(NA, NA, NA), col10 = c(NA, NA, NA)), row.names = c(NA, -3L), class = "data.frame")

for (i in 1:nrow(dat)) {
  k <- 7 #number of non NA cols
  ext <- dat$extent[i]
  if(ext > 0) seqinr::swap(dat[i, 2:(ext + 1)], dat[i, (k + 2):(k + ext + 1)])
}

dat
</code>```

Body:
As shown below, let's assume we have a data frame with 1 'extent' column, and 10 'col' columns, of which only first 7 'cols' are filled in the beginning.

Note: Grey highlight in NA cells is just for aesthetics.

We need to move first 'extent' cells of col columns to the end by some vectorised formula or a function. The output should look like below:

I wrote following piece of code to do it, but it's not working:

df <- ifelse(df$extent > 0,
                  df[, c(1, 9:(9+df$extent), 2+df$extent:8,2:(1+df$extent),(9+df$extent):11)
                      ] ,df)

I get the error as: "numerical expression has 3 elements: only the first used"

Please help me out.

Body:
Using a for loop and a swap function :

dat <- structure(list(extent = 0:2, col1 = c("1", "A", "a"), col2 = c("2", "B", "b"), col3 = c("3", "C", "c"), col4 = c("4", "D", "d"), col5 = c("5", "E", "e"), col6 = c("6", "F", "f"), col7 = c("7", "G", "g"), col8 = c(NA, NA, NA), col9 = c(NA, NA, NA), col10 = c(NA, NA, NA)), row.names = c(NA, -3L), class = "data.frame")

for (i in 1:nrow(dat)) {
  k <- 7 #number of non NA cols
  ext <- dat$extent[i]
  if(ext > 0) seqinr::swap(dat[i, 2:(ext + 1)], dat[i, (k + 2):(k + ext + 1)])
}

dat


问:
Curl To Python Request (-d parameter)
Havin error to convert the below curl into python request.

curl -G "https://thethings.example.com/api/v3/as/applications//packages/storage/uplink_message"

-H "Authorization: Bearer $API_KEY"

-H "Accept: text/event-stream"

-d "limit=10"

-d "after=2020-08-20T00:00:00Z"

-d "field_mask=up.uplink_message.decoded_payload"

Python Request
headers = {
  'Authorization': f'Bearer {apiKey}',

    'Accept': 'text/event-stream',
'Content-Type': 'application/json;charset=utf-8'}

data = {
"order": {
       'field_mask=up.uplink_message.decoded_payload'
      }
   }

response = requests.get(url, headers=headers)
print(response.status_code)
print(response.text)

答:
you can try use this tool - https://curlconverter.com/</p>
```<code>import os
import requests

API_KEY = os.getenv('API_KEY')

headers = {
    'Authorization': f"Bearer {API_KEY}",
    'Accept': 'text/event-stream',
}

params = (
    ('limit', '10'),
    ('after', '2020-08-20T00:00:00Z'),
    ('field_mask', 'up.uplink_message.decoded_payload'),
)

response = requests.get('https://thethings.example.com/api/v3/as/applications//packages/storage/uplink_message', headers=headers, params=params)
</code>```

Title: Curl To Python Request (-d parameter)

Body:
you can try use this tool - https://curlconverter.com/

import os
import requests

API_KEY = os.getenv('API_KEY')

headers = {
    'Authorization': f"Bearer {API_KEY}",
    'Accept': 'text/event-stream',
}

params = (
    ('limit', '10'),
    ('after', '2020-08-20T00:00:00Z'),
    ('field_mask', 'up.uplink_message.decoded_payload'),
)

response = requests.get('https://thethings.example.com/api/v3/as/applications//packages/storage/uplink_message', headers=headers, params=params)


问:
How to convert an object into an array of objects with named properties?
How do you go from a single object like this:

```<code>{
    item001: '200',
    item002: '350',
    ...
}
</code>```

to an array of objects with named properties like this:

```<code>[
    {
        product: 'item001',
        price: 200
    },
    {
        product: 'item002',
        price: 350
    },
    ...
]
</code>```

答:
var main = {
    item001: '200',
    item002: '350'
}

function doThis(items){
 var keys = Object.keys(items);
 var obj = keys.map(key=>({product:key,price:items[key]}))
 return obj;
}

console.log(doThis(main))```

Body:
How do you go from a single object like this:

{
    item001: '200',
    item002: '350',
    ...
}

to an array of objects with named properties like this:

[
    {
        product: 'item001',
        price: 200
    },
    {
        product: 'item002',
        price: 350
    },
    ...
]


问:
How to sum two double linked lists in one list efficiently?
For example listA = [3,6,7,4] and listB = [2,3,1] and the output has to be listC=[5,9,8,6]. This is what I have so far but it is not very efficient.</p>
```<code>`public void sum(doublelist aList) {`
for (int i = 0; i < size(); i++) {
     set(i, this.get(i) + other.get(i % other.size()));
}
}
</code>```

答:
The answer is totally dependent of what kind of List you are using.

But anyway, the best complexity you can get is O(n), you will have to iterate at least one time over each element of the lists.

The easiest is to use a ListIterator, that allow to set a value while iterating over the list.

    void sum(List<Integer> l1, List<Integer> l2) {
        final ListIterator<Integer> it1 = l1.listIterator();
        final Iterator<Integer> it2 = l2.iterator();

        while (it1.hasNext() && it2.hasNext()) {
            it1.set(it1.next() + it2.next());
        }
    }

```

Body:
For example listA = [3,6,7,4] and listB = [2,3,1] and the output has to be listC=[5,9,8,6]. This is what I have so far but it is not very efficient.

`public void sum(doublelist aList) {`
for (int i = 0; i < size(); i++) {
     set(i, this.get(i) + other.get(i % other.size()));
}
}


问:
How to convert a column from string to array in PySpark
I have a dataframe converted from an inherited dataset which looks like the following:

```<code>data = [("[]","2000","M",False),
            ("[{'username':'aabb','points':'200','active':'true'}, {'username':'bbaa22','points':'0','active':'false'}]","1999","F",True),
            ("[{'username':'topuser','points':'855','active':'false'}]","1974","M",True),
            ("[]","2005","F",False),
            ("[{'username':'myprimary','points':'1050','active':'true'}, {'username':'mylurk','points':'100','active':'true'}, {'username':'closedlurk','points':'50','active':'false'}]","1992","M",True)
            ]

columns=["user","dob_year","gender","member"]
df=spark.createDataFrame(data,columns)
</code>```

+--------------------+--------+------+------+
|                user|dob_year|gender|member|
+--------------------+--------+------+------+
|                  []|    2000|     M| false|
|[{'username':'aab...|    1999|     F|  true|
|[{'username':'top...|    1974|     M|  true|
|                  []|    2005|     F| false|
|[{'username':'myp...|    1992|     M|  true|
+--------------------+--------+------+------+
```
<p>I need to extract some of the elements from the <code>user</code> column and I attempt to use the pyspark <code>explode</code> function.</p>
```from pyspark.sql.functions import explode

df2 = df.select(explode(df.user), df.dob_year)
```
<p>When I attempt this, I'm met with the following error:</p>
<blockquote>
<p>AnalysisException: cannot resolve 'explode(<code>user</code>)' due to data type mismatch: input to function explode should be array or map type, not string;</p>
</blockquote>
<p>When I run <code>df.printSchema()</code>, I realize that the user column is string, rather than list as desired.</p>
<p>I also attempted to cast the strings in the column to arrays by creating a UDF</p>
```import pyspark.sql.functions as f

df2 = df.withColumn("user", str2list_udf(f.col("user"))).withColumn("user",df.user.cast(ArrayType(StringType())))
```
<p>When I do that, I'm met with the following error:</p>
<blockquote>
<p>AnalysisException: cannot resolve '<code>user</code>' due to data type mismatch: cannot cast string to array;</p>
</blockquote>
<p>How can the data in this column be cast or converted into an array so that the explode function can be leveraged and individual keys parsed out into their own columns (example: having individual columns for <code>username</code>, <code>points</code> and <code>active</code>)? If explode isn't the best method, is there another route I should follow?</p>
<p>If it's helpful, here is the UDF that I created:</p>
```def str2list(x):
  if x == '[]':
    return list()
  else:
    return list(x)

str2list_udf = udf(lambda x: str2list(x))
```

Thank you

答:
Convert the stringified arrays into array of structs using from_json the explode the resulting array:

```<code>from pyspark.sql import functions as F
from pyspark.sql.types import StructField, ArrayType, StringType, StructType

user_schema = ArrayType(
    StructType([
        StructField("username", StringType(), True),
        StructField("points", StringType(), True),
        StructField("active", StringType(), True)
    ])
)

df1 = (df.withColumn("user", F.from_json("user", user_schema))
       .selectExpr("inline(user)", "dob_year", "gender", "member")
       )

df1.show()
#+----------+------+------+--------+------+------+
#|  username|points|active|dob_year|gender|member|
#+----------+------+------+--------+------+------+
#|      aabb|   200|  true|    1999|     F|  true|
#|    bbaa22|     0| false|    1999|     F|  true|
#|   topuser|   855| false|    1974|     M|  true|
#| myprimary|  1050|  true|    1992|     M|  true|
#|    mylurk|   100|  true|    1992|     M|  true|
#|closedlurk|    50| false|    1992|     M|  true|
#+----------+------+------+--------+------+------+
</code>```

Body:
I have a dataframe converted from an inherited dataset which looks like the following:

data = [("[]","2000","M",False),
            ("[{'username':'aabb','points':'200','active':'true'}, {'username':'bbaa22','points':'0','active':'false'}]","1999","F",True),
            ("[{'username':'topuser','points':'855','active':'false'}]","1974","M",True),
            ("[]","2005","F",False),
            ("[{'username':'myprimary','points':'1050','active':'true'}, {'username':'mylurk','points':'100','active':'true'}, {'username':'closedlurk','points':'50','active':'false'}]","1992","M",True)
            ]

columns=["user","dob_year","gender","member"]
df=spark.createDataFrame(data,columns)

+--------------------+--------+------+------+
|                user|dob_year|gender|member|
+--------------------+--------+------+------+
|                  []|    2000|     M| false|
|[{'username':'aab...|    1999|     F|  true|
|[{'username':'top...|    1974|     M|  true|
|                  []|    2005|     F| false|
|[{'username':'myp...|    1992|     M|  true|
+--------------------+--------+------+------+

I need to extract some of the elements from the user column and I attempt to use the pyspark explode function.

from pyspark.sql.functions import explode

df2 = df.select(explode(df.user), df.dob_year)

When I attempt this, I'm met with the following error:

AnalysisException: cannot resolve 'explode(user)' due to data type mismatch: input to function explode should be array or map type, not string;

When I run df.printSchema(), I realize that the user column is string, rather than list as desired.

I also attempted to cast the strings in the column to arrays by creating a UDF

import pyspark.sql.functions as f

df2 = df.withColumn("user", str2list_udf(f.col("user"))).withColumn("user",df.user.cast(ArrayType(StringType())))

When I do that, I'm met with the following error:

AnalysisException: cannot resolve 'user' due to data type mismatch: cannot cast string to array;

How can the data in this column be cast or converted into an array so that the explode function can be leveraged and individual keys parsed out into their own columns (example: having individual columns for username, points and active)? If explode isn't the best method, is there another route I should follow?

If it's helpful, here is the UDF that I created:

def str2list(x):
  if x == '[]':
    return list()
  else:
    return list(x)

str2list_udf = udf(lambda x: str2list(x))

Thank you

Body:
Convert the stringified arrays into array of structs using from_json the explode the resulting array:

from pyspark.sql import functions as F
from pyspark.sql.types import StructField, ArrayType, StringType, StructType

user_schema = ArrayType(
    StructType([
        StructField("username", StringType(), True),
        StructField("points", StringType(), True),
        StructField("active", StringType(), True)
    ])
)

df1 = (df.withColumn("user", F.from_json("user", user_schema))
       .selectExpr("inline(user)", "dob_year", "gender", "member")
       )

df1.show()
#+----------+------+------+--------+------+------+
#|  username|points|active|dob_year|gender|member|
#+----------+------+------+--------+------+------+
#|      aabb|   200|  true|    1999|     F|  true|
#|    bbaa22|     0| false|    1999|     F|  true|
#|   topuser|   855| false|    1974|     M|  true|
#| myprimary|  1050|  true|    1992|     M|  true|
#|    mylurk|   100|  true|    1992|     M|  true|
#|closedlurk|    50| false|    1992|     M|  true|
#+----------+------+------+--------+------+------+


问:
Process certain properties in array of objects
I am trying to process some properties from an array of objects.

The order is always the same, in that after the second property always comes a range of dates for the next 12 entries, everything after that is to be excluded and sometimes can be two like in this instance or it could be more.

So what I want to do is exclude everything but the keyword and the range of dates.

const data = [{
  "keyword": "foo",
  // This key never changes
  "search_vol": 0,
  // These keys can change when they start, i.e. starts jan-21
  "jul-20": 10,
  "aug-20": 10,
  "sep-20": 10,
  "oct-20": 10,
  "nov-20": 10,
  "dec-20": 10,
  "jan-21": 10,
  "feb-21": 10,
  "mar-21": 10,
  "apr-21": 20,
  "may-21": 10,
  "jun-21": 10,
  // These would change to different properties in name and amount
  "drain": "FALSE",
  "toilet": "TRUE"
}, {
  "keyword": "faa",

  "search_vol": 100,

  "jul-20": 880,
  "aug-20": 880,
  "sep-20": 880,
  "oct-20": 880,
  "nov-20": 880,
  "dec-20": 880,
  "jan-21": 1000,
  "feb-21": 880,
  "mar-21": 1000,
  "apr-21": 720,
  "may-21": 880,
  "jun-21": 880,

  "drain": "TRUE",
  "toilet": "TRUE"
}]
```
<p>I want to do this so later I can get the max value for the dates on each object and have an entry with the months that hit that max</p>
<p>Expected final output:</p>
<pre class="lang-js prettyprint-override"><code>const data = [{
  "keyword": "foo",
  "search_vol": 0,
  "jul-20": 10,
  "aug-20": 10,
  "sep-20": 10,
  "oct-20": 10,
  "nov-20": 10,
  "dec-20": 10,
  "jan-21": 10,
  "feb-21": 10,
  "mar-21": 10,
  "apr-21": 20,
  "may-21": 10,
  "jun-21": 10,
  "Max months": ['apr-21'],
  "drain": "FALSE",
  "toilet": "TRUE"
}, {
  "keyword": "faa",
  "search_vol": 100,
  "jul-20": 880,
  "aug-20": 880,
  "sep-20": 880,
  "oct-20": 880,
  "nov-20": 880,
  "dec-20": 880,
  "jan-21": 1000,
  "feb-21": 880,
  "mar-21": 1000,
  "apr-21": 720,
  "may-21": 880,
  "jun-21": 880,
  "Max months": ['jan-21','mar-21'],
  "drain": "TRUE",
  "toilet": "TRUE"
}]
</code>```

Is it worth separating the processes, first set aside the dates and then get the max, or is it best to do it all in one go?

This is my attempt, excluding the mergin back with the data, but I think is over complicated

const data = [{
  "keyword": "foo",
  "search_vol": 0,

  "jul-20": 10,
  "aug-20": 10,
  "sep-20": 10,
  "oct-20": 10,
  "nov-20": 10,
  "dec-20": 10,
  "jan-21": 10,
  "feb-21": 10,
  "mar-21": 10,
  "apr-21": 20,
  "may-21": 10,
  "jun-21": 10,

  "drain": "FALSE",
  "toilet": "TRUE"
}, {
  "keyword": "faa",
  "search_vol": 100,

  "jul-20": 880,
  "aug-20": 880,
  "sep-20": 880,
  "oct-20": 880,
  "nov-20": 880,
  "dec-20": 880,
  "jan-21": 1000,
  "feb-21": 880,
  "mar-21": 1000,
  "apr-21": 720,
  "may-21": 880,
  "jun-21": 880,

  "drain": "TRUE",
  "toilet": "TRUE"
}]

const headers = Object.keys(data[0]).filter((_, index) => index === 0 || ( index >=  1 && index <= 13))

const dates = data.reduce((acc, obj) => {
  const filtered = headers.reduce((entries, key) => ({ ...entries, [key]: obj[key] }), {})
  acc.push(filtered)
  return acc
}, [])

const months = dates.map(({ keyword, ...dates }) => {
  const max = Math.max(...Object.values(dates))

  const maxMonths = Object.entries(dates).reduce((acc, [key, value]) => {
    if (value === max) acc.push(key)
    return acc
  }, [])

  return {
    keyword,
    'Max months': maxMonths,
  }
})

console.log(months)```

答:
Here is a solution for you

const data = [
  { 'keyword': 'foo', 'search_vol': 0, 'jul-20': 10, 'aug-20': 10, 'sep-20': 10, 'oct-20': 10, 'nov-20': 10, 'dec-20': 10, 'jan-21': 10, 'feb-21': 10, 'mar-21': 10, 'apr-21': 20, 'may-21': 10, 'jun-21': 10, 'drain': 'FALSE', 'toilet': 'TRUE' },
  { 'keyword': 'faa', 'search_vol': 100, 'jul-20': 880, 'aug-20': 880, 'sep-20': 880, 'oct-20': 880, 'nov-20': 880, 'dec-20': 880, 'jan-21': 1000, 'feb-21': 880, 'mar-21': 1000, 'apr-21': 720, 'may-21': 880, 'jun-21': 880, 'drain': 'TRUE', 'toilet': 'TRUE' }
];

const expected = data.map(_obj => {
  // convert object to an array and filter out the values that are not needed
  const filteredArr = Object.entries(_obj)
    .filter(entry => !['keyword', 'search_vol'].includes(entry[0]))
    .slice(0, 12);

  // find the max value in the array
  const max = Math.max(...filteredArr.map(entry => entry[1]));

  // find the list of months with max value
  const maxMonths = filteredArr.filter(entry => entry[1] === max).map(entry => entry[0]);

  return {
    ..._obj,
    'Max Months': maxMonths
  }
})

console.log(expected);```

Body:
I am trying to process some properties from an array of objects.

The order is always the same, in that after the second property always comes a range of dates for the next 12 entries, everything after that is to be excluded and sometimes can be two like in this instance or it could be more.

So what I want to do is exclude everything but the keyword and the range of dates.

const data = [{
  "keyword": "foo",
  // This key never changes
  "search_vol": 0,
  // These keys can change when they start, i.e. starts jan-21
  "jul-20": 10,
  "aug-20": 10,
  "sep-20": 10,
  "oct-20": 10,
  "nov-20": 10,
  "dec-20": 10,
  "jan-21": 10,
  "feb-21": 10,
  "mar-21": 10,
  "apr-21": 20,
  "may-21": 10,
  "jun-21": 10,
  // These would change to different properties in name and amount
  "drain": "FALSE",
  "toilet": "TRUE"
}, {
  "keyword": "faa",

  "search_vol": 100,

  "jul-20": 880,
  "aug-20": 880,
  "sep-20": 880,
  "oct-20": 880,
  "nov-20": 880,
  "dec-20": 880,
  "jan-21": 1000,
  "feb-21": 880,
  "mar-21": 1000,
  "apr-21": 720,
  "may-21": 880,
  "jun-21": 880,

  "drain": "TRUE",
  "toilet": "TRUE"
}]

I want to do this so later I can get the max value for the dates on each object and have an entry with the months that hit that max

Expected final output:

const data = [{
  "keyword": "foo",
  "search_vol": 0,
  "jul-20": 10,
  "aug-20": 10,
  "sep-20": 10,
  "oct-20": 10,
  "nov-20": 10,
  "dec-20": 10,
  "jan-21": 10,
  "feb-21": 10,
  "mar-21": 10,
  "apr-21": 20,
  "may-21": 10,
  "jun-21": 10,
  "Max months": ['apr-21'],
  "drain": "FALSE",
  "toilet": "TRUE"
}, {
  "keyword": "faa",
  "search_vol": 100,
  "jul-20": 880,
  "aug-20": 880,
  "sep-20": 880,
  "oct-20": 880,
  "nov-20": 880,
  "dec-20": 880,
  "jan-21": 1000,
  "feb-21": 880,
  "mar-21": 1000,
  "apr-21": 720,
  "may-21": 880,
  "jun-21": 880,
  "Max months": ['jan-21','mar-21'],
  "drain": "TRUE",
  "toilet": "TRUE"
}]

Is it worth separating the processes, first set aside the dates and then get the max, or is it best to do it all in one go?

This is my attempt, excluding the mergin back with the data, but I think is over complicated

const data = [{
  "keyword": "foo",
  "search_vol": 0,

  "jul-20": 10,
  "aug-20": 10,
  "sep-20": 10,
  "oct-20": 10,
  "nov-20": 10,
  "dec-20": 10,
  "jan-21": 10,
  "feb-21": 10,
  "mar-21": 10,
  "apr-21": 20,
  "may-21": 10,
  "jun-21": 10,

  "drain": "FALSE",
  "toilet": "TRUE"
}, {
  "keyword": "faa",
  "search_vol": 100,

  "jul-20": 880,
  "aug-20": 880,
  "sep-20": 880,
  "oct-20": 880,
  "nov-20": 880,
  "dec-20": 880,
  "jan-21": 1000,
  "feb-21": 880,
  "mar-21": 1000,
  "apr-21": 720,
  "may-21": 880,
  "jun-21": 880,

  "drain": "TRUE",
  "toilet": "TRUE"
}]

const headers = Object.keys(data[0]).filter((_, index) => index === 0 || ( index >=  1 && index <= 13))

const dates = data.reduce((acc, obj) => {
  const filtered = headers.reduce((entries, key) => ({ ...entries, [key]: obj[key] }), {})
  acc.push(filtered)
  return acc
}, [])

const months = dates.map(({ keyword, ...dates }) => {
  const max = Math.max(...Object.values(dates))

  const maxMonths = Object.entries(dates).reduce((acc, [key, value]) => {
    if (value === max) acc.push(key)
    return acc
  }, [])

  return {
    keyword,
    'Max months': maxMonths,
  }
})

console.log(months)