问:
Flutter - Json Serializing is not working
I have encountered an issue passing data from services to models. The model is supposed to get the json from service, which fetched the data from API, and json converting it in model. But after the data passed into model, the Map toJson didn't process.
I have tried it in many ways, but the result is still the same.

goals_view_service.dart

```<code>import 'dart:convert';
import 'package:requests/requests.dart';

// goal_data={
  //        [
//         'goal_name': savings_goal[1],
//         'amount': savings_goal[2],
//         'duration': savings_goal[3],
//       ]
//          }

class GoalViewServices{

  // List<GoalsModel> _goals;
  var goals = List<GoalsModel>();

   Future<Map<String, dynamic>> _getGoals() async {
      Response request;
      try {
        request = await Requests.get(
          url + '/savings_goal_display',
          headers: {'content-type': 'application/json'},
          // TODO: when having true ssl certificate, change verify to true.
          // verify: false,
          timeoutSeconds: 20,
        );
      } catch (e) {
        return {"result": "Connection Error: $e"};
      }
      if (!request.hasError) {
        try {
          return request.json() as Map<String, dynamic>;
        } catch (e) {
          return {"result": "$e"};
        }
      } else {
        return {"result": "Unknown Request Error"};
      }
  }

  Future<List<GoalsModel>> renewDataForView() async {
    var dic = await _getGoals();
    // var goals = List<GoalsModel>();
    if (dic != null) {
      // print(dic);
      // final savingsGoalsDic = dic['saving_goals'];
      final savingsGoalsDicArray = List<Map<String, dynamic>>.from(dic['savings_goals'] ?? {}) ?? [];
      // final savingsGoalsDicArray = (dic['savings_goals'] ?? {}) ?? [];
      print('savingsGoalsDic__: $savingsGoalsDicArray');
      for (final aData in savingsGoalsDicArray) {
          // print(aData);
          // Map json = jsonDecode(aData);
          // var title = aData["goal_name"];
          // var totalAmount = aData["amount"];
          // var durations = aData["duration"];
          goals.add(GoalsModel.fromJson(aData));
        }
    }
    // print(goals);
    return goals;
  }

}
</code>```

goals_model.dart

```<code>class GoalsModel {
  String title;
  String imagePath;
  int totalAmount;
  int durations;

  GoalsModel({this.title,this.totalAmount,this.durations});

  // final Map<String, String> goalsImage = {
  //   "Housing": "assets/images/housing.jpg",
  //   "Car": "assets/images/car.jpg",
  //   "Retirement": "assets/images/retirement.jpg",
  //   "Shopping": "assets/images/shopping.jpg",
  //   "Travel": "assets/images/travel.jpg",
  //   "Wedding": "assets/images/wedding.jpg",
  //   "Study": "assets/images/study.jpg"
  // };

  GoalsModel.fromJson(Map<String, dynamic> json) {

    // print(json);
    title = json["goal_name"] as String;
    // print(this.title);
    totalAmount = json["amount"] as int;
    // print(this.totalAmount);
    durations = json["duration"] as int;
    // print(this.durations);
    imagePath = "assets/images/study.jpg";
    // var data = _toJson(this.title,this.imagePath,this.totalAmount,this.durations);

    // if (this.title == goals.keys){
    //     this.imagePath = goals.values;
    // }
  }

  // GoalsModel.fromJson(Map<String, dynamic> json)
  //     : title = json["goal_name"],
  //       totalAmount = json["amount"],
  //       durations = json["duration"],
  //        imagePath = "assets/images/study.jpg";

  Map<String, dynamic> toJson () =>{
    'title' : title,
    'imagePath' :imagePath,
    'totalAmount' : totalAmount,
    'durations': durations,

  };

}
</code>```

Goals_viewmodels.dart

```<code>class GoalsViewModel extends BaseModel {
    GoalViewServices _goalViewServices=locator<GoalViewServices>();

    List<GoalsModel> goalList;

    Future<List<GoalsModel>> getGoals() async {
    setState(ViewState.Busy);
    goalList = await _goalViewServices.renewDataForView();
    print(goalList);
    setState(ViewState.Idle);
    return goalList;
  }

}

</code>```

Goals Dictionary

```<code>savingsGoalsDic__: [{amount: 123, duration: 3, goal_name: Car}, {amount: 123, duration: 2, goal_name: Housing}, {amount: 0, duration: 5, goal_name: Retirement}, {amount: 0, duration: 2, goal_name: Shopping}, {amount: 0, duration: 2, goal_name: Travel}, {amount: 12, duration: 3, goal_name: Wedding}]
</code>```

Result from Goals_model

```<code>[Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel']
</code>```

答:
You can copy paste run full code below

Step 1: _getGoals() need to return json.decode(response.body); for Map<String, dynamic>

```<code>Future<Map<String, dynamic>> _getGoals() async {
    String jsonString = '''
    ...
    ''';
    http.Response response = http.Response(jsonString, 200);

    return json.decode(response.body);
</code>```

Step 2: renewDataForView() can use Payload.fromJson see definition in full code

```<code>Future<List<GoalsModel>> renewDataForView() async {
    var dic = await _getGoals();
    Payload payload;
    if (dic != null) {
      payload = Payload.fromJson(dic);
    }
    // print(goals);
    return payload.savingsGoalsDic;
  }
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
  Payload({
    this.savingsGoalsDic,
  });

  List<GoalsModel> savingsGoalsDic;

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        savingsGoalsDic: List<GoalsModel>.from(
            json["savingsGoalsDic__"].map((x) => GoalsModel.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "savingsGoalsDic__":
            List<dynamic>.from(savingsGoalsDic.map((x) => x.toJson())),
      };
}

class GoalsModel {
  GoalsModel({
    this.totalAmount,
    this.durations,
    this.title,
  });

  int totalAmount;
  int durations;
  String title;

  factory GoalsModel.fromJson(Map<String, dynamic> json) => GoalsModel(
        totalAmount: json["amount"],
        durations: json["duration"],
        title: json["goal_name"],
      );

  Map<String, dynamic> toJson() => {
        "amount": totalAmount,
        "duration": durations,
        "goal_name": title,
      };
}

class GoalViewServices {
  // List<GoalsModel> _goals;
  var goals = List<GoalsModel>();

  Future<Map<String, dynamic>> _getGoals() async {
    String jsonString = '''
    {"savingsGoalsDic__": [{"amount": 123, "duration": 3, "goal_name": "Car"}, {"amount": 123, "duration": 2, "goal_name": "Housing"}, {"amount": 0, "duration": 5, "goal_name": "Retirement"}, {"amount": 0, "duration": 2, "goal_name": "Shopping"}, {"amount": 0, "duration": 2, "goal_name": "Travel"}, {"amount": 12, "duration": 3, "goal_name": "Wedding"}
]
}
    ''';
    http.Response response = http.Response(jsonString, 200);

    return json.decode(response.body);

    /*Response request;
    try {
      request = await Requests.get(
        url + '/savings_goal_display',
        headers: {'content-type': 'application/json'},
        // TODO: when having true ssl certificate, change verify to true.
        // verify: false,
        timeoutSeconds: 20,
      );
    } catch (e) {
      return {"result": "Connection Error: $e"};
    }
    if (!request.hasError) {
      try {
        return request.json() as Map<String, dynamic>;
      } catch (e) {
        return {"result": "$e"};
      }
    } else {
      return {"result": "Unknown Request Error"};
    }*/
  }

  Future<List<GoalsModel>> renewDataForView() async {
    var dic = await _getGoals();
    Payload payload;
    if (dic != null) {
      payload = Payload.fromJson(dic);
    }
    // print(goals);
    return payload.savingsGoalsDic;
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  GoalViewServices goalViewServices = GoalViewServices();

  Future<List<GoalsModel>> _future;

  @override
  void initState() {
    _future = goalViewServices.renewDataForView();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<List<GoalsModel>> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (context, index) {
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot.data[index].title),
                                    Spacer(),
                                    Text(
                                      snapshot.data[index].totalAmount
                                          .toString(),
                                    ),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}
</code>```

Body:
I have encountered an issue passing data from services to models. The model is supposed to get the json from service, which fetched the data from API, and json converting it in model. But after the data passed into model, the Map toJson didn't process.
I have tried it in many ways, but the result is still the same.

goals_view_service.dart

import 'dart:convert';
import 'package:requests/requests.dart';

// goal_data={
  //        [
//         'goal_name': savings_goal[1],
//         'amount': savings_goal[2],
//         'duration': savings_goal[3],
//       ]
//          }

class GoalViewServices{

  // List<GoalsModel> _goals;
  var goals = List<GoalsModel>();

   Future<Map<String, dynamic>> _getGoals() async {
      Response request;
      try {
        request = await Requests.get(
          url + '/savings_goal_display',
          headers: {'content-type': 'application/json'},
          // TODO: when having true ssl certificate, change verify to true.
          // verify: false,
          timeoutSeconds: 20,
        );
      } catch (e) {
        return {"result": "Connection Error: $e"};
      }
      if (!request.hasError) {
        try {
          return request.json() as Map<String, dynamic>;
        } catch (e) {
          return {"result": "$e"};
        }
      } else {
        return {"result": "Unknown Request Error"};
      }
  }

  Future<List<GoalsModel>> renewDataForView() async {
    var dic = await _getGoals();
    // var goals = List<GoalsModel>();
    if (dic != null) {
      // print(dic);
      // final savingsGoalsDic = dic['saving_goals'];
      final savingsGoalsDicArray = List<Map<String, dynamic>>.from(dic['savings_goals'] ?? {}) ?? [];
      // final savingsGoalsDicArray = (dic['savings_goals'] ?? {}) ?? [];
      print('savingsGoalsDic__: $savingsGoalsDicArray');
      for (final aData in savingsGoalsDicArray) {
          // print(aData);
          // Map json = jsonDecode(aData);
          // var title = aData["goal_name"];
          // var totalAmount = aData["amount"];
          // var durations = aData["duration"];
          goals.add(GoalsModel.fromJson(aData));
        }
    }
    // print(goals);
    return goals;
  }

}

goals_model.dart

class GoalsModel {
  String title;
  String imagePath;
  int totalAmount;
  int durations;

  GoalsModel({this.title,this.totalAmount,this.durations});

  // final Map<String, String> goalsImage = {
  //   "Housing": "assets/images/housing.jpg",
  //   "Car": "assets/images/car.jpg",
  //   "Retirement": "assets/images/retirement.jpg",
  //   "Shopping": "assets/images/shopping.jpg",
  //   "Travel": "assets/images/travel.jpg",
  //   "Wedding": "assets/images/wedding.jpg",
  //   "Study": "assets/images/study.jpg"
  // };

  GoalsModel.fromJson(Map<String, dynamic> json) {

    // print(json);
    title = json["goal_name"] as String;
    // print(this.title);
    totalAmount = json["amount"] as int;
    // print(this.totalAmount);
    durations = json["duration"] as int;
    // print(this.durations);
    imagePath = "assets/images/study.jpg";
    // var data = _toJson(this.title,this.imagePath,this.totalAmount,this.durations);

    // if (this.title == goals.keys){
    //     this.imagePath = goals.values;
    // }
  }

  // GoalsModel.fromJson(Map<String, dynamic> json)
  //     : title = json["goal_name"],
  //       totalAmount = json["amount"],
  //       durations = json["duration"],
  //        imagePath = "assets/images/study.jpg";

  Map<String, dynamic> toJson () =>{
    'title' : title,
    'imagePath' :imagePath,
    'totalAmount' : totalAmount,
    'durations': durations,

  };

}

Goals_viewmodels.dart

class GoalsViewModel extends BaseModel {
    GoalViewServices _goalViewServices=locator<GoalViewServices>();

    List<GoalsModel> goalList;

    Future<List<GoalsModel>> getGoals() async {
    setState(ViewState.Busy);
    goalList = await _goalViewServices.renewDataForView();
    print(goalList);
    setState(ViewState.Idle);
    return goalList;
  }

}

Goals Dictionary

savingsGoalsDic__: [{amount: 123, duration: 3, goal_name: Car}, {amount: 123, duration: 2, goal_name: Housing}, {amount: 0, duration: 5, goal_name: Retirement}, {amount: 0, duration: 2, goal_name: Shopping}, {amount: 0, duration: 2, goal_name: Travel}, {amount: 12, duration: 3, goal_name: Wedding}]

Result from Goals_model

[Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel']

Body:
You can copy paste run full code below

Step 1: _getGoals() need to return json.decode(response.body); for Map<String, dynamic>

Future<Map<String, dynamic>> _getGoals() async {
    String jsonString = '''
    ...
    ''';
    http.Response response = http.Response(jsonString, 200);

    return json.decode(response.body);

Step 2: renewDataForView() can use Payload.fromJson see definition in full code

Future<List<GoalsModel>> renewDataForView() async {
    var dic = await _getGoals();
    Payload payload;
    if (dic != null) {
      payload = Payload.fromJson(dic);
    }
    // print(goals);
    return payload.savingsGoalsDic;
  }

working demo

full code

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
  Payload({
    this.savingsGoalsDic,
  });

  List<GoalsModel> savingsGoalsDic;

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        savingsGoalsDic: List<GoalsModel>.from(
            json["savingsGoalsDic__"].map((x) => GoalsModel.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "savingsGoalsDic__":
            List<dynamic>.from(savingsGoalsDic.map((x) => x.toJson())),
      };
}

class GoalsModel {
  GoalsModel({
    this.totalAmount,
    this.durations,
    this.title,
  });

  int totalAmount;
  int durations;
  String title;

  factory GoalsModel.fromJson(Map<String, dynamic> json) => GoalsModel(
        totalAmount: json["amount"],
        durations: json["duration"],
        title: json["goal_name"],
      );

  Map<String, dynamic> toJson() => {
        "amount": totalAmount,
        "duration": durations,
        "goal_name": title,
      };
}

class GoalViewServices {
  // List<GoalsModel> _goals;
  var goals = List<GoalsModel>();

  Future<Map<String, dynamic>> _getGoals() async {
    String jsonString = '''
    {"savingsGoalsDic__": [{"amount": 123, "duration": 3, "goal_name": "Car"}, {"amount": 123, "duration": 2, "goal_name": "Housing"}, {"amount": 0, "duration": 5, "goal_name": "Retirement"}, {"amount": 0, "duration": 2, "goal_name": "Shopping"}, {"amount": 0, "duration": 2, "goal_name": "Travel"}, {"amount": 12, "duration": 3, "goal_name": "Wedding"}
]
}
    ''';
    http.Response response = http.Response(jsonString, 200);

    return json.decode(response.body);

    /*Response request;
    try {
      request = await Requests.get(
        url + '/savings_goal_display',
        headers: {'content-type': 'application/json'},
        // TODO: when having true ssl certificate, change verify to true.
        // verify: false,
        timeoutSeconds: 20,
      );
    } catch (e) {
      return {"result": "Connection Error: $e"};
    }
    if (!request.hasError) {
      try {
        return request.json() as Map<String, dynamic>;
      } catch (e) {
        return {"result": "$e"};
      }
    } else {
      return {"result": "Unknown Request Error"};
    }*/
  }

  Future<List<GoalsModel>> renewDataForView() async {
    var dic = await _getGoals();
    Payload payload;
    if (dic != null) {
      payload = Payload.fromJson(dic);
    }
    // print(goals);
    return payload.savingsGoalsDic;
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  GoalViewServices goalViewServices = GoalViewServices();

  Future<List<GoalsModel>> _future;

  @override
  void initState() {
    _future = goalViewServices.renewDataForView();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<List<GoalsModel>> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (context, index) {
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot.data[index].title),
                                    Spacer(),
                                    Text(
                                      snapshot.data[index].totalAmount
                                          .toString(),
                                    ),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}


来源: stackexchange

问:
AWS Lambda with php.handler node 12.x error - SOLVED
UPDATE: Thank you all! I have solved this by creating a custom runtime for my PHP Lambda.

I am currently using Node.js 8.10 Runtime with a php.handler and my Lambda function works fine, but when I change the Runtime to 12.x, I get the following error:

"php-7-bin/bin/php: error while loading shared libraries: libcrypt.so.1: cannot open shared object file: No such file or directory"

```<code>exports.handler = function(event, context, callback) {
    var php = spawn('php-7-bin/bin/php',['--php-ini', 'user.ini', process.env['PHPFILE']], {maxBuffer: 200 * 1024 * 200});
    var output = "";
    var statusCode = 0;

    php.stdin.write(JSON.stringify(event));

    php.stdin.end();

    php.stdout.on('data', function(data) {
          console.log("CHUNK: " + data);
          output+=data;
    });

    php.stderr.on('data', function(data) {
       console.log(data);
    });

      php.on('close', function(code) {
        var obj = JSON.parse(output);
        statusCode = obj.status.statusCode;
        if(statusCode !== 0){
          callback(output);
        }else{
          context.succeed(obj);
        }

      });
}
</code>```

I need to update my Lambda to the latest node.js version, but I have no idea how to overcome this error, so any help would be greatly appreciated!

答:
I Fix this problem by adding extra library folder in my function's zip.

Make a directory name extra-libs

Copy all required libraries from Amazon Linux 2 to Extra-libs by using following steps :

Run amazon Linux 2's docker instance by following command

docker run --rm -it -v :/opt:rw,delegated amazonlinux:latest

Then in docker instance make directory using

mkdir deps

Copy all required libraries from lib64 to deps directory using

cp -f lib64/libcrypt.so.1 deps (Taken libcrypt.so.1 for example purpose)

Then open another terminal window and move all library files to local extra-libs

docker cp <DOCKER_CONTAINER_ID>:/deps/ . && mv deps/* ./extra-libs

Get container id by using docker ps

Then in index.js file , add following line to php's env setting.

```<code>LD_LIBRARY_PATH:path.join(__dirname, '/extra-libs')
</code>```

Zip extra-libs folder with your lambda function and upload it.

Hope this helps.

ContentLicense: CC BY-SA 4.0

Body:
UPDATE: Thank you all! I have solved this by creating a custom runtime for my PHP Lambda.

I am currently using Node.js 8.10 Runtime with a php.handler and my Lambda function works fine, but when I change the Runtime to 12.x, I get the following error:

"php-7-bin/bin/php: error while loading shared libraries: libcrypt.so.1: cannot open shared object file: No such file or directory"

exports.handler = function(event, context, callback) {
    var php = spawn('php-7-bin/bin/php',['--php-ini', 'user.ini', process.env['PHPFILE']], {maxBuffer: 200 * 1024 * 200});
    var output = "";
    var statusCode = 0;

    php.stdin.write(JSON.stringify(event));

    php.stdin.end();

    php.stdout.on('data', function(data) {
          console.log("CHUNK: " + data);
          output+=data;
    });

    php.stderr.on('data', function(data) {
       console.log(data);
    });

      php.on('close', function(code) {
        var obj = JSON.parse(output);
        statusCode = obj.status.statusCode;
        if(statusCode !== 0){
          callback(output);
        }else{
          context.succeed(obj);
        }

      });
}

I need to update my Lambda to the latest node.js version, but I have no idea how to overcome this error, so any help would be greatly appreciated!

Body:
I Fix this problem by adding extra library folder in my function's zip.

Make a directory name extra-libs

Copy all required libraries from Amazon Linux 2 to Extra-libs by using following steps :

Run amazon Linux 2's docker instance by following command

docker run --rm -it -v :/opt:rw,delegated amazonlinux:latest

Then in docker instance make directory using

mkdir deps

Copy all required libraries from lib64 to deps directory using

cp -f lib64/libcrypt.so.1 deps (Taken libcrypt.so.1 for example purpose)

Then open another terminal window and move all library files to local extra-libs

docker cp <DOCKER_CONTAINER_ID>:/deps/ . && mv deps/* ./extra-libs

Get container id by using docker ps

Then in index.js file , add following line to php's env setting.

LD_LIBRARY_PATH:path.join(__dirname, '/extra-libs')

Zip extra-libs folder with your lambda function and upload it.

Hope this helps.


问:
How to get the execution time of a cypher query from python?
I am trying to compare get the execution time of a Cypher query from python, i.e. the time required to compute on the neo4j-server (not including the time required output the result). Right now I am using the following code:

```<code>from neo4j.v1 import
driver = GraphDatabase.driver('bolt://localhost:7687', auth=('neo4j', '1234'))

n_repeats = 3
cypher = "MATCH (a) -[:{}*]- (b) WHERE ID(a) < ID(b) RETURN DISTINCT a, b".format(graphname + '_edges')

with driver.session() as session:
    total_time = 0
    for _ in range(n_repeats):
        with session.begin_transaction() as tx:
            start = time.time()
            tx.run(cypher)
            total_time += time.time() - start

avg_time = total_time*1000 / n_repeats
print('Average execution time:', avg_time, 'ms')
</code>```

Is there a better way to time the execution time of a cypher query? In postgresql for instance there is the EXPLAIN ANALYZE statement, which also provides the time required to execute a SQL query. In Cypher there are EXPLAIN and PROFILE statements, but both seemingly don't return specific times.

I am using neo4j-driver to connect to neo4j right now, but I would be willing to switch to another library.

答:
Neo4j Python Driver 1.7

```<code>from neo4j.v1 import
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))

n_repeats = 3
cypher = "MATCH (a) -[:{}*]- (b) WHERE ID(a) < ID(b) RETURN DISTINCT a, b".format(graphname + '_edges')

with driver.session() as session:
    total_time = 0
    for _ in range(n_repeats):
        with session.begin_transaction() as tx:
            start = time.time()
            result = tx.run(cypher)
            records = list(result)  # consume the records
            tx.commit()
            total_time += time.time() - start

avg_time = total_time*1000 / n_repeats
print('Average execution time:', avg_time, 'ms')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to compare get the execution time of a Cypher query from python, i.e. the time required to compute on the neo4j-server (not including the time required output the result). Right now I am using the following code:

from neo4j.v1 import
driver = GraphDatabase.driver('bolt://localhost:7687', auth=('neo4j', '1234'))

n_repeats = 3
cypher = "MATCH (a) -[:{}*]- (b) WHERE ID(a) < ID(b) RETURN DISTINCT a, b".format(graphname + '_edges')

with driver.session() as session:
    total_time = 0
    for _ in range(n_repeats):
        with session.begin_transaction() as tx:
            start = time.time()
            tx.run(cypher)
            total_time += time.time() - start

avg_time = total_time*1000 / n_repeats
print('Average execution time:', avg_time, 'ms')

Is there a better way to time the execution time of a cypher query? In postgresql for instance there is the EXPLAIN ANALYZE statement, which also provides the time required to execute a SQL query. In Cypher there are EXPLAIN and PROFILE statements, but both seemingly don't return specific times.

I am using neo4j-driver to connect to neo4j right now, but I would be willing to switch to another library.

Body:
Neo4j Python Driver 1.7

from neo4j.v1 import
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))

n_repeats = 3
cypher = "MATCH (a) -[:{}*]- (b) WHERE ID(a) < ID(b) RETURN DISTINCT a, b".format(graphname + '_edges')

with driver.session() as session:
    total_time = 0
    for _ in range(n_repeats):
        with session.begin_transaction() as tx:
            start = time.time()
            result = tx.run(cypher)
            records = list(result)  # consume the records
            tx.commit()
            total_time += time.time() - start

avg_time = total_time*1000 / n_repeats
print('Average execution time:', avg_time, 'ms')


问:
Beginner Reading Python Programming Text: A Simple Game Keeps Returning AttributeError
Very sorry in advance for the long paste.

The code is straight from the text. It may be due to class Scene, that seems to have the instruction to: subclass it and implement enter(). But I don't know what that means.

from sys import exit
from random import randint
from textwrap import dedent

class Scene(object):

    def enter(self):
        print("This scene is not yet configured.")
        print("Subclass it and implement enter()")
        exit(1)
# Skeleton code: a base class for Scene that will have
# the common things that all scenes do.

class Engine(object):

    def __init__(self, scene_map):
        self.scene_map = scene_map

    def play(self):
        current_scene = self.scene_map.opening_scene()
        last_scene = self.scene_map.next_scene('finished')

        while current_scene != last_scene:
            next_scene_name = current_scene.enter()
            current_scene = self.scene_map.next_scene(next_scene_name)

        # be sure to print out the last scene
        current_scene.enter()

class Death(Scene):

    quips = [
        "You died.  You kinda suck at this.",
        "Your Mom would be proud...if she were smarter.",
        "Such a luser.",
        "I have a small puppy that's better at this.",
        "You're worse than your Dad's jokes."

    ]

    def enter(self):
        print(Death.quips[randint(0, len(self.quips)-1)])

class CentralCorridor(Scene):

    def enter(self):
        print(dedent("""
            The Gothons of Planet Percal #25 have invaded your ship and
            destroyed your entire crew.  You are the last surviving member
            member and your last mission is to get the neutron destruct
            bomb from the Weapons Armory, put it in the bridge, and
            blow the ship up after getting into an escape pod.

            You're running down the central corridor to the Weapons
            Armory when a Gothon jumps out, red scaly skin, dark grimy
            teeth, and evil clown costume flowing around his hate
            filled body.  He's blocking the door to the Armory and
            about to pull a weapon to blast you.
            """))

        action = input("> ")

        if action == "shoot!":
            print(dedent("""
                Quick on the draw you yank out your blaster and fire
                it at the Gothon.  His clown costume is flowing and
                moving around his body, which throws off your aim.
                Your laster hits his costume but misses him entirely.
                This completely ruins his brand new costume his mother
                bought him, which makes him fly into an insane rage
                and blast you repeatedly in the face until you are
                dead.  Then he eats you.
                """))
            return 'death'

        elif action == "dodge!":
            print(dedent("""
                Like a world class boxer you dodge, weave, slip and
                slide right as the Gothon's blaster cranks a laser
                past your head. In the middle of your artful dodge
                your foot slips and you bang your head on the metal
                wall and pass out.  You wake up shortly after only to
                die as the Gothon stomps on your head and eats you.
                """))
            return 'death'

        elif action == "tell a joke":
            print(dedent("""
                Lucky for you they made you learn Gothon insults in
                the academy.  You tell the one Gothon joke you know:
                Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr,
                fur fvgf nebhaq gur ubhfr.  The Gothon stops, tries
                not to laugh, then busts out laughing and can't move.
                While he's laughing you run up and shoot him square in
                the head putting him down, then jump through the
                Weapon Armory door.
                """))
            return 'laster_weapon_armory'

        else:
            print("DOES NOT COMPUTE!")
            return 'central_corridor'

class LaserWeaponArmory(Scene):

    def enter(self):
        print(dedent("""
            You do a dive roll into the Weapon Armory, crouch and scan
            the room for more GOthon that might be hiding. It's dead
            quiet, too quiet.  You stand up and run to the far side of
            the room and find the neutron bomb in its container.
            There's a keypad lock on the box and you need the code to
            get the bomb out. If you get the code wrong 10 times then
            the lock closes forever and you can't get the bomb.  The
            code is 3 digits.
            """))

        code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
        guess = input("[keypad]> ")
        guesses = 0

        while guess != code and guesses <10:
            print("BZZZZEDDD!")
            guesses += 1
            guess = input("[keypad]> ")

        if guess == code:
            print(dedent("""
                The container clicks open and the seal breaks, letting
                gas out.  You grab the neutron bomb and run as fast as
                you can to the bridge where you must place it in the
                right spot.
                """))
            return 'the_bridge'
        else:
            print(dedent("""
                The lock buzzes one last time and then you hear a
                sickening melting sound as the mechanism is fused
                together.  You decide to sit there, and finally the
                Gothons blow up the ship from their ship and you die.
                """))
            return 'death'

class Finished(Scene):

    def enter(self):
        print("You won! Good job.")
        return 'finished'

class Map(object):

    scenes = {
        'central_corridor': CentralCorridor(),
        'laster_weapon_armory': LaserWeaponArmory(),
        'the_bridge': TheBridge(),
        'escape_pod': EscapePod(),
        'death': Death(),
        'finished': Finished()
    }

    def __init__(self, start_scene):
        self.start_scene = start_scene

    def next_scene(self, scene_name):
        val = Map.scenes.get(scene_name)
        return val

    def opening_scene(self):
        return self.next_scene(self.start_scene)

# Finally the code that runs the game by making a Map, handing that map to
# an Engine before calling play to make game work.
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
```

<p>I'm trying to understand what's going on here, but I don't see it. I've also deleted two of the larger classes because they don't seem to be at issue here. </p>

<p>EDIT: The return I'm putting in is:</p>

```(base) ➜  Python python ex43.py
```

<p>Then,</p>

```dodge!
```

<p>This returns:</p>

```Like a world class boxer you dodge, weave, slip and slide right as the Gothon's blaster cranks a laser past your head. In the middle of your artful dodge your foot slips and you bang your head on the metal wall and pass out.  You wake up shortly after only to die as the Gothon stomps on your head and eats you.

You're worse than your Dad's jokes. Traceback (most recent call last): File "ex43.py", line 283, in <module>
    a_game.play()   File "ex43.py", line 45, in play
    next_scene_name = current_scene.enter() AttributeError: 'NoneType' object has no attribute 'enter'
```

答:
As the error says,

```<code>next_scene_name = current_scene.enter() AttributeError: 'Nonetype' object has no attribute 'enter'
</code>```

That means that your current_scene variable is equal to None when you call current_scene.enter() in the play method. You need to make sure the variable current_scene is properly instantiated so that its not None. One way to debug this is to add a print(current_scene) line right after every mention of current_scene. This will tell you when its equal to None in your code.

Body:
Very sorry in advance for the long paste.

The code is straight from the text. It may be due to class Scene, that seems to have the instruction to: subclass it and implement enter(). But I don't know what that means.

from sys import exit
from random import randint
from textwrap import dedent

class Scene(object):

    def enter(self):
        print("This scene is not yet configured.")
        print("Subclass it and implement enter()")
        exit(1)
# Skeleton code: a base class for Scene that will have
# the common things that all scenes do.

class Engine(object):

    def __init__(self, scene_map):
        self.scene_map = scene_map

    def play(self):
        current_scene = self.scene_map.opening_scene()
        last_scene = self.scene_map.next_scene('finished')

        while current_scene != last_scene:
            next_scene_name = current_scene.enter()
            current_scene = self.scene_map.next_scene(next_scene_name)

        # be sure to print out the last scene
        current_scene.enter()

class Death(Scene):

    quips = [
        "You died.  You kinda suck at this.",
        "Your Mom would be proud...if she were smarter.",
        "Such a luser.",
        "I have a small puppy that's better at this.",
        "You're worse than your Dad's jokes."

    ]

    def enter(self):
        print(Death.quips[randint(0, len(self.quips)-1)])

class CentralCorridor(Scene):

    def enter(self):
        print(dedent("""
            The Gothons of Planet Percal #25 have invaded your ship and
            destroyed your entire crew.  You are the last surviving member
            member and your last mission is to get the neutron destruct
            bomb from the Weapons Armory, put it in the bridge, and
            blow the ship up after getting into an escape pod.

            You're running down the central corridor to the Weapons
            Armory when a Gothon jumps out, red scaly skin, dark grimy
            teeth, and evil clown costume flowing around his hate
            filled body.  He's blocking the door to the Armory and
            about to pull a weapon to blast you.
            """))

        action = input("> ")

        if action == "shoot!":
            print(dedent("""
                Quick on the draw you yank out your blaster and fire
                it at the Gothon.  His clown costume is flowing and
                moving around his body, which throws off your aim.
                Your laster hits his costume but misses him entirely.
                This completely ruins his brand new costume his mother
                bought him, which makes him fly into an insane rage
                and blast you repeatedly in the face until you are
                dead.  Then he eats you.
                """))
            return 'death'

        elif action == "dodge!":
            print(dedent("""
                Like a world class boxer you dodge, weave, slip and
                slide right as the Gothon's blaster cranks a laser
                past your head. In the middle of your artful dodge
                your foot slips and you bang your head on the metal
                wall and pass out.  You wake up shortly after only to
                die as the Gothon stomps on your head and eats you.
                """))
            return 'death'

        elif action == "tell a joke":
            print(dedent("""
                Lucky for you they made you learn Gothon insults in
                the academy.  You tell the one Gothon joke you know:
                Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr,
                fur fvgf nebhaq gur ubhfr.  The Gothon stops, tries
                not to laugh, then busts out laughing and can't move.
                While he's laughing you run up and shoot him square in
                the head putting him down, then jump through the
                Weapon Armory door.
                """))
            return 'laster_weapon_armory'

        else:
            print("DOES NOT COMPUTE!")
            return 'central_corridor'

class LaserWeaponArmory(Scene):

    def enter(self):
        print(dedent("""
            You do a dive roll into the Weapon Armory, crouch and scan
            the room for more GOthon that might be hiding. It's dead
            quiet, too quiet.  You stand up and run to the far side of
            the room and find the neutron bomb in its container.
            There's a keypad lock on the box and you need the code to
            get the bomb out. If you get the code wrong 10 times then
            the lock closes forever and you can't get the bomb.  The
            code is 3 digits.
            """))

        code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
        guess = input("[keypad]> ")
        guesses = 0

        while guess != code and guesses <10:
            print("BZZZZEDDD!")
            guesses += 1
            guess = input("[keypad]> ")

        if guess == code:
            print(dedent("""
                The container clicks open and the seal breaks, letting
                gas out.  You grab the neutron bomb and run as fast as
                you can to the bridge where you must place it in the
                right spot.
                """))
            return 'the_bridge'
        else:
            print(dedent("""
                The lock buzzes one last time and then you hear a
                sickening melting sound as the mechanism is fused
                together.  You decide to sit there, and finally the
                Gothons blow up the ship from their ship and you die.
                """))
            return 'death'

class Finished(Scene):

    def enter(self):
        print("You won! Good job.")
        return 'finished'

class Map(object):

    scenes = {
        'central_corridor': CentralCorridor(),
        'laster_weapon_armory': LaserWeaponArmory(),
        'the_bridge': TheBridge(),
        'escape_pod': EscapePod(),
        'death': Death(),
        'finished': Finished()
    }

    def __init__(self, start_scene):
        self.start_scene = start_scene

    def next_scene(self, scene_name):
        val = Map.scenes.get(scene_name)
        return val

    def opening_scene(self):
        return self.next_scene(self.start_scene)

# Finally the code that runs the game by making a Map, handing that map to
# an Engine before calling play to make game work.
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()

I'm trying to understand what's going on here, but I don't see it. I've also deleted two of the larger classes because they don't seem to be at issue here.

EDIT: The return I'm putting in is:

(base) ➜  Python python ex43.py

Then,

dodge!

This returns:

Like a world class boxer you dodge, weave, slip and slide right as the Gothon's blaster cranks a laser past your head. In the middle of your artful dodge your foot slips and you bang your head on the metal wall and pass out.  You wake up shortly after only to die as the Gothon stomps on your head and eats you.

You're worse than your Dad's jokes. Traceback (most recent call last): File "ex43.py", line 283, in <module>
    a_game.play()   File "ex43.py", line 45, in play
    next_scene_name = current_scene.enter() AttributeError: 'NoneType' object has no attribute 'enter'

Body:
As the error says,

next_scene_name = current_scene.enter() AttributeError: 'Nonetype' object has no attribute 'enter'

That means that your current_scene variable is equal to None when you call current_scene.enter() in the play method. You need to make sure the variable current_scene is properly instantiated so that its not None. One way to debug this is to add a print(current_scene) line right after every mention of current_scene. This will tell you when its equal to None in your code.


问:
AWS Lambda and MongoDB
I'm new to AWS Lambda and interested in trying it. I have a MongoDB instance that I want to connect to through my AWS lambda function. How would I connect to my mongo instance? I can't load pymongo onto AWS Lambda so how would I get this to work in the Lambda function? </p>

```<code>client = MongoClient()
client = MongoClient("mongodb://xxxxxx:27017 username user --password")
</code>```

答:
make a virutalenv something like "venv" and run pip3 install pymongo in your local system

then make a new folder that has all the packages of the venv installed (copy from venv --> lib --> python 3.x --> site packages)

copy your lambda python file also into the same folder you have the pacakges

then zip the folder and you see a upload zip file in aws lambda function, upload it and save

note that, your lambda function py file is named as "lambda_file" and lambda function inside it is named as "lamda_function" then change the name in handler info in aws lambda placed in third column

like this lambda_file.lambda_function

Title: AWS Lambda and MongoDB

Body:
I'm new to AWS Lambda and interested in trying it. I have a MongoDB instance that I want to connect to through my AWS lambda function. How would I connect to my mongo instance? I can't load pymongo onto AWS Lambda so how would I get this to work in the Lambda function?

client = MongoClient()
client = MongoClient("mongodb://xxxxxx:27017 username user --password")


问:
Removing an item and its children in ngrx
I am new to ngrx store and confused with the placement of logic i.e whether looping through array should go to reducer or component. I have an array of objects of type Item and have to delete an item. While deleting an item, I have to delete its reference in parent's children as well as all its children.

```<code>    export class Item {
      id: string;
      message: string;
      children: string[];
    }

</code>```

The children property of Item contains ids of objects of type Item itself.

```<code>    Items: Item[] = [
     {id: "1", "message": "First Message" , children:["4","5"]},
     {id: "2", "message": "Seccond message" , children:["3"]},
     {id: "3", "message": "First child Message" , children:[]},
     {id: "4", "message": "Second child message" , children:["6"]},
     {id: "5", "message": "third child message" , children:[]},
     {id: "6", "message": "child message" , children:[]},
    ]

</code>```

I have to remove an item and it's corresponding children from the array on dispatch of action "DeleteItemByID" e.g. if I am deleting an item with id=4, it updates the item with id="1" and remove the "4" from its children's array. The delete action then deletes the children of the item which is the item with id="6" and then finally deletes the item with id="4".

```<code>    Items: Item[] = [
     {id: "1", "message": "First Message" , children:["5"]},
     {id: "2", "message": "Second message" , children:["3"]},
     {id: "3", "message": "First child Message" , children:[]},
     {id: "5", "message": "third child message" , children:[]},
    ]

    export class DeleteItemByID implements Action {
        readonly type = "DeleteById";
     /**
      * Constructor
      * @param payload The id of the discussion to remove
      */
        constructor(public payload: string) { }
    }

    /*App state*/
    export class AppState{
        items: Item[]
    }

    /* reducer */
    export function reducer(state: AppState = [], action  ) : AppState{
       switch (action.type) {
            case "DeleteById":
                /* Delete Logic*/
                return {};
            default:
                return state;
    }
</code>```

Help me out the best approach I should be taking for delete operation.

答:
They correct answer will differ case to case,

Case 1:-
  If you want to reuse this deletion behavior at multiple places, i.e. at multiple components/services. Create two different actions i.e. DeleteChildrenItemById and DeleteItemById.

OR

You can create a service method which will delete required items from array and dispatch a whole new array to reducer to replace existing one, that will help you avoid complex login in reducer.

Case 2 :- If this behavior is only required for this component then do the deletion in component and dispatch this new array to reducer.

Body:
I am new to ngrx store and confused with the placement of logic i.e whether looping through array should go to reducer or component. I have an array of objects of type Item and have to delete an item. While deleting an item, I have to delete its reference in parent's children as well as all its children.

    export class Item {
      id: string;
      message: string;
      children: string[];
    }

The children property of Item contains ids of objects of type Item itself.

    Items: Item[] = [
     {id: "1", "message": "First Message" , children:["4","5"]},
     {id: "2", "message": "Seccond message" , children:["3"]},
     {id: "3", "message": "First child Message" , children:[]},
     {id: "4", "message": "Second child message" , children:["6"]},
     {id: "5", "message": "third child message" , children:[]},
     {id: "6", "message": "child message" , children:[]},
    ]

I have to remove an item and it's corresponding children from the array on dispatch of action "DeleteItemByID" e.g. if I am deleting an item with id=4, it updates the item with id="1" and remove the "4" from its children's array. The delete action then deletes the children of the item which is the item with id="6" and then finally deletes the item with id="4".

    Items: Item[] = [
     {id: "1", "message": "First Message" , children:["5"]},
     {id: "2", "message": "Second message" , children:["3"]},
     {id: "3", "message": "First child Message" , children:[]},
     {id: "5", "message": "third child message" , children:[]},
    ]

    export class DeleteItemByID implements Action {
        readonly type = "DeleteById";
     /**
      * Constructor
      * @param payload The id of the discussion to remove
      */
        constructor(public payload: string) { }
    }

    /*App state*/
    export class AppState{
        items: Item[]
    }

    /* reducer */
    export function reducer(state: AppState = [], action  ) : AppState{
       switch (action.type) {
            case "DeleteById":
                /* Delete Logic*/
                return {};
            default:
                return state;
    }

Help me out the best approach I should be taking for delete operation.


问:
How to return boolean "if-then-else" statement in a single return
I am getting a sonar issue of Replace this if-then-else statement by a single return statement. As I have three conditions in the if condition, how can I return this without if-else?

```<code>  public boolean isDateRangeExceedOneYear(CardPluginInterface plugin, Date begin, Date end)
  {
    if (!DateTimeToolkit.getInstance().isEmpty(begin)
        && ((CardValidatorInterface) plugin).isValidateYearDateRangeFor()
        && DateTimeToolkit.getInstance().compare(
        DateTimeToolkit.getInstance().add(new DateTime(begin, new Time((short) 0, (short) 0, (short) 0)), 1, 1).date,
        end) <= 0)
    {
      return true;
    }
    else
    {
      return false;
    }
  }
</code>```

答:
For the above you can use</p>

```<code>return !DateTimeToolkit.getInstance().isEmpty(begin)
    && ((CardValidatorInterface) plugin).isValidateYearDateRangeFor()
    && DateTimeToolkit.getInstance().compare(
    DateTimeToolkit.getInstance().add(new DateTime(begin, new Time((short) 0, (short) 0, (short) 0)), 1, 1).date,
    end) <= 0;
</code>```

Body:
I am getting a sonar issue of Replace this if-then-else statement by a single return statement. As I have three conditions in the if condition, how can I return this without if-else?

  public boolean isDateRangeExceedOneYear(CardPluginInterface plugin, Date begin, Date end)
  {
    if (!DateTimeToolkit.getInstance().isEmpty(begin)
        && ((CardValidatorInterface) plugin).isValidateYearDateRangeFor()
        && DateTimeToolkit.getInstance().compare(
        DateTimeToolkit.getInstance().add(new DateTime(begin, new Time((short) 0, (short) 0, (short) 0)), 1, 1).date,
        end) <= 0)
    {
      return true;
    }
    else
    {
      return false;
    }
  }

Body:
For the above you can use

return !DateTimeToolkit.getInstance().isEmpty(begin)
    && ((CardValidatorInterface) plugin).isValidateYearDateRangeFor()
    && DateTimeToolkit.getInstance().compare(
    DateTimeToolkit.getInstance().add(new DateTime(begin, new Time((short) 0, (short) 0, (short) 0)), 1, 1).date,
    end) <= 0;


问:
Adding Language to tesseract 4 on macOS?
I have tesseract 4 installed. It works with German, English etc. I want to add a language, say Latin.

I have downloaded the file lat.traineddata from here, for tesseract 4. Now I'd like to install this file so that I can use it with tesseract. How do I do this?

答: I think just running brew install tesseract-lang should work fine on OSX.


问:
(iphone) inAppPurchase when to log purchase history in own server?
I'd like to record purchase history in my server.

Problem is,

I shouldn't log it until purchase is complete.(because the purchase might fail)

But if I log it after purchase's completion, user might stop the application and app might fail to send the purchase history message to server.

I originally thought "logging purchase history" when user verifies the receipt(when my server gets the verification of receipt from apple server).

But user might go through receipt verification stage several times without actually completing the purchase? (i'm not sure about this)

Is there a recommended way of storing in-app-purchase buy history in server model?

答:
You can temporarily persist the purchase log using NSUserDefaults upon purchase completion and sync it to server afterwards.

You can block the UI until purchase is completed AND the purchase log is pushed to server.


问:
Is it legal to use \\ in // C++ comment? (LaTeX equation in C++ comment)
For documentation purpose I need to add some LaTeX equations in my C++ comments, by example:

```<code>//
// \begin{eqnarray*}
//   y_1 &=& x_1 \\
//   y_2 &=& x_2
// \end{eqnarray*}
//
int main() {}
</code>```

With clang++ (version 9.0.1-10) I can compile my code without problem:

```<code>clang++ -Wall prog.cpp
</code>```

but with g++ (version 9.2.1)

```<code>g++ -Wall prog.cpp
</code>```

I get this warning:

```<code>prog.cpp:3:1: warning: multi-line comment [-Wcomment]
    3 | //   y_1 &=& x_1 \\
      | ^
</code>```

My question: which compiler is right? Can I legally use \\ inside C++ // comment?

答:
Is it legal? Yes. Is it error prone? Yes. That's why you are getting a warning.

The C/C++ standard has one token above all (processed first): \

This token removes the line break. Consider the following code:

```<code>1.  // the below code is commented out \
2.  despite not having a comment at the beginning of the line
3.
4.  // it's important to be careful because \\
5.  int not_compiled_code = 0;
6.  // the above code is not compiled.
</code>```

Despite stackoverflow's syntax highlighting, lines 2 and 5 are not compiled.

In case you're wondering, the next tokens are // and /*.

```<code>// /* incomplete block comment
int compiled_code = 0;

/*
// this entire line isn't commented */ int compiled_code_2 = 0;
</code>```

which compiler is right?

Both, because warnings are irrelevant to the standard. They compiled successfully and that's all that matters - they both conformed properly to the standard.

Body:
For documentation purpose I need to add some LaTeX equations in my C++ comments, by example:

//
// \begin{eqnarray*}
//   y_1 &=& x_1 \\
//   y_2 &=& x_2
// \end{eqnarray*}
//
int main() {}

With clang++ (version 9.0.1-10) I can compile my code without problem:

clang++ -Wall prog.cpp

but with g++ (version 9.2.1)

g++ -Wall prog.cpp

I get this warning:

prog.cpp:3:1: warning: multi-line comment [-Wcomment]
    3 | //   y_1 &=& x_1 \\
      | ^

My question: which compiler is right? Can I legally use \\ inside C++ // comment?

Body:
Is it legal? Yes. Is it error prone? Yes. That's why you are getting a warning.

The C/C++ standard has one token above all (processed first): \

This token removes the line break. Consider the following code:

1.  // the below code is commented out \
2.  despite not having a comment at the beginning of the line
3.
4.  // it's important to be careful because \\
5.  int not_compiled_code = 0;
6.  // the above code is not compiled.

Despite stackoverflow's syntax highlighting, lines 2 and 5 are not compiled.

In case you're wondering, the next tokens are // and /*.

// /* incomplete block comment
int compiled_code = 0;

/*
// this entire line isn't commented */ int compiled_code_2 = 0;

which compiler is right?

Both, because warnings are irrelevant to the standard. They compiled successfully and that's all that matters - they both conformed properly to the standard.


问:
python3 send() function in generators
According to docs, the send() function:

"Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. When send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receive the value."

But i can't understand, why "The value argument becomes the result of the current yield expression" is not happened in the following example:

```<code>def gen():
    yield 1
    x = (yield 42)
    print(x)
    yield 2

>>>c=gen() #create generator
>>>next(c) #prints '1' and stop execution, which is caused by yield 1
>>>c.send(100) #prints '42', because 'The send() method returns the next value yielded by the generator'
>>>next(c) #prints 'None' and '2'
</code>```

So why x variable stays 'None' dispite i send 100 to it by c.send(100)? It seems, that yield expression in right hand side works in two steps: first it return the value to generator's caller and the second it returns argument of send function inside generator. And if add extra next(c) before send(42) i'll get expected behavior and programm prints '100'. It's not clear for me from documentation, why these two steps should not happen simultaneously when i call send().

答:
From documentation:
The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator.

assume we have following infinite generator:

```<code>def infgen():
    a = 0
    while True:
        a = yield a
        a += 1

generato = infgen()

generato.send(None)
</code>```

output:0

.send(None) is executed almost the same as next()

now we have yeild first value of a = 0  and

code stopped here a = yield a

as value becomes result of the current yield expression

yielded expression is yield a. Result of yielded expresion is a

```<code>generato.send(5)
</code>```

.send(5) we send 5 to a in generator and it continue:

Result of yielded expresion is a = 5

a = 5

a += 1

Go to while loop with a = 5 + 1 = 6

And stops and yield a where a is 6

output:6

Title: python3 send() function in generators

Body:
According to docs, the send() function:

"Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. When send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receive the value."

But i can't understand, why "The value argument becomes the result of the current yield expression" is not happened in the following example:

def gen():
    yield 1
    x = (yield 42)
    print(x)
    yield 2

>>>c=gen() #create generator
>>>next(c) #prints '1' and stop execution, which is caused by yield 1
>>>c.send(100) #prints '42', because 'The send() method returns the next value yielded by the generator'
>>>next(c) #prints 'None' and '2'

So why x variable stays 'None' dispite i send 100 to it by c.send(100)? It seems, that yield expression in right hand side works in two steps: first it return the value to generator's caller and the second it returns argument of send function inside generator. And if add extra next(c) before send(42) i'll get expected behavior and programm prints '100'. It's not clear for me from documentation, why these two steps should not happen simultaneously when i call send().

Body:
From documentation:
The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator.

assume we have following infinite generator:

def infgen():
    a = 0
    while True:
        a = yield a
        a += 1

generato = infgen()

generato.send(None)

output:0

.send(None) is executed almost the same as next()

now we have yeild first value of a = 0  and

code stopped here a = yield a

as value becomes result of the current yield expression

yielded expression is yield a. Result of yielded expresion is a

generato.send(5)

.send(5) we send 5 to a in generator and it continue:

Result of yielded expresion is a = 5

a = 5

a += 1

Go to while loop with a = 5 + 1 = 6

And stops and yield a where a is 6

output:6


问:
Angular post request sending empty body to node.js server
I am trying to post form data from angular to node.js. The angular post request sends an empty body.
this is my post router
submit function is ts file

```<code>  onSubmit( loginData ) {
if(!loginData) { return; }
this.userService.addUser( loginData as User  )
  .subscribe(user => {
    this.users.push(user);
  });
</code>```

service used to post data

```<code>   addUser(user: User): Observable<User> {
    // console.log('this is '+user.email);
    const url = `${this.usersUrl}/register`;
    return this.http.post<User>(url, user).pipe(
      tap((newUser: User) => this.log(`added user w/ email=${newUser.email}`)),
      catchError(this.handleError<User>('addUser'))
    );
  }
</code>```

答:
I figured out the problem.
There is no problem in this angular code.
I also checked the network tab as suggested by David, and saw that the payload was being sent.
the problem was this line of code in my node.js server

```<code>app.use(express.static('public'))
</code>```

Instead I had to use

```<code>app.use(exrpess.json())
</code>```

I had copied the template from another application and somehow missed this. Anyway thanks for all your help!

Body:
I am trying to post form data from angular to node.js. The angular post request sends an empty body.
this is my post router
submit function is ts file

  onSubmit( loginData ) {
if(!loginData) { return; }
this.userService.addUser( loginData as User  )
  .subscribe(user => {
    this.users.push(user);
  });

service used to post data

   addUser(user: User): Observable<User> {
    // console.log('this is '+user.email);
    const url = `${this.usersUrl}/register`;
    return this.http.post<User>(url, user).pipe(
      tap((newUser: User) => this.log(`added user w/ email=${newUser.email}`)),
      catchError(this.handleError<User>('addUser'))
    );
  }

Body:
I figured out the problem.
There is no problem in this angular code.
I also checked the network tab as suggested by David, and saw that the payload was being sent.
the problem was this line of code in my node.js server

app.use(express.static('public'))

Instead I had to use

app.use(exrpess.json())

I had copied the template from another application and somehow missed this. Anyway thanks for all your help!


问:
how to remove sublime option in right click, i used a .bat file?

*how to remove sublime option in the open with menu. I tried to find .bat file but no progress or say not found it.

Sublime Text 3, how to add to right click?
from here i used that script.

答:
Maybe you should try this.. work for me

```<code>@echo off
@reg delete "HKEY_CLASSES_ROOT\*\shell\Open with Sublime Text 3"
@reg delete "HKEY_CLASSES_ROOT\*\shell\Open with Sublime Text 3"
@reg delete "HKEY_CLASSES_ROOT\*\shell\Open with Sublime Text 3\command"
@reg delete "HKEY_CLASSES_ROOT\Folder\shell\Open with Sublime Text 3"
@reg delete "HKEY_CLASSES_ROOT\Folder\shell\Open with Sublime Text 3"
@reg delete "HKEY_CLASSES_ROOT\Folder\shell\Open with Sublime Text 3\command"
</code>```

Body:
Maybe you should try this.. work for me

@echo off
@reg delete "HKEY_CLASSES_ROOT\*\shell\Open with Sublime Text 3"
@reg delete "HKEY_CLASSES_ROOT\*\shell\Open with Sublime Text 3"
@reg delete "HKEY_CLASSES_ROOT\*\shell\Open with Sublime Text 3\command"
@reg delete "HKEY_CLASSES_ROOT\Folder\shell\Open with Sublime Text 3"
@reg delete "HKEY_CLASSES_ROOT\Folder\shell\Open with Sublime Text 3"
@reg delete "HKEY_CLASSES_ROOT\Folder\shell\Open with Sublime Text 3\command"


问:
Selectable panel in Swing
I´m trying to make something similar to the downloads panel of Transmission BT (here an image: http://www.transmissionbt.com/images/screenshots/Mac-Large.jpg) but I´m having some problems.
I made a JPanel with the progress bar, labels, icon and buttons and then added this panel to a container (JPanel again) but I need to make this component selectable.

How can I do this?

答:
Dont you think  A table would be easier with this? It has al the functions you need. JUst create a table on a FRAME and then remove the headers so you just have the table. In this was you can easily handle what was selected..

Another way is to use a grid layout that changes on each addition and then each section of the column grid should have a panel. Each panel should have a mouse listener for a click. When clicked you just change the background color.

They are stil more ways of handling this so these are just two.

Goodluck

Title: Selectable panel in Swing


问:
Issues converting HTML to PDF using DomPDF
I am trying to convert a HTML content with CSS and custom fonts and images to PDF using DomPDF.

I need to add these custom fonts also the alignments has to be perfect, since the content is made for responsive look, i cannot modify most of them.

Following is the HTML content.

```<code><html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="assets/css/material-dashboard.min.css?v=2.1.2" rel="stylesheet">
    <title>Document</title>
    <style>
        @font-face {
  font-family: Eutemia;
  src: url(assets/fonts/Eutemia.ttf);
}
@font-face {
  font-family: Pecita;
  src: url(assets/fonts/Pecita.ttf);
}
@font-face {
  font-family: Scribble;
  src: url(assets/fonts/Scribble.ttf);
}
@font-face {
  font-family: SFBurlingtonScript;
  src: url(assets/fonts/SFBurlingtonScript.ttf);
}
@font-face {
  font-family: DancingScript-Regular;
  src: url(assets/fonts/DancingScript-Regular.ttf);
}
@font-face {
  font-family: dotmatrix;
  src: url(assets/fonts/dotmatrix.ttf);
}
.signature1{
  font-family: Eutemia;
  color: black;
  font-size: 50px;
}
.signature2{
  font-family: Pecita;
  color: black;
  font-size: 50px;
}
.signature3{
  font-family: Scribble;
  color: black;
  font-size: 50px;
}
.signature4{
  font-family: SFBurlingtonScript;
  color: black;
  font-size: 50px;
}
.clinic-title{
  font-family: DancingScript-Regular;
  color: #0067b1;
  text-align: center;
  font-size:5.7vmax ;

}
.clinic-footer-text{
  color: #ff0000;
  font-size: 10px;
}

hr.clinic-line {
  border: 1.5px solid#0067b1;
}
.clinic-text{
  color: #0067b1;
}
.doc-name{
  font-size: 20px;
  font-weight: bold;
}
.dot-matrix{
  font-family: dotmatrix;
  color: #000;
  font-size: 25px;
}
    </style>
</head>
<body>
    <div class="pdf-generation">
        <div class="col-md-12">
          <div class="card">
            <div class="card-body text-center">

        <div class="container" id="html2pdf">
                <div class="row">
                  <div class="col-md-12">
                    <h4 class="text-right unique-roll">SNMC-060120-1001</h4>
                  </div>
                    <div class="col-md-2">
                      <img src="assets/img/SNMC.png" width="120" height="120">
                    </div>
                    <div class="col-md-10">
                      <div class="clinic-title"><br><br>
                        Senthivel Nadar Memorial Clinic
                      </div>
                    </div>
                    <div class="col-md-12">
                      <hr class="clinic-line">
                    </div>
                    <div class="col-md-12">
                      <div class="doc-name clinic-text text-center">test</div>
                    </div>
                    <div class="col-md-12">
                      <hr class="clinic-line">
                    </div>
                    <div class="col-md-5">
                      <div class="clinic-text patient-name">Name: wefwe</div>
                    </div>
                    <div class="col-md-3">
                      <div class="clinic-text today-date">Date: 01/06/2020</div>
                    </div>
                    <div class="col-md-2">
                      <div class="clinic-text patient-sex">Sex: male</div>
                    </div>
                    <div class="col-md-2">
                      <div class="clinic-text patient-age">Age: 23</div>
                    </div>
                    <div class="col-md-12">
                      <hr class="clinic-line">
                    </div>
                    <div class="col-md-12">
                      <div class="table-responsive">
                        <table class="table" id="prescribed-medicine">
                            <thead>
                              <tr>
                                <th class="text-center">#</th>
                                <th>Component</th>
                                <th>Brand</th>
                                <th>Type</th>
                                <th>Consumption</th>
                                <th>Dosage</th>
                                <th>Duration</th>
                                <th>Interval</th>
                                <th>Intake Period</th>

                              </tr>
                            <tr><td>1</td><td>test</td><td>test2 </td><td>test4</td><td>after food  உணவுக்குப் பிறகு</td><td>200 milliliter(s) 200 மில்லிலிட்டர் (கள்)</td><td>6 days 6 நாட்கள்</td><td>nil இல்லை</td><td>morning  evening காலை மாலை</td></tr></thead>
                            <tbody>
                            </tbody>
                          </table>
                      </div>
                    </div>
                    <div class="col-md-3 ml-auto">
                        <div class="text-center">
                          <div class="form-check">
                            <div class="clinic-text">Doctor's Signature</div>
                        </div>
                          <div class="form-check">
                              <div class="sheet-sign addSignName signature3">sample</div>
                          </div>
                        </div>
                    </div>
                    <div class="col-md-12">
                      <hr class="clinic-line">
                    </div>
                    <div class="col-md-12">
                      <div class="text-center">
                          <div class="form-check">
                            <div class="clinic-text">செந்திவேல் நாடார் நினைவு மருத்துவமனை</div>
                        </div>
                        <div class="form-check">
                          <div class="clinic-footer-text">45 மெயின் ரோடு, எம். செந்திவேல் நாடார் பில்டிங், பணக்குடி - 627109 Ph: + 91-4637-245012</div>
                      </div>
                      </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

</body>
</html>
</code>```

and the PHP code.

```<code>require_once 'dompdf/autoload.inc.php';
ob_start();
use Dompdf\Dompdf;

$html = ob_get_contents();
$dompdf = new Dompdf();
$dompdf->load_html($html);
$dompdf->render();
$output = $dompdf->output();
file_put_contents('test.pdf', $output);
</code>```

while the result should look something like this...

this is what i get...

is the CSS not loading or am i doing something wrong?
Any help is appreciated.

答:
Dompdf is not a CSS friendly and compatible with CSS 2.1 .

You use bootstrap framework and bootstrap, use modern css and this for dompdf not pleasant.

I suggest you writing pure CSS code for this work.

Body:
I am trying to convert a HTML content with CSS and custom fonts and images to PDF using DomPDF.

I need to add these custom fonts also the alignments has to be perfect, since the content is made for responsive look, i cannot modify most of them.

Following is the HTML content.

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="assets/css/material-dashboard.min.css?v=2.1.2" rel="stylesheet">
    <title>Document</title>

SNMC-060120-1001

                        Senthivel Nadar Memorial Clinic

test

Name: wefwe

Date: 01/06/2020

Sex: male

Age: 23

                                #
                                Component
                                Brand
                                Type
                                Consumption
                                Dosage
                                Duration
                                Interval
                                Intake Period

1	test	test2 	test4	after food  உணவுக்குப் பிறகு	200 milliliter(s) 200 மில்லிலிட்டர் (கள்)	6 days 6 நாட்கள்	nil இல்லை	morning  evening காலை மாலை

Doctor's Signature

sample

செந்திவேல் நாடார் நினைவு மருத்துவமனை

45 மெயின் ரோடு, எம். செந்திவேல் நாடார் பில்டிங், பணக்குடி - 627109 Ph: + 91-4637-245012

and the PHP code.

require_once 'dompdf/autoload.inc.php';
ob_start();
use Dompdf\Dompdf;

$html = ob_get_contents();
$dompdf = new Dompdf();
$dompdf->load_html($html);
$dompdf->render();
$output = $dompdf->output();
file_put_contents('test.pdf', $output);

while the result should look something like this...

this is what i get...

is the CSS not loading or am i doing something wrong?
Any help is appreciated.


问:
Modify numbers inside list with lambda and map functions in Python 3
for homework I need to create a function that receives 2 list of numbers and every time a number from the first list matches with one of the second one I have to add 10 to the number in the first list. Here's what I've tried.

```<code>def modifyEspecials(mylist,especials):
  return list(map(lambda n: str(int(n)+10) if map(lambda x: True if n==x else False,especials)== True else n,mylist))

if __name__ == "__main__":
  especials=[*range(39,48),*range(58,63),*range(91,97)]
  mylist= ['72', '45', '41', '56', '46', '56', '49', '45', '48', '41', '39', '46', '71', '52', '46', '56', '52', '46', '42']
  modifiedList= modifyEspecials(mylist,especials)
  print(modifiedList)
</code>```

This returns the same list.

Note: I can't create variables inside modifyEspecials() in this homework and I'm only allowed to import ascii_lowercase, ascii_uppercase and functools or for/while loops

答:
So if you have to use this overcomplicated methods to do so, there is 2 mistakes you do:

In the second map you compare string of int with ints

The second map returns an iterator of size especials

In order to overcome the first issue just transform to int, for the second issue just sum all elements after transforming to list, if there is at least 1 True than you should add 10

See the following fix:

```<code>def modifyEspecials(mylist,especials):
  return list(map(lambda n: str(int(n)+10) if sum(list(map(lambda x: True if int(n)==x else False, especials))) > 0 else n, mylist))

if __name__ == "__main__":
  especials=[*range(39,48),*range(58,63),*range(91,97)]
  mylist= ['72', '45', '41', '56', '46', '56', '49', '45', '48', '41', '39', '46', '71', '52', '46', '56', '52', '46', '42']
  modifiedList= modifyEspecials(mylist,especials)
  print(modifiedList)
</code>```

Note Although map and lambda are powerful, its not always advisable to use them where there is no need to.

Body:
for homework I need to create a function that receives 2 list of numbers and every time a number from the first list matches with one of the second one I have to add 10 to the number in the first list. Here's what I've tried.

def modifyEspecials(mylist,especials):
  return list(map(lambda n: str(int(n)+10) if map(lambda x: True if n==x else False,especials)== True else n,mylist))

if __name__ == "__main__":
  especials=[*range(39,48),*range(58,63),*range(91,97)]
  mylist= ['72', '45', '41', '56', '46', '56', '49', '45', '48', '41', '39', '46', '71', '52', '46', '56', '52', '46', '42']
  modifiedList= modifyEspecials(mylist,especials)
  print(modifiedList)

This returns the same list.

Note: I can't create variables inside modifyEspecials() in this homework and I'm only allowed to import ascii_lowercase, ascii_uppercase and functools or for/while loops

Body:
So if you have to use this overcomplicated methods to do so, there is 2 mistakes you do:

In the second map you compare string of int with ints

The second map returns an iterator of size especials

In order to overcome the first issue just transform to int, for the second issue just sum all elements after transforming to list, if there is at least 1 True than you should add 10

See the following fix:

def modifyEspecials(mylist,especials):
  return list(map(lambda n: str(int(n)+10) if sum(list(map(lambda x: True if int(n)==x else False, especials))) > 0 else n, mylist))

if __name__ == "__main__":
  especials=[*range(39,48),*range(58,63),*range(91,97)]
  mylist= ['72', '45', '41', '56', '46', '56', '49', '45', '48', '41', '39', '46', '71', '52', '46', '56', '52', '46', '42']
  modifiedList= modifyEspecials(mylist,especials)
  print(modifiedList)

Note Although map and lambda are powerful, its not always advisable to use them where there is no need to.


问:
C - Printing null character using %c in nested printf statement
Why both inner printf() functions are working different even the printing value is same for both functions ?
Here is the code -:</p>

```<code>#include<stdio.h>
int main()
{
    char ch = '\0';

    printf("%d",printf("%c", ch)) ;
    // This line will print 1.

    printf("%d",printf("\0")) ;
    // This line will print 0.
   return 0;
}
</code>```

答:
```<code> printf("%d", printf("%c", '\0'));
</code>```

Why this line prints 1?

The value '\0' is one single character, which "%c" sends th stdout (though you can't see it).

```<code> printf("%d", printf("%s", "\0"));
</code>```

Why this line prints 0?

The string "\0" has two characters in it: the literal '\0' and the implied '\0'. None of them are printed with "%s", the first zero terminates the string. The string "foo" has 4 characters: the 3 literal ones and the implied '\0'

Body:
Why both inner printf() functions are working different even the printing value is same for both functions ?
Here is the code -:

#include<stdio.h>
int main()
{
    char ch = '\0';

    printf("%d",printf("%c", ch)) ;
    // This line will print 1.

    printf("%d",printf("\0")) ;
    // This line will print 0.
   return 0;
}

Body:
 printf("%d", printf("%c", '\0'));

Why this line prints 1?

The value '\0' is one single character, which "%c" sends th stdout (though you can't see it).

 printf("%d", printf("%s", "\0"));

Why this line prints 0?

The string "\0" has two characters in it: the literal '\0' and the implied '\0'. None of them are printed with "%s", the first zero terminates the string. The string "foo" has 4 characters: the 3 literal ones and the implied '\0'


问:
Stress-ng - Overload Memory
I want to test the systems reaction to a process that wants to consume more memory than there is available.
I run stress-ng with the following command (on a 6G RAM machine):
stress-ng --vm-bytes 8G  --vm-keep -m 1 --aggressive
but I get this error:
stress-ng: error: [5035] stress-ng-vm: gave up trying to mmap, no available memory
Is it possible to force the program to ignore its own secure mechanism ?

答:
try to add this parameter --vm 4

I was having the same problem and it is gone after that.

Title: Stress-ng - Overload Memory


问:
A pattern that matches all except starting with a word
How can I set a regex pattern which matches all words but the strings which starts with

/word

/word/

/word/ following by anything else.

I think the pattern starts with  \A but I don'0t know how to tell that should not follow a word

Thanks

答:
Perhaps using a string comparison will be clearer and faster.</p>

```<code>if (text.startsWith("word")) {
   // text is OK
} else {
   // not OK
}
</code>```

Body:
Perhaps using a string comparison will be clearer and faster.

if (text.startsWith("word")) {
   // text is OK
} else {
   // not OK
}


问:
static methods can not run in a non-static context
I'm trying to simulate a game of Yahtzee by using various methods to roll, compare, and sum up dice.

This is an assignment and I'm required to use these three static methods to do all of my work in.

When I try to run my code however I get this error

```<code>exit status 1
Main.java:6: error: non-static method rollDice(int[]) cannot be referenced from a static context
   rollDice(dice);
   ^
Main.java:7: error: non-static method rollDice(int[]) cannot be referenced from a static context
   dice= rollDice(dice);
         ^
2 errors
</code>```

I tried running the methods before assigning the values they return to variables but that didn't seem to work. Here is my complete code:

```<code>class Main {
  public static void main(String[] args) {
  // int array to hold 5 dice

   int dice[] = new int[5];
   rollDice(dice);
   dice= rollDice(dice);

   fiveOfaKind(dice);
   int points = fiveOfaKind(dice);

   getChance(dice,points);
   int printpoint = getChance(dice,points);
   // You may roll the dice up to 3 times to try to get 5 of a Kind
   // If you get 5 of a Kind, stop if not keep trying.
   // If you do not get 5 of a Kind after the 3rd roll, you must take the
   // CHANCE score.

   System.out.println("Your score is " + printpoint);

  }// end of main method

  public int[] rollDice(int dice[]){
    // generate 5 random numbers / update dice array
     for (int i = 0; i < dice.length; i++) {
      dice[i] = (int)(Math.random() * 6 + 1);
     }
    return dice;

  }// end of rollDice - rolls 5 dice and puts them in an array
   // All 5 dice must be rolled each time

  public static int fiveOfaKind(int dice[]){
     int pts = 0;
     int rNum=0;

    for(int i=0; rNum<3; rNum++){
    if(dice[0]==dice[1]&&dice[1]==dice[2]&&dice[2]==dice[3]&&dice[3]==dice[4]&&dice[4]==dice[5]&&dice[5]==dice[6]){
      pts=50;
    }
    else if(rNum==3){
      pts=0;
    }
    else{
      int[] rollDice;
    }

    }//end of forloop

    // use Array dice - evaluate if all elements are equal
    // if true = pts = 50
    // if false - pts = 0

    return pts;

  }// end of fiveOfaKind - evaluates the dice roll to see if all 5 are equal
   // Returns 50 points if they do

  public static int getChance(int dice[], int points){

    if(points<50){
       points=0;
      for (int i = 0; i < dice.length; i++) {
         points+=dice[i];
      }
    }
    // use Array dice - sum the elements of the Array
    // pys = calculated value of the sum

    int p = points;

    return p;

  }// end of getChance - adds the total value of the dice
    // Returns the total points calculated

}// end of  class
</code>```

答:
To put it simply, static methods/fields are more like properties associated with the class and can be shared between objects of the class.

public int[] rollDice method doesn't have an existence unless you create an object of the class enclosing the method because it's non-static. Non-static methods are simply associated with each and every object you create. So, the objects you create will have their own set of properties that are not dependent on other objects and you can use these properties to maintain a state within that object.

Simple fix:

Make the method rollDice static (Recommended based on your program structure)

or

Call the method like this:

```<code>Main obj = new Main();
obj.rollDice(dice);
</code>```

I will recommend you go through this article (Static vs Non-Static) if you don't know the difference between the two. It's really important to understand it in terms of Object-oriented programming.

Body:
I'm trying to simulate a game of Yahtzee by using various methods to roll, compare, and sum up dice.

This is an assignment and I'm required to use these three static methods to do all of my work in.

When I try to run my code however I get this error

exit status 1
Main.java:6: error: non-static method rollDice(int[]) cannot be referenced from a static context
   rollDice(dice);
   ^
Main.java:7: error: non-static method rollDice(int[]) cannot be referenced from a static context
   dice= rollDice(dice);
         ^
2 errors

I tried running the methods before assigning the values they return to variables but that didn't seem to work. Here is my complete code:

class Main {
  public static void main(String[] args) {
  // int array to hold 5 dice

   int dice[] = new int[5];
   rollDice(dice);
   dice= rollDice(dice);

   fiveOfaKind(dice);
   int points = fiveOfaKind(dice);

   getChance(dice,points);
   int printpoint = getChance(dice,points);
   // You may roll the dice up to 3 times to try to get 5 of a Kind
   // If you get 5 of a Kind, stop if not keep trying.
   // If you do not get 5 of a Kind after the 3rd roll, you must take the
   // CHANCE score.

   System.out.println("Your score is " + printpoint);

  }// end of main method

  public int[] rollDice(int dice[]){
    // generate 5 random numbers / update dice array
     for (int i = 0; i < dice.length; i++) {
      dice[i] = (int)(Math.random() * 6 + 1);
     }
    return dice;

  }// end of rollDice - rolls 5 dice and puts them in an array
   // All 5 dice must be rolled each time

  public static int fiveOfaKind(int dice[]){
     int pts = 0;
     int rNum=0;

    for(int i=0; rNum<3; rNum++){
    if(dice[0]==dice[1]&&dice[1]==dice[2]&&dice[2]==dice[3]&&dice[3]==dice[4]&&dice[4]==dice[5]&&dice[5]==dice[6]){
      pts=50;
    }
    else if(rNum==3){
      pts=0;
    }
    else{
      int[] rollDice;
    }

    }//end of forloop

    // use Array dice - evaluate if all elements are equal
    // if true = pts = 50
    // if false - pts = 0

    return pts;

  }// end of fiveOfaKind - evaluates the dice roll to see if all 5 are equal
   // Returns 50 points if they do

  public static int getChance(int dice[], int points){

    if(points<50){
       points=0;
      for (int i = 0; i < dice.length; i++) {
         points+=dice[i];
      }
    }
    // use Array dice - sum the elements of the Array
    // pys = calculated value of the sum

    int p = points;

    return p;

  }// end of getChance - adds the total value of the dice
    // Returns the total points calculated

}// end of  class

Body:
To put it simply, static methods/fields are more like properties associated with the class and can be shared between objects of the class.

public int[] rollDice method doesn't have an existence unless you create an object of the class enclosing the method because it's non-static. Non-static methods are simply associated with each and every object you create. So, the objects you create will have their own set of properties that are not dependent on other objects and you can use these properties to maintain a state within that object.

Simple fix:

Make the method rollDice static (Recommended based on your program structure)

or

Call the method like this:

Main obj = new Main();
obj.rollDice(dice);

I will recommend you go through this article (Static vs Non-Static) if you don't know the difference between the two. It's really important to understand it in terms of Object-oriented programming.


问:
How to fix this bazel project for kotlin?
I want to be able to use bazel to organize a simple kotlin project.

I am using the templates as listed in rules_kotlin (https://github.com/bazelbuild/rules_kotlin)

This is my BUILD file

```<code>load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kt_jvm_library")

kt_jvm_library(
    name = "redis-tools",
    srcs = glob(["*.kt"]),
    deps = [],
)
</code>```

This is my WORKSPACE file

```<code>load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

rules_kotlin_version = "legacy-1.3.0"
rules_kotlin_sha = "4fd769fb0db5d3c6240df8a9500515775101964eebdf85a3f9f0511130885fde"
http_archive(
    name = "io_bazel_rules_kotlin",
    urls = ["https://github.com/bazelbuild/rules_kotlin/archive/%s.zip" % rules_kotlin_version],
    type = "zip",
    strip_prefix = "rules_kotlin-%s" % rules_kotlin_version,
    sha256 = rules_kotlin_sha,
)

load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kotlin_repositories", "kt_register_toolchains")
kotlin_repositories() # if you want the default. Otherwise see custom kotlinc distribution below
kt_register_toolchains() # to use the default toolchain, otherwise see toolchains below
</code>```

My kotlin file main.kt:

```<code>import java.util.Scanner

fun main(args: Array<String>) {

    // Creates a reader instance which takes
    // input from standard input - keyboard
    val reader = Scanner(System.`in`)
    print("Enter a number: ")

    // nextInt() reads the next integer from the keyboard
    var integer:Int = reader.nextInt()

    // println() prints the following line to the output screen
    println("You entered: $integer")
}
</code>```

I use a very simple file to test my setup.

Without bazel, I can do these to build: kotlinc main.kt -include-runtime -d test.jar

then run it with java -jar test.jar

When I use bazel build ., bazel creates a few folders. I tried to run java -jar bazel-out/darwin-fastbuild/bin/redis-tools.jar but it failed.

```<code>$ java -jar bazel-out/darwin-fastbuild/bin/redis-tools.jar
no main manifest attribute, in bazel-out/darwin-fastbuild/bin/redis-tools.jar
</code>```

Did I miss a target? How can I run the main.tk from the bazel output?

答:
The jar you are trying to run is missing a manifest file which declares its main class.

For executing a binary, Bazel uses a shell script wrapper which includes  the required jvm flags and its run-time dependencies.

Notice that you are using kt_jvm_library. This rule builds a shared dependency without the wrapper. To include a wrapper you should use the kt_jvm_binary rule. Then you can specify the main class by setting the main_class attribute.

Notice that you can use the bazel run :redis-tools to run the jar (use -s to see which script Bazel excuted)

You can also use bazel build :redis-tools_deploy.jar to build a "fat-jar" which will include the manifest.

Body:
I want to be able to use bazel to organize a simple kotlin project.

I am using the templates as listed in rules_kotlin (https://github.com/bazelbuild/rules_kotlin)

This is my BUILD file

load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kt_jvm_library")

kt_jvm_library(
    name = "redis-tools",
    srcs = glob(["*.kt"]),
    deps = [],
)

This is my WORKSPACE file

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

rules_kotlin_version = "legacy-1.3.0"
rules_kotlin_sha = "4fd769fb0db5d3c6240df8a9500515775101964eebdf85a3f9f0511130885fde"
http_archive(
    name = "io_bazel_rules_kotlin",
    urls = ["https://github.com/bazelbuild/rules_kotlin/archive/%s.zip" % rules_kotlin_version],
    type = "zip",
    strip_prefix = "rules_kotlin-%s" % rules_kotlin_version,
    sha256 = rules_kotlin_sha,
)

load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kotlin_repositories", "kt_register_toolchains")
kotlin_repositories() # if you want the default. Otherwise see custom kotlinc distribution below
kt_register_toolchains() # to use the default toolchain, otherwise see toolchains below

My kotlin file main.kt:

import java.util.Scanner

fun main(args: Array<String>) {

    // Creates a reader instance which takes
    // input from standard input - keyboard
    val reader = Scanner(System.`in`)
    print("Enter a number: ")

    // nextInt() reads the next integer from the keyboard
    var integer:Int = reader.nextInt()

    // println() prints the following line to the output screen
    println("You entered: $integer")
}

I use a very simple file to test my setup.

Without bazel, I can do these to build: kotlinc main.kt -include-runtime -d test.jar

then run it with java -jar test.jar

When I use bazel build ., bazel creates a few folders. I tried to run java -jar bazel-out/darwin-fastbuild/bin/redis-tools.jar but it failed.

$ java -jar bazel-out/darwin-fastbuild/bin/redis-tools.jar
no main manifest attribute, in bazel-out/darwin-fastbuild/bin/redis-tools.jar

Did I miss a target? How can I run the main.tk from the bazel output?


问:
How do I get mouse cursor position behind a control?
I am using C++Builder 10.3 and FMX.

There is a TImage control, on which multiple TRectangle controls are generated by some operation. The TRectangles are filled with claLightGray.

To get the mouse cursor position, I am using the OnMouseMove event for the TImage control. The problem is that I cannot get the mouse cursor position when the mouse moves into a TRectangle control on the TImage control.

How can I get the mouse cursor position for the TImage when it is on a TRectangle? I hope TRectangle is transparent to TImage in terms of mouse cursor position.

答: You can achieve that by setting HitTest = False (it is True as default) on the rectangles.


问:
Vue TypeScript Object prop type is not correct
When using Object properties in Vue Single File Components in TypeScript (generated with Vue CLI 3), the type of the prop is not correct, as shown by the minimal example below.

The type of this.product is (() => any) | ComputedOptions<any>. Does anyone know of a solution to this?

```<code><script lang="ts">
import Vue, { PropType } from 'vue';

interface ProductInterface {
  units: number;
}

export default Vue.extend({
  name: 'Product',
  props: {
    product: {
      type: Object as PropType<ProductInterface>,
      required: true,
    },
  },
  computed: {
    unitsString() {
      return `${this.product.units} Units`;
    },
  },
});
</script>
</code>```

答:
Did you try to put a type after the computed property like so?

```<code>unitsString() :string{
  return ...
}
</code>```

Typescript with Vue reacts weirdly with computed properties which are inferred.

Body:
Did you try to put a type after the computed property like so?

unitsString() :string{
  return ...
}

Typescript with Vue reacts weirdly with computed properties which are inferred.