问:
Converting Firebase Realtime database json response from _InternalLinkedHashMap<Object?, Object?> to Map<String,dynamic>
I have a database in my Firebase Realtime database with children that look like this:

Here's the JSON that I receive in my Flutter app from my firebase call:

```<code>{
  "gameAnalytics" : {
    "log" : {
      "20210926073039AbMc4uSXywqpK9OcusSV" : {
        "cityID" : "newYork",
        "countryCode" : "USA",
        "gameID" : "20210927065000Upper90IndnewYofootbiGZYy",
        "gamePaymentMethod" : "payAtPitch",
        "players" : {
          "umZ5ezrtI6a3UoCDWFDc3hInoNA2" : {
            "pnam" : "Mario Rest",
            "url" : "https://i.ibb.co/blahblah.jpg"
          }
        },
        "sportID" : "football",
        "status" : {
          "202109261130395laHd8h77R" : "completing, send back",
          "20210926113039BcUQ8RdbHs" : "payAtPitch",
          "20210926113039Ck9JsD1uf1" : "playersAdded"
        },
        "timeAndDateString" : "20210926073039",
        "totalCost" : 999,
        "type" : "ADD",
        "userWhoAddedID" : "umZ5ezrtI6a3UoCDWFDc3hInoNA2",
        "wantsToBeOrganizer" : true
      },
      "202109261146540focIuCQRi3wNfSluvkl" : {
        "cityID" : "newYork",
        "countryCode" : "USA",
        "gameID" : "20210927065000Upper90IndnewYofootbiGZYy",
        "gamePaymentMethod" : "payByBalance",
        "players" : {
          "hOBQJtqCCNgGBVrAv2MqeaFJmdu1" : {
            "pnam" : "Seong Kang",
            "url" : "messi"
          }
        },
        "promoCodeData" : "U90qaL",
        "sportID" : "football",
        "status" : {
          "2021092615465414NXsxwW51" : "playersAdded",
          "20210926154654A60TLCmS2t" : "paidByBalance",
          "20210926154654VtYR1t4bMZ" : "completing, send back"
        },
        "timeAndDateString" : "20210926114654",
        "totalCost" : 0,
        "type" : "ADD",
        "userWhoAddedID" : "hOBQJtqCCNgGBVrAv2MqeaFJmdu1",
        "wantsToBeOrganizer" : false
      },
      "20210926204533DjF3lMCMDpvwHfsh6lQJ" : {
        "amountToRefund" : 0,
        "promoCodes" : {
          "hOBQJtqCCNgGBVrAv2MqeaFJmdu1" : "U90qaL"
        },
        "status" : {
          "20210927004533ZWGNEMX27V" : "REFUNDING: 0  null  hOBQJtqCCNgGBVrAv2MqeaFJmdu1"
        },
        "type" : "CANCEL",
        "userWhoAddedID" : "hOBQJtqCCNgGBVrAv2MqeaFJmdu1"
      }
    },
    "pitchCost" : 3500,
    "playerNumbers" : {
      "hoursBefore12" : 2,
      "hoursBefore24" : 1,
      "hoursBefore3" : 2,
      "hoursBefore36" : 1,
      "hoursBefore48" : 1,
      "hoursBefore6" : 2,
      "hoursBefore72" : 1,
      "hoursBefore96" : 1
    },
    "timings" : {
      "added" : {
        "20210917004938" : "organiserID12345",
        "20210926113040" : "umZ5ezrtI6a3UoCDWFDc3hInoNA2",
        "20210926154656" : "hOBQJtqCCNgGBVrAv2MqeaFJmdu1"
      },
      "cancelled" : {
        "20210917004939" : "playersUnCancelled",
        "20210927004522" : "playersCancelled"
      },
      "removed" : {
        "20210926113042" : "organiserID12345"
      }
    }
  },
  "gameData" : {
    "addFakePlayers" : false,
    "can" : true,
    "canAddPromoCode" : true,
    "canDes" : {
      "en" : "somedesc"
    },
    "canMes" : "blahblah.",
    "cost" : 999,
    "cur" : 2,
    "currency" : "usd",
    "dat" : "20210927065000",
    "descriptions" : {
      "en" : "blahblah"
    },
    "dur" : "60 minutes",
    "expOrg" : "",
    "gameTypes" : {
      "en" : "blahblah"
    },
    "hostConfirmed" : false,
    "hostInfo" : {
      "hostDescription" : "blahblah",
      "hostNickname" : "Mario R",
      "hostPhoto" : "https://i.ibb.co/blahblah.jpg",
      "isSuperHost" : false
    },
    "lid" : "Upper90IndoorQueensabcde739219515176663407563157034467ap0mr",
    "max" : 15,
    "mes" : "blahblah",
    "mes1" : "my disappointment",
    "mes2" : "is immessurable",
    "mes3" : "and my day",
    "payAtPitchMessage" : {
      "en" : "is ruined"
    },
    "paymentType" : "justOnline",
    "paymentsAllowed" : [ "card" ],
    "pla1" : {
      "hOBQJtqCCNgGBVrAv2MqeaFJmdu1" : {
        "pnam" : "blahblah",
        "url" : "messi"
      }
    },
    "pla2" : {
      "umZ5ezrtI6a3UoCDWFDc3hInoNA2" : {
        "organizer" : true,
        "pnam" : "Mario Rest",
        "url" : "https://i.ibb.co/blahblah.jpg"
      }
    },
    "pub" : false,
    "removalAllowed" : true,
    "showHostConfirmButton" : false,
    "spotEn" : true,
    "surl" : "https://someurl",
    "title" : {
      "en" : "ok"
    }
  },
  "mess" : {
    "-MjlDj5szZxKaDs0p3CN" : {
      "mes" : "ok",
      "tim" : "20210916204938",
      "unm" : "blahblah",
      "usi" : "XwyPhbjzeKNYVczPdCPFTG0DZbj1"
    },
    "-MjlDj6bnMvKUO76EjLE" : {
      "mes" : "ok",
      "tim" : "20210916204938",
      "unm" : "blahblah",
      "usi" : "XwyPhbjzeKNYVczPdCPFTG0DZbj1"
    },
    "-MjlDj7SeqRV0KzRzFFX" : {
      "mes" : "ok",
      "tim" : "20210916204939",
      "unm" : "bllblb",
      "usi" : "XwyPhbjzeKNYVczPdCPFTG0DZbj1"
    },
    "-MjlDj8C-p406IK8I-cb" : {
      "mes" : "msg",
      "tim" : "20210916204940",
      "unm" : "msg",
      "usi" : "XwyPhbjzeKNYVczPdCPFTG0DZbj1"
    }
  },
  "payment" : {
    "playerPaymentStatus" : {
      "hOBQJtqCCNgGBVrAv2MqeaFJmdu1" : {
        "date" : "20210927004533",
        "refundedAmount" : 0,
        "stripePaymentNotConfirmed" : true,
        "type" : "notPaidForGame",
        "userWhoAddedID" : "hOBQJtqCCNgGBVrAv2MqeaFJmdu1"
      }
    }
  },
  "userReview" : {
    "showReview" : true
  }
}
</code>```

I'm trying to create a Map<String, dynamic> from this response by using Map<String,dynamic>.from() as seen below:

```<code>class PickUpGameItem extends StatefulWidget {
  final String gameId;

  const PickUpGameItem(this.gameId, [Key? key]) : super(key: key);

  @override
  _PickUpGameItemState createState() => _PickUpGameItemState();
}

class _PickUpGameItemState extends State<PickUpGameItem> {
  late StreamSubscription _pickUpGameDetailsStreamSub;
  PickUpGameDetails? gameDetails;

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

  @override
  void deactivate() {
    _pickUpGameDetailsStreamSub.cancel();
    super.deactivate();
  }

  void _setListeners() {
    _pickUpGameDetailsStreamSub = FirebaseDatabase()
        .reference()
        .child(
            '.../gamesDetailed/${widget.gameId}/')
        .onValue
        .listen((event) {
      final detailsJson = Map<String, dynamic>.from(event.snapshot.value);
      setState(() {
        gameDetails = PickUpGameDetails.fromJson(detailsJson);
        print(gameDetails.toString());
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      child: Row(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(8.0),
            child: const Image(
              fit: BoxFit.fill,
              width: 80.0,
              height: 80.0,
              image: AssetImage('assets/images/temp_city_img.jpg'),
            ),
          ),
          const SizedBox(
            width: 10,
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: const [
                Text(
                  'Lorem ipsum dolor sit amet this is a test ......................................',
                  style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.bold,
                      fontSize: 16),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                SizedBox(
                  height: 10,
                ),
                Text(
                  'Lorem ipsum dolor sit amet this is a test ......................................',
                  style: TextStyle(
                      color: Colors.grey,
                      fontWeight: FontWeight.normal,
                      fontSize: 14),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
          const SizedBox(
            width: 10,
          ),
          Flexible(
            flex: 0,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  'Football',
                  style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.bold,
                      fontSize: 16),
                ),
                const SizedBox(
                  height: 10,
                ),
                Row(
                  children: const [
                    Text(
                      '14/16',
                      style: TextStyle(
                          color: Colors.grey,
                          fontWeight: FontWeight.normal,
                          fontSize: 14),
                    ),
                    SizedBox(
                      width: 5,
                    ),
                    Icon(Icons.ac_unit)
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

When I run the app, I get an error saying that the internal linked hash map isn't a subtype of map and that the error occurs when calling GameAnalytics.fromJson(). I've seen multiple similar posts but their error mentioned an _InternalLinkedHashMap<String?, dynamic> map. Why Is this linked hash map in my response using Object? for both keys and values?

```<code>[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>'
</code>```

Here are my dart model classes:

PickUpGameDetails.dart:

```<code>class PickUpGameDetails {
  GameAnalytics? gameAnalytics;
  GameData? gameData;
  UserReview? userReview;

  PickUpGameDetails(
      {required this.gameAnalytics,
      required this.gameData,
      required this.userReview});

  PickUpGameDetails.fromJson(Map<String, dynamic> json) {
    gameAnalytics = json['gameAnalytics'] != null
        ? GameAnalytics.fromJson(json['gameAnalytics'])
        : null;
    gameData =
        json['gameData'] != null ? GameData.fromJson(json['gameData']) : null;
    userReview = json['userReview'] != null
        ? UserReview.fromJson(json['userReview'])
        : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (gameAnalytics != null) {
      data['gameAnalytics'] = gameAnalytics!.toJson();
    }
    if (gameData != null) {
      data['gameData'] = gameData!.toJson();
    }
    if (userReview != null) {
      data['userReview'] = userReview!.toJson();
    }
    return data;
  }
}
</code>```

GameAnalytics.dart:

```<code>class GameAnalytics {
  late int pitchCost;
  PlayerNumbers? playerNumbers;
  Timings? timings;

  GameAnalytics(
      {required this.pitchCost,
      required this.playerNumbers,
      required this.timings});

  GameAnalytics.fromJson(Map<String, dynamic> json) {
    pitchCost = json['pitchCost'];
    playerNumbers = json['playerNumbers'] != null
        ? PlayerNumbers.fromJson(json['playerNumbers'])
        : null;
    timings =
        json['timings'] != null ? Timings.fromJson(json['timings']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['pitchCost'] = pitchCost;
    if (playerNumbers != null) {
      data['playerNumbers'] = playerNumbers!.toJson();
    }
    if (timings != null) {
      data['timings'] = timings!.toJson();
    }
    return data;
  }
}
</code>```

PlayerNumbers.dart:

```<code>class PlayerNumbers {
  late int hoursBefore12;
  late int hoursBefore24;
  late int hoursBefore3;
  late int hoursBefore36;
  late int hoursBefore48;
  late int hoursBefore6;
  late int hoursBefore72;
  late int hoursBefore96;

  PlayerNumbers(
      {required this.hoursBefore12,
      required this.hoursBefore24,
      required this.hoursBefore3,
      required this.hoursBefore36,
      required this.hoursBefore48,
      required this.hoursBefore6,
      required this.hoursBefore72,
      required this.hoursBefore96});

  PlayerNumbers.fromJson(Map<String, dynamic> json) {
    hoursBefore12 = json['hoursBefore12'];
    hoursBefore24 = json['hoursBefore24'];
    hoursBefore3 = json['hoursBefore3'];
    hoursBefore36 = json['hoursBefore36'];
    hoursBefore48 = json['hoursBefore48'];
    hoursBefore6 = json['hoursBefore6'];
    hoursBefore72 = json['hoursBefore72'];
    hoursBefore96 = json['hoursBefore96'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['hoursBefore12'] = hoursBefore12;
    data['hoursBefore24'] = hoursBefore24;
    data['hoursBefore3'] = hoursBefore3;
    data['hoursBefore36'] = hoursBefore36;
    data['hoursBefore48'] = hoursBefore48;
    data['hoursBefore6'] = hoursBefore6;
    data['hoursBefore72'] = hoursBefore72;
    data['hoursBefore96'] = hoursBefore96;
    return data;
  }
}
</code>```

Timings.dart:

```<code>class Timings {
  Map<String, dynamic>? added;
  Map<String, dynamic>? cancelled;
  Map<String, dynamic>? removed;

  Timings(
      {required this.added, required this.cancelled, required this.removed});

  Timings.fromJson(Map<String, dynamic> json) {
    added = json['added'];
    cancelled = json['cancelled'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    if (added != null) {
      data['added'] = added;
    }
    if (cancelled != null) {
      data['cancelled'] = cancelled;
    }
    if (removed != null) {
      data['removed'] = removed;
    }
    return data;
  }
}
</code>```

UserReview.dart:

```<code>class UserReview {
  bool? showReview;

  UserReview({required this.showReview});

  UserReview.fromJson(Map<String, dynamic> json) {
    showReview = json['showReview'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['showReview'] = showReview;
    return data;
  }
}
</code>```

GameData.dart:

```<code>class GameData {
  late bool addFakePlayers;
  late bool hasBeenCancelled;
  late bool canAddPromoCode;
  late String cancellationDescription;
  late String cancellationMsg;
  late int cost;
  late int cur;
  late String currency;
  late String dateTime;
  late String description;
  late String durationMsg;
  late String expOrg;
  late String gameTypeMsg;
  late bool hostConfirmed;
  late String lid;
  late int maxPlayers;
  late List<String> messages;
  late String payAtPitchMessage;
  late String paymentType;
  late List<String> paymentsAllowed;
  Team? team1;
  Team? team2;
  late bool pub;
  late bool removalAllowed;
  late bool showHostConfirmButton;
  late bool spotEn;
  late String surl;
  late String title;

  GameData(
      {required this.addFakePlayers,
      required this.hasBeenCancelled,
      required this.canAddPromoCode,
      required this.cancellationDescription,
      required this.cancellationMsg,
      required this.cost,
      required this.cur,
      required this.currency,
      required this.dateTime,
      required this.description,
      required this.durationMsg,
      required this.expOrg,
      required this.gameTypeMsg,
      required this.hostConfirmed,
      required this.lid,
      required this.maxPlayers,
      required this.messages,
      required this.payAtPitchMessage,
      required this.paymentType,
      required this.paymentsAllowed,
      required this.team1,
      required this.team2,
      required this.pub,
      required this.removalAllowed,
      required this.showHostConfirmButton,
      required this.spotEn,
      required this.surl,
      required this.title});

  GameData.fromJson(Map<String, dynamic> json) {
    addFakePlayers = json['addFakePlayers'];
    hasBeenCancelled = json['can'];
    canAddPromoCode = json['canAddPromoCode'];
    cancellationDescription = json['canDes']['en'];
    cancellationMsg = json['canMes'];
    cost = json['cost'];
    cur = json['cur'];
    currency = json['currency'];
    dateTime = json['dat'];
    description = json['descriptions']['en'];
    durationMsg = json['dur'];
    expOrg = json['expOrg'];
    gameTypeMsg = json['gameTypes']['en'];
    hostConfirmed = json['hostConfirmed'];
    lid = json['lid'];
    maxPlayers = json['max'];
    messages.add(json['mes']);
    messages.add(json['mes1']);
    messages.add(json['mes2']);
    messages.add(json['mes3']);
    payAtPitchMessage = json['payAtPitchMessage']['en'];
    paymentType = json['paymentType'];
    paymentsAllowed = json['paymentsAllowed'].cast<String>();
    team1 = json['pla1'] != null ? Team.fromJson(json['pla1']) : null;
    team2 = json['pla2'] != null ? Team.fromJson(json['pla2']) : null;
    pub = json['pub'];
    removalAllowed = json['removalAllowed'];
    showHostConfirmButton = json['showHostConfirmButton'];
    spotEn = json['spotEn'];
    surl = json['surl'];
    title = json['title']['en'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['addFakePlayers'] = addFakePlayers;
    data['can'] = hasBeenCancelled;
    data['canAddPromoCode'] = canAddPromoCode;
    data['canDes'] = cancellationDescription;
    data['canMes'] = cancellationMsg;
    data['cost'] = cost;
    data['cur'] = cur;
    data['currency'] = currency;
    data['dat'] = dateTime;
    data['descriptions'] = description;
    data['dur'] = durationMsg;
    data['expOrg'] = expOrg;
    data['gameTypes'] = gameTypeMsg;
    data['hostConfirmed'] = hostConfirmed;
    data['lid'] = lid;
    data['max'] = maxPlayers;
    data['mes'] = messages.elementAt(0);
    data['mes1'] = messages.elementAt(1);
    data['mes2'] = messages.elementAt(2);
    data['mes3'] = messages.elementAt(3);
    data['payAtPitchMessage'] = payAtPitchMessage;
    data['paymentType'] = paymentType;
    data['paymentsAllowed'] = paymentsAllowed;
    data['pla1'] = team1?.toJson();
    data['pla2'] = team2?.toJson();
    data['pub'] = pub;
    data['removalAllowed'] = removalAllowed;
    data['showHostConfirmButton'] = showHostConfirmButton;
    data['spotEn'] = spotEn;
    data['surl'] = surl;
    data['title'] = title;
    return data;
  }
}
</code>```

Team.dart:

```<code>class Team {
  Map<String, Player> players;

  Team({required this.players});

  factory Team.fromJson(Map<String, dynamic> json) {
    Map<String, Player> _players = {};
    for (String key in json.keys) {
      _players[key] = Player.fromJson(json[key]);
    }
    return Team(players: _players);
  }

  Map<String, dynamic> toJson() {
    Map<String, dynamic> json = <String, dynamic>{};
    for (String key in players.keys) {
      json[key] = players[key];
    }
    return json;
  }
}
</code>```

Player.dart:

```<code>class PickUpGameItem extends StatefulWidget {
  final String gameId;

  const PickUpGameItem(this.gameId, [Key? key]) : super(key: key);

  @override
  _PickUpGameItemState createState() => _PickUpGameItemState();
}

class _PickUpGameItemState extends State<PickUpGameItem> {
  late StreamSubscription _pickUpGameDetailsStreamSub;
  PickUpGameDetails? gameDetails;

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

  @override
  void deactivate() {
    _pickUpGameDetailsStreamSub.cancel();
    super.deactivate();
  }

  void _setListeners() {
    _pickUpGameDetailsStreamSub = FirebaseDatabase()
        .reference()
        .child(
            '.../gamesDetailed/${widget.gameId}/')
        .onValue
        .listen((event) {
      final detailsJson = Map<String, dynamic>.from(event.snapshot.value);
      setState(() {
        gameDetails = PickUpGameDetails.fromJson(detailsJson);
        print(gameDetails.toString());
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      child: Row(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(8.0),
            child: const Image(
              fit: BoxFit.fill,
              width: 80.0,
              height: 80.0,
              image: AssetImage('assets/images/temp_city_img.jpg'),
            ),
          ),
          const SizedBox(
            width: 10,
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: const [
                Text(
                  'Lorem ipsum dolor sit amet this is a test ......................................',
                  style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.bold,
                      fontSize: 16),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                SizedBox(
                  height: 10,
                ),
                Text(
                  'Lorem ipsum dolor sit amet this is a test ......................................',
                  style: TextStyle(
                      color: Colors.grey,
                      fontWeight: FontWeight.normal,
                      fontSize: 14),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
          const SizedBox(
            width: 10,
          ),
          Flexible(
            flex: 0,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  'Football',
                  style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.bold,
                      fontSize: 16),
                ),
                const SizedBox(
                  height: 10,
                ),
                Row(
                  children: const [
                    Text(
                      '14/16',
                      style: TextStyle(
                          color: Colors.grey,
                          fontWeight: FontWeight.normal,
                          fontSize: 14),
                    ),
                    SizedBox(
                      width: 5,
                    ),
                    Icon(Icons.ac_unit)
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
</code>```0

答:
I found this.</p>
```<code>Map<String, dynamic> map = Map<String, dynamic>.from(snap.snapshot.value as Map<dynamic, dynamic>);
</code>```

Body:
I have a database in my Firebase Realtime database with children that look like this:

Here's the JSON that I receive in my Flutter app from my firebase call:

{
  "gameAnalytics" : {
    "log" : {
      "20210926073039AbMc4uSXywqpK9OcusSV" : {
        "cityID" : "newYork",
        "countryCode" : "USA",
        "gameID" : "20210927065000Upper90IndnewYofootbiGZYy",
        "gamePaymentMethod" : "payAtPitch",
        "players" : {
          "umZ5ezrtI6a3UoCDWFDc3hInoNA2" : {
            "pnam" : "Mario Rest",
            "url" : "https://i.ibb.co/blahblah.jpg"
          }
        },
        "sportID" : "football",
        "status" : {
          "202109261130395laHd8h77R" : "completing, send back",
          "20210926113039BcUQ8RdbHs" : "payAtPitch",
          "20210926113039Ck9JsD1uf1" : "playersAdded"
        },
        "timeAndDateString" : "20210926073039",
        "totalCost" : 999,
        "type" : "ADD",
        "userWhoAddedID" : "umZ5ezrtI6a3UoCDWFDc3hInoNA2",
        "wantsToBeOrganizer" : true
      },
      "202109261146540focIuCQRi3wNfSluvkl" : {
        "cityID" : "newYork",
        "countryCode" : "USA",
        "gameID" : "20210927065000Upper90IndnewYofootbiGZYy",
        "gamePaymentMethod" : "payByBalance",
        "players" : {
          "hOBQJtqCCNgGBVrAv2MqeaFJmdu1" : {
            "pnam" : "Seong Kang",
            "url" : "messi"
          }
        },
        "promoCodeData" : "U90qaL",
        "sportID" : "football",
        "status" : {
          "2021092615465414NXsxwW51" : "playersAdded",
          "20210926154654A60TLCmS2t" : "paidByBalance",
          "20210926154654VtYR1t4bMZ" : "completing, send back"
        },
        "timeAndDateString" : "20210926114654",
        "totalCost" : 0,
        "type" : "ADD",
        "userWhoAddedID" : "hOBQJtqCCNgGBVrAv2MqeaFJmdu1",
        "wantsToBeOrganizer" : false
      },
      "20210926204533DjF3lMCMDpvwHfsh6lQJ" : {
        "amountToRefund" : 0,
        "promoCodes" : {
          "hOBQJtqCCNgGBVrAv2MqeaFJmdu1" : "U90qaL"
        },
        "status" : {
          "20210927004533ZWGNEMX27V" : "REFUNDING: 0  null  hOBQJtqCCNgGBVrAv2MqeaFJmdu1"
        },
        "type" : "CANCEL",
        "userWhoAddedID" : "hOBQJtqCCNgGBVrAv2MqeaFJmdu1"
      }
    },
    "pitchCost" : 3500,
    "playerNumbers" : {
      "hoursBefore12" : 2,
      "hoursBefore24" : 1,
      "hoursBefore3" : 2,
      "hoursBefore36" : 1,
      "hoursBefore48" : 1,
      "hoursBefore6" : 2,
      "hoursBefore72" : 1,
      "hoursBefore96" : 1
    },
    "timings" : {
      "added" : {
        "20210917004938" : "organiserID12345",
        "20210926113040" : "umZ5ezrtI6a3UoCDWFDc3hInoNA2",
        "20210926154656" : "hOBQJtqCCNgGBVrAv2MqeaFJmdu1"
      },
      "cancelled" : {
        "20210917004939" : "playersUnCancelled",
        "20210927004522" : "playersCancelled"
      },
      "removed" : {
        "20210926113042" : "organiserID12345"
      }
    }
  },
  "gameData" : {
    "addFakePlayers" : false,
    "can" : true,
    "canAddPromoCode" : true,
    "canDes" : {
      "en" : "somedesc"
    },
    "canMes" : "blahblah.",
    "cost" : 999,
    "cur" : 2,
    "currency" : "usd",
    "dat" : "20210927065000",
    "descriptions" : {
      "en" : "blahblah"
    },
    "dur" : "60 minutes",
    "expOrg" : "",
    "gameTypes" : {
      "en" : "blahblah"
    },
    "hostConfirmed" : false,
    "hostInfo" : {
      "hostDescription" : "blahblah",
      "hostNickname" : "Mario R",
      "hostPhoto" : "https://i.ibb.co/blahblah.jpg",
      "isSuperHost" : false
    },
    "lid" : "Upper90IndoorQueensabcde739219515176663407563157034467ap0mr",
    "max" : 15,
    "mes" : "blahblah",
    "mes1" : "my disappointment",
    "mes2" : "is immessurable",
    "mes3" : "and my day",
    "payAtPitchMessage" : {
      "en" : "is ruined"
    },
    "paymentType" : "justOnline",
    "paymentsAllowed" : [ "card" ],
    "pla1" : {
      "hOBQJtqCCNgGBVrAv2MqeaFJmdu1" : {
        "pnam" : "blahblah",
        "url" : "messi"
      }
    },
    "pla2" : {
      "umZ5ezrtI6a3UoCDWFDc3hInoNA2" : {
        "organizer" : true,
        "pnam" : "Mario Rest",
        "url" : "https://i.ibb.co/blahblah.jpg"
      }
    },
    "pub" : false,
    "removalAllowed" : true,
    "showHostConfirmButton" : false,
    "spotEn" : true,
    "surl" : "https://someurl",
    "title" : {
      "en" : "ok"
    }
  },
  "mess" : {
    "-MjlDj5szZxKaDs0p3CN" : {
      "mes" : "ok",
      "tim" : "20210916204938",
      "unm" : "blahblah",
      "usi" : "XwyPhbjzeKNYVczPdCPFTG0DZbj1"
    },
    "-MjlDj6bnMvKUO76EjLE" : {
      "mes" : "ok",
      "tim" : "20210916204938",
      "unm" : "blahblah",
      "usi" : "XwyPhbjzeKNYVczPdCPFTG0DZbj1"
    },
    "-MjlDj7SeqRV0KzRzFFX" : {
      "mes" : "ok",
      "tim" : "20210916204939",
      "unm" : "bllblb",
      "usi" : "XwyPhbjzeKNYVczPdCPFTG0DZbj1"
    },
    "-MjlDj8C-p406IK8I-cb" : {
      "mes" : "msg",
      "tim" : "20210916204940",
      "unm" : "msg",
      "usi" : "XwyPhbjzeKNYVczPdCPFTG0DZbj1"
    }
  },
  "payment" : {
    "playerPaymentStatus" : {
      "hOBQJtqCCNgGBVrAv2MqeaFJmdu1" : {
        "date" : "20210927004533",
        "refundedAmount" : 0,
        "stripePaymentNotConfirmed" : true,
        "type" : "notPaidForGame",
        "userWhoAddedID" : "hOBQJtqCCNgGBVrAv2MqeaFJmdu1"
      }
    }
  },
  "userReview" : {
    "showReview" : true
  }
}

I'm trying to create a Map<String, dynamic> from this response by using Map<String,dynamic>.from() as seen below:

class PickUpGameItem extends StatefulWidget {
  final String gameId;

  const PickUpGameItem(this.gameId, [Key? key]) : super(key: key);

  @override
  _PickUpGameItemState createState() => _PickUpGameItemState();
}

class _PickUpGameItemState extends State<PickUpGameItem> {
  late StreamSubscription _pickUpGameDetailsStreamSub;
  PickUpGameDetails? gameDetails;

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

  @override
  void deactivate() {
    _pickUpGameDetailsStreamSub.cancel();
    super.deactivate();
  }

  void _setListeners() {
    _pickUpGameDetailsStreamSub = FirebaseDatabase()
        .reference()
        .child(
            '.../gamesDetailed/${widget.gameId}/')
        .onValue
        .listen((event) {
      final detailsJson = Map<String, dynamic>.from(event.snapshot.value);
      setState(() {
        gameDetails = PickUpGameDetails.fromJson(detailsJson);
        print(gameDetails.toString());
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      child: Row(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(8.0),
            child: const Image(
              fit: BoxFit.fill,
              width: 80.0,
              height: 80.0,
              image: AssetImage('assets/images/temp_city_img.jpg'),
            ),
          ),
          const SizedBox(
            width: 10,
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: const [
                Text(
                  'Lorem ipsum dolor sit amet this is a test ......................................',
                  style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.bold,
                      fontSize: 16),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                SizedBox(
                  height: 10,
                ),
                Text(
                  'Lorem ipsum dolor sit amet this is a test ......................................',
                  style: TextStyle(
                      color: Colors.grey,
                      fontWeight: FontWeight.normal,
                      fontSize: 14),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
          const SizedBox(
            width: 10,
          ),
          Flexible(
            flex: 0,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  'Football',
                  style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.bold,
                      fontSize: 16),
                ),
                const SizedBox(
                  height: 10,
                ),
                Row(
                  children: const [
                    Text(
                      '14/16',
                      style: TextStyle(
                          color: Colors.grey,
                          fontWeight: FontWeight.normal,
                          fontSize: 14),
                    ),
                    SizedBox(
                      width: 5,
                    ),
                    Icon(Icons.ac_unit)
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

When I run the app, I get an error saying that the internal linked hash map isn't a subtype of map and that the error occurs when calling GameAnalytics.fromJson(). I've seen multiple similar posts but their error mentioned an _InternalLinkedHashMap<String?, dynamic> map. Why Is this linked hash map in my response using Object? for both keys and values?

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>'

Here are my dart model classes:

PickUpGameDetails.dart:

class PickUpGameDetails {
  GameAnalytics? gameAnalytics;
  GameData? gameData;
  UserReview? userReview;

  PickUpGameDetails(
      {required this.gameAnalytics,
      required this.gameData,
      required this.userReview});

  PickUpGameDetails.fromJson(Map<String, dynamic> json) {
    gameAnalytics = json['gameAnalytics'] != null
        ? GameAnalytics.fromJson(json['gameAnalytics'])
        : null;
    gameData =
        json['gameData'] != null ? GameData.fromJson(json['gameData']) : null;
    userReview = json['userReview'] != null
        ? UserReview.fromJson(json['userReview'])
        : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (gameAnalytics != null) {
      data['gameAnalytics'] = gameAnalytics!.toJson();
    }
    if (gameData != null) {
      data['gameData'] = gameData!.toJson();
    }
    if (userReview != null) {
      data['userReview'] = userReview!.toJson();
    }
    return data;
  }
}

GameAnalytics.dart:

class GameAnalytics {
  late int pitchCost;
  PlayerNumbers? playerNumbers;
  Timings? timings;

  GameAnalytics(
      {required this.pitchCost,
      required this.playerNumbers,
      required this.timings});

  GameAnalytics.fromJson(Map<String, dynamic> json) {
    pitchCost = json['pitchCost'];
    playerNumbers = json['playerNumbers'] != null
        ? PlayerNumbers.fromJson(json['playerNumbers'])
        : null;
    timings =
        json['timings'] != null ? Timings.fromJson(json['timings']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['pitchCost'] = pitchCost;
    if (playerNumbers != null) {
      data['playerNumbers'] = playerNumbers!.toJson();
    }
    if (timings != null) {
      data['timings'] = timings!.toJson();
    }
    return data;
  }
}

PlayerNumbers.dart:

class PlayerNumbers {
  late int hoursBefore12;
  late int hoursBefore24;
  late int hoursBefore3;
  late int hoursBefore36;
  late int hoursBefore48;
  late int hoursBefore6;
  late int hoursBefore72;
  late int hoursBefore96;

  PlayerNumbers(
      {required this.hoursBefore12,
      required this.hoursBefore24,
      required this.hoursBefore3,
      required this.hoursBefore36,
      required this.hoursBefore48,
      required this.hoursBefore6,
      required this.hoursBefore72,
      required this.hoursBefore96});

  PlayerNumbers.fromJson(Map<String, dynamic> json) {
    hoursBefore12 = json['hoursBefore12'];
    hoursBefore24 = json['hoursBefore24'];
    hoursBefore3 = json['hoursBefore3'];
    hoursBefore36 = json['hoursBefore36'];
    hoursBefore48 = json['hoursBefore48'];
    hoursBefore6 = json['hoursBefore6'];
    hoursBefore72 = json['hoursBefore72'];
    hoursBefore96 = json['hoursBefore96'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['hoursBefore12'] = hoursBefore12;
    data['hoursBefore24'] = hoursBefore24;
    data['hoursBefore3'] = hoursBefore3;
    data['hoursBefore36'] = hoursBefore36;
    data['hoursBefore48'] = hoursBefore48;
    data['hoursBefore6'] = hoursBefore6;
    data['hoursBefore72'] = hoursBefore72;
    data['hoursBefore96'] = hoursBefore96;
    return data;
  }
}

Timings.dart:

class Timings {
  Map<String, dynamic>? added;
  Map<String, dynamic>? cancelled;
  Map<String, dynamic>? removed;

  Timings(
      {required this.added, required this.cancelled, required this.removed});

  Timings.fromJson(Map<String, dynamic> json) {
    added = json['added'];
    cancelled = json['cancelled'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    if (added != null) {
      data['added'] = added;
    }
    if (cancelled != null) {
      data['cancelled'] = cancelled;
    }
    if (removed != null) {
      data['removed'] = removed;
    }
    return data;
  }
}

UserReview.dart:

class UserReview {
  bool? showReview;

  UserReview({required this.showReview});

  UserReview.fromJson(Map<String, dynamic> json) {
    showReview = json['showReview'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['showReview'] = showReview;
    return data;
  }
}

GameData.dart:

class GameData {
  late bool addFakePlayers;
  late bool hasBeenCancelled;
  late bool canAddPromoCode;
  late String cancellationDescription;
  late String cancellationMsg;
  late int cost;
  late int cur;
  late String currency;
  late String dateTime;
  late String description;
  late String durationMsg;
  late String expOrg;
  late String gameTypeMsg;
  late bool hostConfirmed;
  late String lid;
  late int maxPlayers;
  late List<String> messages;
  late String payAtPitchMessage;
  late String paymentType;
  late List<String> paymentsAllowed;
  Team? team1;
  Team? team2;
  late bool pub;
  late bool removalAllowed;
  late bool showHostConfirmButton;
  late bool spotEn;
  late String surl;
  late String title;

  GameData(
      {required this.addFakePlayers,
      required this.hasBeenCancelled,
      required this.canAddPromoCode,
      required this.cancellationDescription,
      required this.cancellationMsg,
      required this.cost,
      required this.cur,
      required this.currency,
      required this.dateTime,
      required this.description,
      required this.durationMsg,
      required this.expOrg,
      required this.gameTypeMsg,
      required this.hostConfirmed,
      required this.lid,
      required this.maxPlayers,
      required this.messages,
      required this.payAtPitchMessage,
      required this.paymentType,
      required this.paymentsAllowed,
      required this.team1,
      required this.team2,
      required this.pub,
      required this.removalAllowed,
      required this.showHostConfirmButton,
      required this.spotEn,
      required this.surl,
      required this.title});

  GameData.fromJson(Map<String, dynamic> json) {
    addFakePlayers = json['addFakePlayers'];
    hasBeenCancelled = json['can'];
    canAddPromoCode = json['canAddPromoCode'];
    cancellationDescription = json['canDes']['en'];
    cancellationMsg = json['canMes'];
    cost = json['cost'];
    cur = json['cur'];
    currency = json['currency'];
    dateTime = json['dat'];
    description = json['descriptions']['en'];
    durationMsg = json['dur'];
    expOrg = json['expOrg'];
    gameTypeMsg = json['gameTypes']['en'];
    hostConfirmed = json['hostConfirmed'];
    lid = json['lid'];
    maxPlayers = json['max'];
    messages.add(json['mes']);
    messages.add(json['mes1']);
    messages.add(json['mes2']);
    messages.add(json['mes3']);
    payAtPitchMessage = json['payAtPitchMessage']['en'];
    paymentType = json['paymentType'];
    paymentsAllowed = json['paymentsAllowed'].cast<String>();
    team1 = json['pla1'] != null ? Team.fromJson(json['pla1']) : null;
    team2 = json['pla2'] != null ? Team.fromJson(json['pla2']) : null;
    pub = json['pub'];
    removalAllowed = json['removalAllowed'];
    showHostConfirmButton = json['showHostConfirmButton'];
    spotEn = json['spotEn'];
    surl = json['surl'];
    title = json['title']['en'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['addFakePlayers'] = addFakePlayers;
    data['can'] = hasBeenCancelled;
    data['canAddPromoCode'] = canAddPromoCode;
    data['canDes'] = cancellationDescription;
    data['canMes'] = cancellationMsg;
    data['cost'] = cost;
    data['cur'] = cur;
    data['currency'] = currency;
    data['dat'] = dateTime;
    data['descriptions'] = description;
    data['dur'] = durationMsg;
    data['expOrg'] = expOrg;
    data['gameTypes'] = gameTypeMsg;
    data['hostConfirmed'] = hostConfirmed;
    data['lid'] = lid;
    data['max'] = maxPlayers;
    data['mes'] = messages.elementAt(0);
    data['mes1'] = messages.elementAt(1);
    data['mes2'] = messages.elementAt(2);
    data['mes3'] = messages.elementAt(3);
    data['payAtPitchMessage'] = payAtPitchMessage;
    data['paymentType'] = paymentType;
    data['paymentsAllowed'] = paymentsAllowed;
    data['pla1'] = team1?.toJson();
    data['pla2'] = team2?.toJson();
    data['pub'] = pub;
    data['removalAllowed'] = removalAllowed;
    data['showHostConfirmButton'] = showHostConfirmButton;
    data['spotEn'] = spotEn;
    data['surl'] = surl;
    data['title'] = title;
    return data;
  }
}

Team.dart:

class Team {
  Map<String, Player> players;

  Team({required this.players});

  factory Team.fromJson(Map<String, dynamic> json) {
    Map<String, Player> _players = {};
    for (String key in json.keys) {
      _players[key] = Player.fromJson(json[key]);
    }
    return Team(players: _players);
  }

  Map<String, dynamic> toJson() {
    Map<String, dynamic> json = <String, dynamic>{};
    for (String key in players.keys) {
      json[key] = players[key];
    }
    return json;
  }
}

Player.dart:

class Player {
  String name;
  String url;

  Player({required this.name, required this.url});

  factory Player.fromJson(Map<String, dynamic> json) {
    return Player(name: json['pname'], url: json['url']);
  }

  Map<String, dynamic> toJson() {
    final json = <String, dynamic>{};
    json['pname'] = name;
    json['url'] = url;
    return json;
  }
}

Body:
I found this.

Map<String, dynamic> map = Map<String, dynamic>.from(snap.snapshot.value as Map<dynamic, dynamic>);


来源: stackexchange

问:
Cannot remove padding from Android Material slider
I've created a slider and I want to remove the padding. It seem it's not possible. I know there is some padding necessary for the thump, but I'd like to take care of the padding myself.

```<code>        <com.google.android.material.slider.Slider
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="0dp" />
</code>```

Even with setting padding to 0 it still shows some padding. It seems the padding parameter is ignored. It also seems the thumb diameter is not taken into account for the padding.

image taken from layout inspector

How can I set the padding? What if I want a real big thumb diameter?

答:
all dimensions is here

you can override all of them in your project dimens.xml

ContentLicense: CC BY-SA 4.0

Body:
I've created a slider and I want to remove the padding. It seem it's not possible. I know there is some padding necessary for the thump, but I'd like to take care of the padding myself.

        <com.google.android.material.slider.Slider
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="0dp" />

Even with setting padding to 0 it still shows some padding. It seems the padding parameter is ignored. It also seems the thumb diameter is not taken into account for the padding.

image taken from layout inspector

How can I set the padding? What if I want a real big thumb diameter?


问:
Flutter Debug: Warning: CocoaPods not installed. Skipping pod install
my problem is this:

I want to connect my app to Firebase. I followed all the steps and did everything according to the instructions. When I tried to debug the app, the following error came up:

When I enter - flutter run - from the terminal, the following happens:

In flutter doctor -v the following comes out:

[✓] Flutter (Channel stable, 1.20.4, on macOS 11.2 20D64, locale de)
• Flutter version 1.20.4 at /Users/danielalakin/development/flutter
• Framework revision fba99f6cf9 (5 months ago), 2020-09-14 15:32:52 -0700
• Engine revision d1bc06f032
• Dart version 2.9.2

[✓] Android toolchain - develop for Android devices (Android SDK
version 30.0.2)
• Android SDK at /Users/danielalakin/Library/Android/sdk
• Platform android-30, build-tools 30.0.2
• Java binary at: /Applications/Android
Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build
1.8.0_242-release-1644-b3-6222593)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.4)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 12.4, Build version 12D4e
• CocoaPods version 1.10.1

[!] Android Studio (version 4.1)
• Android Studio at /Applications/Android Studio.app/Contents
✗ Flutter plugin not installed; this adds Flutter specific functionality.
✗ Dart plugin not installed; this adds Dart specific functionality.
• Java version OpenJDK Runtime Environment (build
1.8.0_242-release-1644-b3-6222593)

[✓] VS Code (version 1.52.1)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.19.0

[✓] Connected device (1 available)
• iPhone 12 Pro Max (mobile) • C0991E0B-425B-46BD-9DEA-674181136D99 • ios •
com.apple.CoreSimulator.SimRuntime.iOS-14-4 (simulator)

And I have the following versions and paths:

$ pod --version:
1.10.1

$ which pod:
/usr/local/bin/pod

$ which gem:
/Users/danielalakin/.rvm/rubies/ruby-3.0.0/bin/gem

$ which ruby:
/Users/danielalakin/.rvm/rubies/ruby-3.0.0/bin/ruby

Do you know how I can solve this problem?

PS: I work on Visual Studio Code and XCode. I use MacOS Big Sur Version 11.2.

答:
For me none of these was helpful,
The workaround was opening the Android studio using Terminal rather than GUI

open /Applications/Android\ Studio.app

After that, I can use GUI and there was no problem :)!

you can find more info here:

https://github.com/flutter/flutter-intellij/issues/4981#issuecomment-751443625


问:
cannot update identity column in Entity Framework Core
I've added a separate Identification to the AspNetUsers table called NumericId that will serve along with the GUID like ID that ASP has for default.

I've added the property as an additional property of the ApplicationUser class:

```<code>public class ApplicationUser : IdentityUser
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int NumericId { get; set; }
}
</code>```

However, when I try to register, or update the user's details (that aren't even relevant to the numericId) I keep getting the error

```<code>SqlException: Cannot update identity column 'NumericId'.
</code>```

which prevents any changes and in the end does not update the user (but it does register one, and Numeric Id is properly assigned on that part. But this is irrelevant)

答:
Solution for asp.net core 5 EF 5</p>
```<code>modelBuilder.Entity<Type>().Property(u => u.Property).ValueGeneratedOnUpdate().Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've added a separate Identification to the AspNetUsers table called NumericId that will serve along with the GUID like ID that ASP has for default.

I've added the property as an additional property of the ApplicationUser class:

public class ApplicationUser : IdentityUser
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int NumericId { get; set; }
}

However, when I try to register, or update the user's details (that aren't even relevant to the numericId) I keep getting the error

SqlException: Cannot update identity column 'NumericId'.

which prevents any changes and in the end does not update the user (but it does register one, and Numeric Id is properly assigned on that part. But this is irrelevant)

Body:
Solution for asp.net core 5 EF 5

modelBuilder.Entity<Type>().Property(u => u.Property).ValueGeneratedOnUpdate().Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);


问:
GitHub Action: Ignore tag trigger completely stops the pipeline
Except a tag stated with v pushed to the branch, all other action shall start the pipeline

Here is my code

```<code>on:
  push:
    tags-ignore:
      - "v*"
  pull_request:
    tags-ignore:
      - "v*"
</code>```

Why its stops everything? When I push anything to the branch, nothing is happing with my pipeline

答:
It all works as expected, here is an example

I think you may have a problem of branches versus workflows.

Usually you push all workflows in master branches - that's fine.

But for all existing branches it won't work - if workflow doesn't exist on certain branch, it won't be triggered for it.
You have to either rebase branches on top of master or cherry pick a commit with your workflow to make it work.

Body:
Except a tag stated with v pushed to the branch, all other action shall start the pipeline

Here is my code

on:
  push:
    tags-ignore:
      - "v*"
  pull_request:
    tags-ignore:
      - "v*"

Why its stops everything? When I push anything to the branch, nothing is happing with my pipeline


问:
Getting error in console Uncaught ReferenceError: arguments is not defined after upgrading the webpack 4 to webpack 5
Getting error in console Uncaught ReferenceError: arguments is not defined after upgrading the webpack 4 to webpack 5. This arguments is in debounce funtion

答:
The debounce function you have here is an arrow function which doesn't have arguments.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Which leads to this issue.


问:
How do I hide the bottom console text output area in Sublime Text 3?
This is probably really simple, but it's frustrating me so much. I'm using Sublime Text 3. Sometimes my plugins output code to a little window at the bottom like this:

And I can't hide it no matter what I try. The only way I can get rid of it is by closing the program and opening it again. Does anyone know how to close this?

答: In my case, Esc button is working to remove the side bar(terminal/console bar).</p>


问:
using expo and @react-native-community/async-storage
I'm using expo to build and bundle my app. I've added @react-native-async-storage/async-storage but I get the following error on console:

```<code>Failed building JavaScript bundle.
Unable to resolve "@react-native-async-storage/async-storage" from "src/components/Message/Message.js"
</code>```

my device also show multiple steps that might help to solve it as can be seen here

but unfortunately it didn't solve it.
I also tried:

to clean expo cache folder from ~/.expo/

remove-re-install the Expo Client app

clear the metro bundler cache in /tmp folder

I must say that when checking the node_modules folder, I've noticed that the package is installed under @react-native-community folder and not under @react-native-async-storage - but I can't be sure how those links magically happening under the hood, but maybe it worth to mention.

I saw in @react-native-async-storage/async-storage docs that I need to run another pod install command but In expo the platform-specific folder is not accisible and the command runs without doing anything. Moreover, I've conducted expo snack example but it functions properly. So probably something in my env or missing some configuration?

Any ideas?

Env details:

"expo": "^38.0.0",
"expo-cli": "3.27.6",
"react-native": "https://github.com/expo/react-native/archive/sdk-38.0.2.tar.gz",
"@react-native-community/async-storage": "~1.11.0",
```

答:
If you're running expo using:

expo start --dev-client

You likely need to rebuild your dev client.

If you're running using Expo GO it'll be linked automatically:

expo start

Body:
I'm using expo to build and bundle my app. I've added @react-native-async-storage/async-storage but I get the following error on console:

Failed building JavaScript bundle.
Unable to resolve "@react-native-async-storage/async-storage" from "src/components/Message/Message.js"

my device also show multiple steps that might help to solve it as can be seen here

but unfortunately it didn't solve it.
I also tried:

to clean expo cache folder from ~/.expo/

remove-re-install the Expo Client app

clear the metro bundler cache in /tmp folder

I must say that when checking the node_modules folder, I've noticed that the package is installed under @react-native-community folder and not under @react-native-async-storage - but I can't be sure how those links magically happening under the hood, but maybe it worth to mention.

I saw in @react-native-async-storage/async-storage docs that I need to run another pod install command but In expo the platform-specific folder is not accisible and the command runs without doing anything. Moreover, I've conducted expo snack example but it functions properly. So probably something in my env or missing some configuration?

Any ideas?

Env details:

"expo": "^38.0.0",
"expo-cli": "3.27.6",
"react-native": "https://github.com/expo/react-native/archive/sdk-38.0.2.tar.gz",
"@react-native-community/async-storage": "~1.11.0",


问:
Refreshing all the pivot tables in my excel workbook with a macro
I have a workbook with 20 different pivot tables. Is there any easy way to find all the pivot tables and refresh them in VBA?</p>

答:
This VBA code will refresh all pivot tables/charts in the workbook.

```<code>Sub RefreshAllPivotTables()

Dim PT As PivotTable
Dim WS As Worksheet

    For Each WS In ThisWorkbook.Worksheets

        For Each PT In WS.PivotTables
          PT.RefreshTable
        Next PT

    Next WS

End Sub
</code>```

Another non-programatic option is:

Right click on each pivot table

Select Table options

Tick the 'Refresh on open' option.

Click on the OK button

This will refresh the pivot table each time the workbook is opened.

OwnerDisplayName: Lipis

LastEditorDisplayName: Luke Girvin

Body:
This VBA code will refresh all pivot tables/charts in the workbook.

Sub RefreshAllPivotTables()

Dim PT As PivotTable
Dim WS As Worksheet

    For Each WS In ThisWorkbook.Worksheets

        For Each PT In WS.PivotTables
          PT.RefreshTable
        Next PT

    Next WS

End Sub

Another non-programatic option is:

Right click on each pivot table

Select Table options

Tick the 'Refresh on open' option.

Click on the OK button

This will refresh the pivot table each time the workbook is opened.

OwnerDisplayName: Robert Mearns

ContentLicense: CC BY-SA 2.5


问:
How change the color of rulers in Visual Studio Code
Not sure if this feature is included in the VSCode settings yet, but I'd love to change the ruler color from it's default grey.

Tried:

```<code>"editor.rulers.color": "color"
</code>```

But got an "unknown configuration setting error.

答:
File -> Preferences -> Settings Or cntrl+,

type "rulers" and click Edit Setings.json

3. Add the size value by ',' As you wish

```<code> "workbench.colorCustomizations": {
    "editorRuler.foreground": "#0ddf73"
  },
</code>```

Like this(Gif)

Body:
Not sure if this feature is included in the VSCode settings yet, but I'd love to change the ruler color from it's default grey.

Tried:

"editor.rulers.color": "color"

But got an "unknown configuration setting error.

Body:
File -> Preferences -> Settings Or cntrl+,

type "rulers" and click Edit Setings.json

3. Add the size value by ',' As you wish

 "workbench.colorCustomizations": {
    "editorRuler.foreground": "#0ddf73"
  },

Like this(Gif)


问:
Missing a message from TCPClient
I am new into Python and socket programming. This is my TCPClient code.

```<code>from socket import *
serverName = 'localhost'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)

clientSocket.connect((serverName, serverPort))

sentence = input('Input lowercase sentence :')
clientSocket.send(sentence.encode())
modifiedSentence = clientSocket.recv(1024)

print('From server', modifiedSentence.decode())

clientSocket.close()
</code>```

The message that should be displayed when I run the code should be :

Input lowercase sentence : message  (example sentence)

From server MESSAGE

But only 1. was displayed, 2. wasnt even there.

Can someone point out my mistake?

This is my TPCServer code anyway.

```<code>from socket import *
serverName = 'localhost'
serverPort = 12000

serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((serverName, serverPort))

serverSocket.listen(1)

print('The server is ready to receive.')

while True:
    connectionSocket, addr = serverSocket.accept()
    sentence = connectionSocket.recv(1024)
</code>```

答:
Server side:

```<code>from socket import *
serverName = 'localhost'
serverPort = 12000

serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((serverName, serverPort))

serverSocket.listen(1)

print('The server is ready to receive.')

while True:
    connectionSocket, addr = serverSocket.accept()
    sentence = connectionSocket.recv(1024)
    if sentence:
        print(sentence.decode())
        sentence = sentence.upper()
        print(sentence)
        connectionSocket.send(sentence)
</code>```

Client side:

```<code>from socket import *
serverName = 'localhost'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)

clientSocket.connect((serverName, serverPort))

sentence = input('Input lowercase sentence :')
clientSocket.send(sentence.encode())
modifiedSentence = clientSocket.recv(1024)

print('From server', modifiedSentence.decode())

clientSocket.close()
</code>```

This will output to the client:

```<code>Input lowercase sentence :teste
From server TESTE
</code>```

Title: Missing a message from TCPClient

Body:
I am new into Python and socket programming. This is my TCPClient code.

from socket import *
serverName = 'localhost'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)

clientSocket.connect((serverName, serverPort))

sentence = input('Input lowercase sentence :')
clientSocket.send(sentence.encode())
modifiedSentence = clientSocket.recv(1024)

print('From server', modifiedSentence.decode())

clientSocket.close()

The message that should be displayed when I run the code should be :

Input lowercase sentence : message  (example sentence)

From server MESSAGE

But only 1. was displayed, 2. wasnt even there.

Can someone point out my mistake?

This is my TPCServer code anyway.

from socket import *
serverName = 'localhost'
serverPort = 12000

serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((serverName, serverPort))

serverSocket.listen(1)

print('The server is ready to receive.')

while True:
    connectionSocket, addr = serverSocket.accept()
    sentence = connectionSocket.recv(1024)

Body:
Server side:

from socket import *
serverName = 'localhost'
serverPort = 12000

serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((serverName, serverPort))

serverSocket.listen(1)

print('The server is ready to receive.')

while True:
    connectionSocket, addr = serverSocket.accept()
    sentence = connectionSocket.recv(1024)
    if sentence:
        print(sentence.decode())
        sentence = sentence.upper()
        print(sentence)
        connectionSocket.send(sentence)

Client side:

from socket import *
serverName = 'localhost'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)

clientSocket.connect((serverName, serverPort))

sentence = input('Input lowercase sentence :')
clientSocket.send(sentence.encode())
modifiedSentence = clientSocket.recv(1024)

print('From server', modifiedSentence.decode())

clientSocket.close()

This will output to the client:

Input lowercase sentence :teste
From server TESTE


问:
In the Django REST framework, how are the default permission classes combined with per-view(set) ones?
I'm reading http://www.django-rest-framework.org/api-guide/permissions/ and trying to relate it to the OAuth2 toolkit documentation, http://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html. The latter has an example in which in settings.py one specifies

```<code>REST_FRAMEWORK = {
    # ...

    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}
</code>```

and in addition, IsAuthenticated is also specified added to the permission_classes list of a ModelViewSet:

```<code>class UserViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    queryset = User.objects.all()
    serializer_class = UserSerializer
</code>```

Do I infer correctly from this example that the DEFAULT_PERMISSION_CLASSES are not prepended / postpended to a ModelViewSet's permission classes, but are instead replaced by it?

答:
If you do want to extend the default permissions, this seems to work.

Disclaimer: I found it by looking into DRF's code, not sure it is documented.

from rest_framework.settings import api_settings

class UserViewSet(viewsets.ModelViewSet):
    permission_classes = [*api_settings.DEFAULT_PERMISSION_CLASSES, TokenHasReadWriteScope]
```

Body:
I'm reading http://www.django-rest-framework.org/api-guide/permissions/ and trying to relate it to the OAuth2 toolkit documentation, http://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html. The latter has an example in which in settings.py one specifies

REST_FRAMEWORK = {
    # ...

    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

and in addition, IsAuthenticated is also specified added to the permission_classes list of a ModelViewSet:

class UserViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    queryset = User.objects.all()
    serializer_class = UserSerializer

Do I infer correctly from this example that the DEFAULT_PERMISSION_CLASSES are not prepended / postpended to a ModelViewSet's permission classes, but are instead replaced by it?


问:
What happens if you inline a function that calls it self in C++
First I thought the compile time would take forever, or I take a weird error, but that didn't happen. The code runs for a while and then crashes.

This is my code:

#include <iostream>

inline void say_hello()
{
    std::cout << "hello\n";
    say_hello();
}

int main()
{
    say_hello();
}

```
<p>I thought the compiler will convert it to something like this:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>

int main()
{
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    // and crash because my storage is filled
}
</code>```

But, I think the compiler ignored the inline keyword.

答:
In modern C++, the inline specifier is only a suggestion to the compiler that you might want to inline the function. The compiler is not required to comply.

For your specific compiler, please see Visual Studio Inline Functions (C++). You seem to "want" the __forceinline decorator combined with #pragma inline_recursion(on). This will inline to a depth of 16, but that is modifiable as well. I hope it's obvious why this is all a bad idea. Note that this is ALL compiler specific and does not apply to gcc.

__forceinline can fail for a variety of reasons, but the ones that might apply to you:

the function is recursive (what you have) and #pragma inline_recursion(on) is not set

the program is compiled with /Ob0 (the default for debug builds, which you might have set)

If you want to recurse to a level different than 16 (the default), you can use the inline_depth pragma to specify.

Your function would end up looking like this (untested):

```<code>#include <iostream>

#pragma inline_depth(9000)
#pragma inline_recursion(on)
__forceinline void say_hello()
{
    std::cout << "hello\n";
    say_hello();
}

int main()
{
    say_hello();
}
</code>```

Body:
First I thought the compile time would take forever, or I take a weird error, but that didn't happen. The code runs for a while and then crashes.

This is my code:

#include <iostream>

inline void say_hello()
{
    std::cout << "hello\n";
    say_hello();
}

int main()
{
    say_hello();
}

I thought the compiler will convert it to something like this:

#include <iostream>

int main()
{
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    std::cout << "hello\n";
    // and crash because my storage is filled
}

But, I think the compiler ignored the inline keyword.

Body:
In modern C++, the inline specifier is only a suggestion to the compiler that you might want to inline the function. The compiler is not required to comply.

For your specific compiler, please see Visual Studio Inline Functions (C++). You seem to "want" the __forceinline decorator combined with #pragma inline_recursion(on). This will inline to a depth of 16, but that is modifiable as well. I hope it's obvious why this is all a bad idea. Note that this is ALL compiler specific and does not apply to gcc.

__forceinline can fail for a variety of reasons, but the ones that might apply to you:

the function is recursive (what you have) and #pragma inline_recursion(on) is not set

the program is compiled with /Ob0 (the default for debug builds, which you might have set)

If you want to recurse to a level different than 16 (the default), you can use the inline_depth pragma to specify.

Your function would end up looking like this (untested):

#include <iostream>

#pragma inline_depth(9000)
#pragma inline_recursion(on)
__forceinline void say_hello()
{
    std::cout << "hello\n";
    say_hello();
}

int main()
{
    say_hello();
}


问:
PHP SOAP Randomly Fails as "Could not connect to host" after working for days/hours
We have three web applications, on separate servers with unique inteneral/external IP addresses.  Each server is running Windows Server 2016, IIS, and PHP 7.x via FastCGI.

We're connecting to two different remote SOAP APIs from each of these web applications -- service A and service B. Since January 25th, we've been having random issues with service "A".  Once or twice a day, for about an hour, we will get a SOAP Exception of "Could not connect to host".

I understand what that message means, but I'm unsure of why it is randomly happening -- server A will have the issue, but servers B and C will connect without an issue.  And then the issue will resolve itself on server A, and then server C will start throwing SOAP exceptions later in the day.  Rebooting the server will also immediately fix the issue.

Unfortunately I don't have any access to the firewalls in front of SOAP service A, so  I can't say if its restricting connections because there are too many requests coming from a single IP, or if our requests are being dropped for another reason, or if they're even making it there.

We're trying a few different things today such as hardcoding the IP address to web service A, switching DNS providers, and doing some additional monitoring... but I've never had this issue with SOAP-heavy services in the past.

答:
Meh. We thought we'd eliminated DNS issues, but apparently not.

The webserver was using the datacenter's DNS servers, but somehow it would occasionally use the client's internal DNS servers... so the IP address of the webservice was changing at random times.


问:
HTML chart display issue - move the chart inside of the card
I used the "Range Selector plugin" to create a line chart with the date selector.

The following codes are in my HTML file:

```<code><script src="https://cdn.amcharts.com/lib/4/core.js"></script>
<script src="https://cdn.amcharts.com/lib/4/charts.js"></script>
<script src="https://cdn.amcharts.com/lib/4/themes/animated.js"></script>
<script src="https://cdn.amcharts.com/lib/4/plugins/rangeSelector.js"></script>
<div id="chartdiv"></div>
<div id="selectordiv"></div>

 <div class="card shadow mb-4">
   <div class="card-header py-3">
     <h6 class="m-0 font-weight-bold text-primary">Area Chart</h6>
   </div>
   <div class="card-body">
    <div class="chart-line">
     <canvas id="chart"></canvas>
<script> var chart = am4core.create("chartdiv", am4charts.XYChart);
chart.paddingRight = 20;

var data = [];
var visits = 10;
for (var i = 1; i < 50000; i++) {
  visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
  data.push({ date: new Date(2018, 0, i), value: visits });
}

chart.data = data;

var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0;
dateAxis.minZoomCount = 5;

dateAxis.groupData = true;
dateAxis.groupCount = 500;

var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.dateX = "date";
series.dataFields.valueY = "value";
series.tooltipText = "{valueY}";
series.tooltip.pointerOrientation = "vertical";
series.tooltip.background.fillOpacity = 0.5;

chart.cursor = new am4charts.XYCursor();
chart.cursor.xAxis = dateAxis;

var scrollbarX = new am4core.Scrollbar();
scrollbarX.marginBottom = 20;
chart.scrollbarX = scrollbarX;

var selector = new am4plugins_rangeSelector.DateAxisRangeSelector();
selector.container = document.getElementById("selectordiv");
selector.axis = dateAxis;

</script>
      </div>
         </div>
           </div>
</code>```

But my chart doesn't display properly. It is outside of the card:

Please advise what I should adjust to move the chart inside of the card

答:
You need to move your #chartdiv element inside the area chart card body.  I have tried to do this with the HTML you supplied but it seems to be missing some CSS.  I've managed to get it working though:

var chart = am4core.create("chartdiv", am4charts.XYChart);
chart.paddingRight = 20;

var data = [];
var visits = 10;
for (var i = 1; i < 50000; i++) {
  visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
  data.push({
    date: new Date(2018, 0, i),
    value: visits
  });
}

chart.data = data;

var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0;
dateAxis.minZoomCount = 5;

dateAxis.groupData = true;
dateAxis.groupCount = 500;

var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.dateX = "date";
series.dataFields.valueY = "value";
series.tooltipText = "{valueY}";
series.tooltip.pointerOrientation = "vertical";
series.tooltip.background.fillOpacity = 0.5;

chart.cursor = new am4charts.XYCursor();
chart.cursor.xAxis = dateAxis;

var scrollbarX = new am4core.Scrollbar();
scrollbarX.marginBottom = 20;
chart.scrollbarX = scrollbarX;

var selector = new am4plugins_rangeSelector.DateAxisRangeSelector();
selector.container = document.getElementById("selectordiv");
selector.axis = dateAxis;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#chartdiv {
  height: 500px;
}</code>```

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

Area Chart

```

Body:
I used the "Range Selector plugin" to create a line chart with the date selector.

The following codes are in my HTML file:

Area Chart

     <canvas id="chart"></canvas>

But my chart doesn't display properly. It is outside of the card:

Please advise what I should adjust to move the chart inside of the card

Body:
You need to move your #chartdiv element inside the area chart card body.  I have tried to do this with the HTML you supplied but it seems to be missing some CSS.  I've managed to get it working though:

var chart = am4core.create("chartdiv", am4charts.XYChart);
chart.paddingRight = 20;

var data = [];
var visits = 10;
for (var i = 1; i < 50000; i++) {
  visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
  data.push({
    date: new Date(2018, 0, i),
    value: visits
  });
}

chart.data = data;

var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0;
dateAxis.minZoomCount = 5;

dateAxis.groupData = true;
dateAxis.groupCount = 500;

var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.dateX = "date";
series.dataFields.valueY = "value";
series.tooltipText = "{valueY}";
series.tooltip.pointerOrientation = "vertical";
series.tooltip.background.fillOpacity = 0.5;

chart.cursor = new am4charts.XYCursor();
chart.cursor.xAxis = dateAxis;

var scrollbarX = new am4core.Scrollbar();
scrollbarX.marginBottom = 20;
chart.scrollbarX = scrollbarX;

var selector = new am4plugins_rangeSelector.DateAxisRangeSelector();
selector.container = document.getElementById("selectordiv");
selector.axis = dateAxis;

#chartdiv {
  height: 500px;
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div id="selectordiv"></div>
<div class="card shadow mb-4">
  <div class="card-header py-3">
    <h6 class="m-0 font-weight-bold text-primary">Area Chart</h6>
  </div>
  <div class="card-body">
    <div class="chart-line">
      <div id="chartdiv"></div>
    </div>
  </div>
</div>
<script src="https://cdn.amcharts.com/lib/4/core.js"></script>
<script src="https://cdn.amcharts.com/lib/4/charts.js"></script>
<script src="https://cdn.amcharts.com/lib/4/themes/animated.js"></script>
<script src="https://cdn.amcharts.com/lib/4/plugins/rangeSelector.js"></script>


问:
Uncaught TypeError: equipo.data is undefined using React
I have the following problem trying to traverse an array of objects and I don't know where the problem is.

```<code>import './App.css';
import React from 'react';

function App() {

  const [equipo, setEquipo] = React.useState([]);

  // Constructor
  React.useEffect(() => {
    document.title = "Magic - React";
    obtenerDatos();
  }, []);

  // Metodo que recoge info de una Api
  const obtenerDatos = async () => {
    const data = await fetch("https://api.scryfall.com/cards/search?order=set&q=e%3Augin&unique=prints");
    const info = await data.json();
    setEquipo(info);
  };

  return (
    <div className="App">
      <ul>
        {equipo.data.map((item) => (
          <li>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;
</code>```

Here is the JSON Api where I search the info.

https://api.scryfall.com/cards/search?order=set&q=e%3Augin&unique=prints

I try to show the images and the text of the cards in the HTML. I am new with React. Please help and thanks.

答:
Try this:</p>
```<code>return (
    <div className="App">
      <ul>
        {equipo?.data?.map((item) => (
          <li>{item.name}</li>
        ))}
      </ul>
    </div>
  );
</code>```

Body:
I have the following problem trying to traverse an array of objects and I don't know where the problem is.

import './App.css';
import React from 'react';

function App() {

  const [equipo, setEquipo] = React.useState([]);

  // Constructor
  React.useEffect(() => {
    document.title = "Magic - React";
    obtenerDatos();
  }, []);

  // Metodo que recoge info de una Api
  const obtenerDatos = async () => {
    const data = await fetch("https://api.scryfall.com/cards/search?order=set&q=e%3Augin&unique=prints");
    const info = await data.json();
    setEquipo(info);
  };

  return (

        {equipo.data.map((item) => (

{item.name}

        ))}

  );
}

export default App;

Here is the JSON Api where I search the info.

https://api.scryfall.com/cards/search?order=set&q=e%3Augin&unique=prints

I try to show the images and the text of the cards in the HTML. I am new with React. Please help and thanks.

Body:
Try this:

return (
    <div className="App">
      <ul>
        {equipo?.data?.map((item) => (
          <li>{item.name}</li>
        ))}
      </ul>
    </div>
  );


问:
Identifying duplicates in a list of character vectors in R
I have a list of character vectors like this:

```<code>my_list <- list(c('a','b','c','d','e'),c('e','f','g'),c('h','i','j'))
names(my_list) <- c("group1","group2","group3")
</code>```

And I want to have a simple way to test my_list for duplicates in the letters across any of the 3 groups/vectors in my list.  So for instance, "e" appears in both group 1 and group 2 so that would be a duplicate.  Anything simple that just returns a logical if there is at least one or more duplicates across 2 or more groups would be ideal.  So a FALSE return would mean that the letters in each group are unique to that group only (this isn't the case in my example here obviously).

Thanks so much!

答:
We can stack the named list to a two column data.frame, get the frequency count with table, check for duplicates by column with colSums on a logical vector and return with the names that are occuring more than 1

```<code>names(which(colSums(table(stack(my_list)[2:1])> 0) > 1))
[1] "e"
</code>```

Or slighly more compact

```<code> names(which(table(unlist(my_list)) > 1))
[1] "e"
</code>```

If we want a logical column

```<code>library(dplyr)
library(tidyr)
library(tibble)
enframe(my_list) %>%
   unnest(value) %>%
  group_by(value) %>%
   mutate(flag = any(n_distinct(name) > 1)) %>%
 group_by(name) %>%
  summarise(flag = any(flag))
</code>```

-output

```<code># A tibble: 3 × 2
  name   flag
  <chr>  <lgl>
1 group1 TRUE
2 group2 TRUE
3 group3 FALSE
</code>```

Body:
I have a list of character vectors like this:

my_list <- list(c('a','b','c','d','e'),c('e','f','g'),c('h','i','j'))
names(my_list) <- c("group1","group2","group3")

And I want to have a simple way to test my_list for duplicates in the letters across any of the 3 groups/vectors in my list.  So for instance, "e" appears in both group 1 and group 2 so that would be a duplicate.  Anything simple that just returns a logical if there is at least one or more duplicates across 2 or more groups would be ideal.  So a FALSE return would mean that the letters in each group are unique to that group only (this isn't the case in my example here obviously).

Thanks so much!

Body:
We can stack the named list to a two column data.frame, get the frequency count with table, check for duplicates by column with colSums on a logical vector and return with the names that are occuring more than 1

names(which(colSums(table(stack(my_list)[2:1])> 0) > 1))
[1] "e"

Or slighly more compact

 names(which(table(unlist(my_list)) > 1))
[1] "e"

If we want a logical column

library(dplyr)
library(tidyr)
library(tibble)
enframe(my_list) %>%
   unnest(value) %>%
  group_by(value) %>%
   mutate(flag = any(n_distinct(name) > 1)) %>%
 group_by(name) %>%
  summarise(flag = any(flag))

-output

# A tibble: 3 × 2
  name   flag
  <chr>  <lgl>
1 group1 TRUE
2 group2 TRUE
3 group3 FALSE


问:
Recompile with -Xlint in Android studio
When I build my Android project in Android Studio, I get message:

```<code>Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
</code>```

and

```<code>Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
</code>```

I would like to do what the message suggested, but how? How can I configure my Android studio to re-compile my project with -Xlint as the above message suggested?  (I am using Android Studio 3.0.1)

答:
The message suggests to recompile with -Xlint flag in command-line, to get more issue details, but even if you do, the next log may ask for --stacktrace flag.

In build.gradle file, do something like:

```<code>import org.gradle.api.logging.configuration.ShowStacktrace
allprojects {
    // Same as passing --stacktrace option.
    gradle.startParameter.showStacktrace = ShowStacktrace.ALWAYS

    tasks.withType(JavaCompile) {
        options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
    }
}
</code>```

Note that the import may not be required (just imported to be clear).

Also as y4n9b0 said; Then you can use warnings' details to fix issues.

For example, you can replace deprecated method with new method (I mean, there must be a new-method, since old-method has been deprecated).

But sometimes for backward compatibility, we don't want change our code, and just want to get rid of compile-time warnings; simply add in front of the deprecated method:

```<code>@SuppressWarnings("deprecation")
</code>```

Title: Recompile with -Xlint in Android studio

Body:
When I build my Android project in Android Studio, I get message:

Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

and

Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

I would like to do what the message suggested, but how? How can I configure my Android studio to re-compile my project with -Xlint as the above message suggested?  (I am using Android Studio 3.0.1)

Body:
The message suggests to recompile with -Xlint flag in command-line, to get more issue details, but even if you do, the next log may ask for --stacktrace flag.

In build.gradle file, do something like:

import org.gradle.api.logging.configuration.ShowStacktrace
allprojects {
    // Same as passing --stacktrace option.
    gradle.startParameter.showStacktrace = ShowStacktrace.ALWAYS

    tasks.withType(JavaCompile) {
        options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
    }
}

Note that the import may not be required (just imported to be clear).

Also as y4n9b0 said; Then you can use warnings' details to fix issues.

For example, you can replace deprecated method with new method (I mean, there must be a new-method, since old-method has been deprecated).

But sometimes for backward compatibility, we don't want change our code, and just want to get rid of compile-time warnings; simply add in front of the deprecated method:

@SuppressWarnings("deprecation")


问:
How to find the index of n largest elements in a list or np.array, Python
Is there a built-in function or a very simple way of finding the index of n largest elements in a list or a numpy array?

```<code>K = [1,2,2,4,5,5,6,10]
</code>```

Find the index of the largest 5 elements?

I count the duplicates more than once, and the output should be a list of the indices of those largest numbers

答:
For efficiency, numpy partition is much more efficient for large array.
There is no need to sort fully.

"All elements smaller than the k-th element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined."

Body:
Is there a built-in function or a very simple way of finding the index of n largest elements in a list or a numpy array?

K = [1,2,2,4,5,5,6,10]

Find the index of the largest 5 elements?

I count the duplicates more than once, and the output should be a list of the indices of those largest numbers


问:
Creating a date column based on two different conditions
I am trying to create a column that calculates the current time a person has been active on a therapy.

I have a start date column and an 'end date column'; but in the 'end date column', the people who are still active have a date of 2030-12-31 00:00:00 assigned.
I have tried to change this value only to now with pd.Timestamp("now") based on the condition of being active or not being active to today.

```<code>now = pd.Timestamp('now')

def tiempo_terapia (row):
    if row['Fecha_baja_terapia'] == no_baja:
        return row[((now - df['Fecha_instalación_terapia'])/np.timedelta64(1,'Y')).round(2)]
    else:
        return row[((df['Fecha_baja_terapia'] - df['Fecha_instalación_terapia'])/np.timedelta64(1,'Y')).round(2)]

df['Tiempo_con_terapia']= df.apply(lambda row : tiempo_terapia(row), axis =1)
df.head()
</code>```

I keep getting different error types. The latest is:
KeyError: "None of [Float64Index([ 9.38,  9.38, 11.78, 11.78,  7.73,  7.73, 12.33, 12.33, 12.33,\n               8.01,\n              ...\n               0.11, -0.22, -0.72, -0.39, -0.39, -0.39,  0.06,  0.08,  0.15,\n               0.14],\n             dtype='float64', length=746448)] are in the [index]"

Any ideas ?? I have tried everthing I find as a suggestion in stackflow

答:
Welcome to Stack Overflow. This is a well written first question. The only things it's critically missing are some sample data (row = [how exactly is it?]) and import pandas as pd; import numpy as np to make it reproducible and get faster good answers. Other suggestions you can find here.

Moving on, since I do not have the original row I created a sample:

import pandas
import time
import numpy

one_row = {'Name':['Maria'],
           'Date_before': [numpy.nan],
           'Date_later': [numpy.nan],
           'Duration': [numpy.nan]}
one_row_dataframe = pandas.DataFrame(one_row)
one_row_dataframe
#     Name  Date_before  Date_later  Duration
# 0  Maria          NaN         NaN       NaN

time_before = pandas.Timestamp('now')
time.sleep(3) # delay 3 seconds
time_later = pandas.Timestamp('now')
time_difference = time_later - time_before
duration = time_difference / numpy.timedelta64(1, 's')

one_row_dataframe['Date_before'] = one_row_dataframe['Date_before'].replace([numpy.nan],  time_before)

one_row_dataframe['Date_later'] = one_row_dataframe['Date_later'].replace([numpy.nan],  time_later)

one_row_dataframe['Duration'] = one_row_dataframe['Duration'].replace([numpy.nan],  duration)

one_row_dataframe
#     Name                Date_before                 Date_later  Duration
# 0  Maria 2022-02-11 18:14:49.242946 2022-02-11 18:14:52.246801  3.003855

```

Since this works, I am certain you can figure out how you can apply it on your case with some ad-hoc data frame/column manipulation that fits your specific data set.

Body:
I am trying to create a column that calculates the current time a person has been active on a therapy.

I have a start date column and an 'end date column'; but in the 'end date column', the people who are still active have a date of 2030-12-31 00:00:00 assigned.
I have tried to change this value only to now with pd.Timestamp("now") based on the condition of being active or not being active to today.

now = pd.Timestamp('now')

def tiempo_terapia (row):
    if row['Fecha_baja_terapia'] == no_baja:
        return row[((now - df['Fecha_instalación_terapia'])/np.timedelta64(1,'Y')).round(2)]
    else:
        return row[((df['Fecha_baja_terapia'] - df['Fecha_instalación_terapia'])/np.timedelta64(1,'Y')).round(2)]

df['Tiempo_con_terapia']= df.apply(lambda row : tiempo_terapia(row), axis =1)
df.head()

I keep getting different error types. The latest is:
KeyError: "None of [Float64Index([ 9.38,  9.38, 11.78, 11.78,  7.73,  7.73, 12.33, 12.33, 12.33,\n               8.01,\n              ...\n               0.11, -0.22, -0.72, -0.39, -0.39, -0.39,  0.06,  0.08,  0.15,\n               0.14],\n             dtype='float64', length=746448)] are in the [index]"

Any ideas ?? I have tried everthing I find as a suggestion in stackflow

Body:
Welcome to Stack Overflow. This is a well written first question. The only things it's critically missing are some sample data (row = [how exactly is it?]) and import pandas as pd; import numpy as np to make it reproducible and get faster good answers. Other suggestions you can find here.

Moving on, since I do not have the original row I created a sample:

import pandas
import time
import numpy

one_row = {'Name':['Maria'],
           'Date_before': [numpy.nan],
           'Date_later': [numpy.nan],
           'Duration': [numpy.nan]}
one_row_dataframe = pandas.DataFrame(one_row)
one_row_dataframe
#     Name  Date_before  Date_later  Duration
# 0  Maria          NaN         NaN       NaN

time_before = pandas.Timestamp('now')
time.sleep(3) # delay 3 seconds
time_later = pandas.Timestamp('now')
time_difference = time_later - time_before
duration = time_difference / numpy.timedelta64(1, 's')

one_row_dataframe['Date_before'] = one_row_dataframe['Date_before'].replace([numpy.nan],  time_before)

one_row_dataframe['Date_later'] = one_row_dataframe['Date_later'].replace([numpy.nan],  time_later)

one_row_dataframe['Duration'] = one_row_dataframe['Duration'].replace([numpy.nan],  duration)

one_row_dataframe
#     Name                Date_before                 Date_later  Duration
# 0  Maria 2022-02-11 18:14:49.242946 2022-02-11 18:14:52.246801  3.003855

Since this works, I am certain you can figure out how you can apply it on your case with some ad-hoc data frame/column manipulation that fits your specific data set.


问:
Customizing CSS classes in ASP.NET
I am working on an application where the user will be allowed to change the font color of header titles.

The header titles use a value from cssClass (the cssClass uses font-size, font-color, font-weight & font-family).

Is there a way that I can allow a custom font-color in the css file itself?

One option would be to eliminate font-color from the cssClass, and use Font-Color in the .aspx page.

答:
If you are letting user's pick just their own font color, it's probably easiest to set the Font-Color attribute or set an inline style attribute on the client side. If you did it on the client side, the interface would be snappier (not requiring a postback for a color change), but you would need to save the user's choice somewhere and set it again on postback.

Here's an example of setting the header colors on the client-side:

With jQuery

```<code>function setHeaderColor(color) {
    // The color parameters should be of the form '#000000'
    $('h1, h2, h3').css({ color: color });
}
</code>```

Without jQuery

```<code>function setHeaderColor(color) {
    var hdrs = [].concat(document.getElementsByTagName('h1'))
                 .concat(document.getElementsByTagName('h2'))
                 .concat(document.getElementsByTagName('h3')),
        ii, jj;

    for (ii = 0; ii < hdrs.length; ii += 1) {
        for (jj = 0; jj < hdrs[ii].length; jj += 1) {
            hdrs[ii].item(jj).style.color = color;
        }
    }
}
</code>```

Title: Customizing CSS classes in ASP.NET

Body:
If you are letting user's pick just their own font color, it's probably easiest to set the Font-Color attribute or set an inline style attribute on the client side. If you did it on the client side, the interface would be snappier (not requiring a postback for a color change), but you would need to save the user's choice somewhere and set it again on postback.

Here's an example of setting the header colors on the client-side:

With jQuery

function setHeaderColor(color) {
    // The color parameters should be of the form '#000000'
    $('h1, h2, h3').css({ color: color });
}

Without jQuery

function setHeaderColor(color) {
    var hdrs = [].concat(document.getElementsByTagName('h1'))
                 .concat(document.getElementsByTagName('h2'))
                 .concat(document.getElementsByTagName('h3')),
        ii, jj;

    for (ii = 0; ii < hdrs.length; ii += 1) {
        for (jj = 0; jj < hdrs[ii].length; jj += 1) {
            hdrs[ii].item(jj).style.color = color;
        }
    }
}


答:
This is your issue:

const [equipo, setEquipo] = React.useState([]);
```
<p>On the first render, before the API call has returned, you're attempting to access the <code>.data</code> field of an empty array. Instead, you need to initialize equipo with:</p>
<pre class="lang-js prettyprint-override"><code>const [equipo, setEquipo] = React.useState({data: []});
</code>```

Title: Uncaught TypeError: equipo.data is undefined using React

Body:
This is your issue:

const [equipo, setEquipo] = React.useState([]);

On the first render, before the API call has returned, you're attempting to access the .data field of an empty array. Instead, you need to initialize equipo with:

const [equipo, setEquipo] = React.useState({data: []});


问:
How do I set initialValues of useFormik to data returned from an API request
I have an update ProfilePage component and I want to preload the form values with the data received from an Axios API request using useQuery, but it seems the useFormik initialValues render before the request is completed therefore having the initial values to be undefined, can anyone help me ?

```<code>  const { isSuccess, data } = useQuery("author", async () => {
    const endPoint = `${baseURL}/auth/author`;
    return Axios.get(endPoint, {
      headers: {
        "x-auth-token": token,
      },
    })
      .then(({ data }) => {
        return data.author;
      })
      .catch((err) => {
        setErrors(err.response.data.errors[0].msg);
        console.log(errors);
      });
  });

  const formik = useFormik({
    initialValues: {
      firstname: data.firstname,
      lastname: data.lastname,
      gender: data.gender,
      dob: data.dob,
      email: data.email,
      oldPassword: "",
      newPassword: "",
      confirmNewPassword: "",
      profilePic: "",
    },
    validationSchema: Yup.object({
      firstname: Yup.string()
        .max(20, "First Name must not be more that 20 characters")
        .required("Required*"),
      lastname: Yup.string()
        .max(20, "Last Name must not be more that 20 characters")
        .required("Required*"),
      gender: Yup.string().required("Required*"),
      dob: Yup.string().required("Required*"),
      email: Yup.string()
        .email("Must be a Valid Email Address")
        .required("Required*"),
      oldPassword: Yup.string().min(
        6,
        "Your password must be more than 6 characters"
      ),
      newPassword: Yup.string().min(
        6,
        "Your password must be more than 6 characters"
      ),
      confirmNewPassword: Yup.string(),
    }),
    onSubmit: (values) => {
      console.log(values);
    },
  });
</code>```

The error I get is Cannot read properties of undefined (reading 'firstname')
if I could get a way make useFormik render just after the API request it'd help

答: You can overcome this issue by using a loading component. Display a loading spinner while the initial values are being fetched from the server and when the payload arrives, send it as a prop to your form component. In this way, you will also avoid showing an empty form which is prefilled after a random amount of time to the user.</p>

Body:
I have an update ProfilePage component and I want to preload the form values with the data received from an Axios API request using useQuery, but it seems the useFormik initialValues render before the request is completed therefore having the initial values to be undefined, can anyone help me ?

  const { isSuccess, data } = useQuery("author", async () => {
    const endPoint = `${baseURL}/auth/author`;
    return Axios.get(endPoint, {
      headers: {
        "x-auth-token": token,
      },
    })
      .then(({ data }) => {
        return data.author;
      })
      .catch((err) => {
        setErrors(err.response.data.errors[0].msg);
        console.log(errors);
      });
  });

  const formik = useFormik({
    initialValues: {
      firstname: data.firstname,
      lastname: data.lastname,
      gender: data.gender,
      dob: data.dob,
      email: data.email,
      oldPassword: "",
      newPassword: "",
      confirmNewPassword: "",
      profilePic: "",
    },
    validationSchema: Yup.object({
      firstname: Yup.string()
        .max(20, "First Name must not be more that 20 characters")
        .required("Required*"),
      lastname: Yup.string()
        .max(20, "Last Name must not be more that 20 characters")
        .required("Required*"),
      gender: Yup.string().required("Required*"),
      dob: Yup.string().required("Required*"),
      email: Yup.string()
        .email("Must be a Valid Email Address")
        .required("Required*"),
      oldPassword: Yup.string().min(
        6,
        "Your password must be more than 6 characters"
      ),
      newPassword: Yup.string().min(
        6,
        "Your password must be more than 6 characters"
      ),
      confirmNewPassword: Yup.string(),
    }),
    onSubmit: (values) => {
      console.log(values);
    },
  });

The error I get is Cannot read properties of undefined (reading 'firstname')
if I could get a way make useFormik render just after the API request it'd help


问:
TypeError: ('invalid cache item: tuple') in XGBoost
I am trying to get classify value using XGBoost model.

However I got an Error when I declared XGBoost model.

How can I fix this error ?

```<code>train = pd.read_csv("./data/train.csv")
test_x = pd.read_csv("./data/test.csv")
train_y = train['Y']
train_x = train.drop('Y', axis=1)

kf = KFold(n_splits=4, shuffle=True, random_state=71)
tr_idx, va_idx = list(kf.split(train_x))[0]
tr_x, va_x = train_x.iloc[tr_idx], train_x.iloc[va_idx]
tr_y, va_y = train_y.iloc[tr_idx], train_y.iloc[va_idx]

dtrain = xgb.DMatrix(tr_x, label=tr_y)
dvalid = xgb.DMatrix(va_x, label=va_y),
dtest = xgb.DMatrix(test_x)

print('-' * 10)

params = {'objective' : 'binary:logistic',
            'eval_metric' : 'logloss',
            'verbosity': 0, 'random_state' : 71}
num_round = 10000

watch_list = [(dtrain, 'train'),(dvalid, 'eval')]
model = xgb.train(params, dtrain, num_round, watch_list) ← error occured here
</code>```

and error message is here.

```<code>TypeError: ('invalid cache item: tuple', [<xgboost.core.DMatrix object at 0x000001B9D6930190>, <xgboost.core.DMatrix object at 0x000001B9D6930190>, (<xgboost.core.DMatrix object at 0x000001B9DBBCA880>,)])
</code>```

答:
The dvalid which you are creating is a tuple of size 1 due to the comma you have put in the end. If you do a = 1, this creates a tuple of size one. If you remove the comma, you get rid of that error

dvalid = xgb.DMatrix(va_x, label=va_y), # Remove the comma here.
``
```

Body:
I am trying to get classify value using XGBoost model.

However I got an Error when I declared XGBoost model.

How can I fix this error ?

train = pd.read_csv("./data/train.csv")
test_x = pd.read_csv("./data/test.csv")
train_y = train['Y']
train_x = train.drop('Y', axis=1)

kf = KFold(n_splits=4, shuffle=True, random_state=71)
tr_idx, va_idx = list(kf.split(train_x))[0]
tr_x, va_x = train_x.iloc[tr_idx], train_x.iloc[va_idx]
tr_y, va_y = train_y.iloc[tr_idx], train_y.iloc[va_idx]

dtrain = xgb.DMatrix(tr_x, label=tr_y)
dvalid = xgb.DMatrix(va_x, label=va_y),
dtest = xgb.DMatrix(test_x)

print('-' * 10)

params = {'objective' : 'binary:logistic',
            'eval_metric' : 'logloss',
            'verbosity': 0, 'random_state' : 71}
num_round = 10000

watch_list = [(dtrain, 'train'),(dvalid, 'eval')]
model = xgb.train(params, dtrain, num_round, watch_list) ← error occured here

and error message is here.

TypeError: ('invalid cache item: tuple', [<xgboost.core.DMatrix object at 0x000001B9D6930190>, <xgboost.core.DMatrix object at 0x000001B9D6930190>, (<xgboost.core.DMatrix object at 0x000001B9DBBCA880>,)])