text:
Q: List is not a subtype of type 'string' in type cast I am trying to post my data which consist an array of cartItems and other information. But could not get through it.
The api from laravel is generated as follows like in image
My Request with postman

I am getting below error in the logcat:
   type 'List<dynamic>' is not a subtype of type 'String' in type cast

E/flutter (13443): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The getter 'statusCode' was called on null.
E/flutter (13443): Receiver: null
E/flutter (13443): Tried calling: statusCode
E/flutter (13443): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter (13443): #1      new ResponseApi (package:kitabyatra/response/ResponseApi.dart:11:21)
E/flutter (13443): #2      ContentRepositoryImpl.dopostApiCallWithToken (package:kitabyatra/repository/ContentRepositoryImpl.dart:184:41)
E/flutter (13443): <asynchronous suspension>
E/flutter (13443): #3      ContentRepositoryImpl.doAddOrderApiCall (package:kitabyatra/repository/ContentRepositoryImpl.dart:515:18)
E/flutter (13443): #4      CheckoutPresenter.doAddOrderApiCall (package:kitabyatra/view/checkout/CheckoutPresenter.dart:552:81)
E/flutter (13443): #5      CheckoutState._buildDeliveryLocation.<anonymous closure> (package:kitabyatra/view/checkout/CheckoutView.dart:303:35)
E/flutter (13443): #6      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19)
E/flutter (13443): #7      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1111:38)
E/flutter (13443): #8      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:183:24)
E/flutter (13443): #9      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:598:11)
E/flutter (13443): #10     BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:287:5)
E/flutter (13443): #11     BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:259:7)
E/flutter (13443): #12     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
E/flutter (13443): #13     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:362:20)
E/flutter (13443): #14     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:338:22)
E/flutter (13443): #15     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:267:11)
E/flutter (13443): #16     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:295:7)
E/flutter (13443): #17     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:240:7)
E/flutter (13443): #18     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:213:7)
E/flutter (13443): #19     _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter (13443): #20     _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter (13443): #21     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter (13443): #22     _invoke1 (dart:ui/hooks.dart:265:10)
E/flutter (13443): #23     _dispatchPointerDataPacket (dart:ui/hooks.dart:174:5)

My Response Api class
    class ResponseApi {

  int code;
  String body;
  String errorMessage;

  ResponseApi(Response response)
  {
    code = response.statusCode;

    if (isSuccessful())
    {
      body = response.body;
      errorMessage = '';
    }
    else
    {
      body = response.body;
      errorMessage = "";
    }
  }

  bool isSuccessful()
  {
    return code >= 100 && code < 600;
  }
}

I have implemented the postcall method as follows:
 @override
  Future<ResponseFormat<ResponseAddOrder>> doAddOrderApiCall(
      Map<String, dynamic> map) async {
    final String url = liveUrl + "user/order/product";
    print("Add Order ");
    print(url);
    return await dopostApiCallWithToken<ResponseAddOrder, ResponseAddOrder>(
        ResponseAddOrder(), url, map);
  }

I have handled my post method as follows:
@override
  Future<ResponseFormat<R>> dopostApiCallWithToken<T extends ResponseUni, R>(
      T obj, String url, Map map) async {
    Map valueMap = json.decode(JsonEncoder().convert(map));
    SecureStorageRepositoryImpl secureStorageRepositoryImpl =
        SecureStorageRepositoryImpl();
    String apiToken = await secureStorageRepositoryImpl.getApiToken();

    if (apiToken == null) {
      apiToken = "";
    }

    final Client client = http.Client();
    Map<String, String> requestHeaders = {'authorization': apiToken};
    try {
      final response = await http
          .post(
        '$url',
        headers: requestHeaders,
        body: valueMap,
      )
          .catchError((dynamic e) {

        print("${e.toString()}");
      });

print(response); ------>>> // Here I am getting null

      final ResponseApi psApiResponse = ResponseApi(response);
      print(psApiResponse.errorMessage);
      print(psApiResponse.code);
      if (psApiResponse.isSuccessful()) {
        final dynamic hashMap = json.decode(response.body);

        if (!(hashMap is Map)) {
          final List<T> tList = <T>[];
          hashMap.forEach((dynamic data) {
            tList.add(obj.fromMap(data));
          });
          return ResponseFormat<R>(Status.SUCCESS, '', tList ?? R);
        } else {
          return ResponseFormat<R>(Status.SUCCESS, '', obj.fromMap(hashMap));
        }
      } else {
        return ResponseFormat<R>(
            Status.ERROR, psApiResponse.errorMessage, null);
      }
    } finally {
      client.close();
    }
  }

I have created my Request class as follows:
class RequestCheckOut extends RequestUni<RequestCheckOut> {
  RequestCheckOut({

    this.cartList,
    this.paymentId,
    this.price,
    this.deliveryAddressId,
    this.billingAddressId,
    this.discount,
    this.deliveryCharge,
    this.finalPrice,

  });
  var cartList;
  String paymentId;
  String price;
  String deliveryAddressId;
  String billingAddressId;
  String discount;
  String deliveryCharge;
  String finalPrice;

  @override
  RequestCheckOut fromMap(dynamic dynamicData) {
    if (dynamicData != null) {
      return RequestCheckOut(
        cartList : dynamicData['cartList'],
        paymentId : dynamicData['payment_id'],
        price : dynamicData['price'],
        deliveryAddressId : dynamicData['delivery_address_id'],
        billingAddressId : dynamicData['billing_address_id'],
        discount : dynamicData['discount'],
        deliveryCharge : dynamicData['delivery_charge_amt'],
        finalPrice : dynamicData['final_price'],

      );
    }
    else
    {
      return null;
    }
  }

  @override
  Map<String, dynamic> toMap()
  {
    var data = Map<String, dynamic>();

    data['cartList']=cartList;
    data['payment_id']=paymentId;
    data['price']=price;
    data['delivery_address_id']=deliveryAddressId;
    data['billing_address_id']=billingAddressId;
    data['discount']=discount;
    data['delivery_charge_amt']=deliveryCharge;
    data['final_price']=finalPrice;

    return data;
  }

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

    cartList = (json['cartList']);
    paymentId = (json['payment_id']);
    price = (json['price']);
    deliveryAddressId = (json['delivery_address_id']);
    billingAddressId = (json['billing_address_id']);
    discount = (json['discount']);
    deliveryCharge = (json['delivery_charge_amt']);
    finalPrice = (json['final_price']);

  }
}

I have called the presenter from the view as follows:
  RequestCheckOut requestCheckout = RequestCheckOut(
                          cartList:widget.cartList,
                          paymentId: presenter.responsePayment.value.data
                              .paymentMethod[_value].id
                              .toString(),
                          price: widget.totalPrice.toString(),
                          deliveryAddressId: presenter.responseAddress.value
                              .data.addressList[toggleIndex].id
                              .toString(),
                          billingAddressId: presenter.responseAddress.value.data
                              .addressList[toggleIndex].id
                              .toString(),
                          discount: "0",
                          deliveryCharge: widget.shipPrice.toString(),
                          finalPrice: widget.totalPrice.toString(),
                        );

                        presenter.doAddOrderApiCall(requestCheckout);

I have implemented doAddOrderApiCall in presenter as follows:
  doAddOrderApiCall(RequestCheckOut requestCheckOut) async
  {

    print("Do Add Order");
    view.showProgress();
    if (isConnectedToInternet)
    {
      print(requestCheckOut);
      final ResponseFormat<ResponseAddOrder> responseFormat = await contentRepo.doAddOrderApiCall(requestCheckOut.toMap());

      if(responseFormat.value.status)
      {

        view.hideProgress();
        view.showMessage(responseFormat.value.message);

        view.onBackPressed();

      }
      else
      {
        view.showMessage(responseFormat.value.message);
        view.hideProgress();
      }
    }
    else
    {

      view.hideProgress();
    }
  }

Response CartList
class ResponseCartList  extends ResponseUni<ResponseCartList>{
  bool status;
  String message;
  Data data;

  ResponseCartList({this.status, this.message, this.data});

  ResponseCartList.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    message = json['message'];
    data = json['data'] != null ? new Data.fromJson(json['data']) : null;
  }

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

  @override
  fromMap(dynamicData) {
    if (dynamicData != null)
    {
      return ResponseCartList(
        status: dynamicData['status'],
        message: dynamicData['message'],
        data:dynamicData['data']!=null?Data.fromJson(dynamicData['data']):null,
      );
    }
    else
    {
      return null;
    }
  }

  @override
  String getPrimaryKey() {
   return '';
  }

  @override
  Map<String, dynamic> toMap(object) {
    {
      if (object != null)
      {
        final Map<String, dynamic> data = <String, dynamic>{};
        data['status'] = object.status;
        data['message'] = object.message;
        data['data'] = object.data!=null?object.data.toJson():null;
        return data;
      }
      else
      {
        return null;
      }
    }
  }
}

class Data {
  List<CartList> cartList;

  Data({this.cartList});

  Data.fromJson(Map<String, dynamic> json) {
    if (json['cart_list'] != null) {
      cartList = new List<CartList>();
      json['cart_list'].forEach((v) {
        cartList.add(new CartList.fromJson(v));
      });
    }
  }

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

class CartList {
  int id;
  int productQty;
  int productId;
  String productSlug;
  String productName;
  String mrpPaperBook;
  String listingPrice;
  String productImage;

  CartList(
      {this.id,
        this.productQty,
        this.productId,
        this.productSlug,
        this.productName,
        this.mrpPaperBook,
        this.listingPrice,
        this.productImage});

  CartList.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    productQty = json['product_qty'];
    productId = json['product_id'];
    productSlug = json['product_slug'];
    productName = json['product_name'];
    mrpPaperBook = json['mrp_paper_book'];
    listingPrice = json['listing_price'];
    productImage = json['product_image'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['product_qty'] = this.productQty;
    data['product_id'] = this.productId;
    data['product_slug'] = this.productSlug;
    data['product_name'] = this.productName;
    data['mrp_paper_book'] = this.mrpPaperBook;
    data['listing_price'] = this.listingPrice;
    data['product_image'] = this.productImage;
    return data;
  }
}

A: try {
  final response = await http
      .post(
    '$url',
    headers: requestHeaders,
    body: valueMap,
  ).catchError((dynamic e) { /// <-- somehting wrong happened here and is catched

    print("${e.toString()}");
  });

when sending the http request there is some error with the parsing, so its catched with the catchError and you print the error which is:
type 'List<dynamic>' is not a subtype of type 'String' in type cast

Because of that the response it's null, that's why printing result returns null, and after that when calling final ResponseApi psApiResponse = ResponseApi(response); the first line:
code = response.statusCode;

throws the rest of your error, because response is null and cannot call statusCode from a null object
E/flutter (13443): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The getter 'statusCode' was called on null.
E/flutter (13443): Receiver: null
E/flutter (13443): Tried calling: statusCode
.....

I'm still confident that your error (which is some kind of parsing) is related with your cartList, you declared it as var cartList and the json.decode / encode tries to parse it as it understands it, if your cartList is a List but you declared it as var it will just assume its a List, you need to change it to the correct type so the decoder/encoder use the correct toJson/fromJson
class RequestCheckOut extends RequestUni<RequestCheckOut> {
  RequestCheckOut({

    this.cartList,
    this.paymentId,
    this.price,
    this.deliveryAddressId,
    this.billingAddressId,
    this.discount,
    this.deliveryCharge,
    this.finalPrice,

  });
  Data cartList;  // <---- Here use exactly the type of object you want to be encoded, Data, List<CartList> or ResponseCartList
  String paymentId;
  String price;
  String deliveryAddressId;
  String billingAddressId;
  String discount;
  String deliveryCharge;
  String finalPrice;

  @override
  RequestCheckOut fromMap(dynamic dynamicData) {
    if (dynamicData != null) {
      return RequestCheckOut(
        cartList : dynamicData['cartList'], // <--- Here try to use the correct fromJson/ fromMap instead of let the machine try it to guess it for you, because it will just decode it from the simplest objects, String, num, etc., if it's Data then use Data.fromJson(dynamicData['cartList'])
        paymentId : dynamicData['payment_id'],
        price : dynamicData['price'],
        deliveryAddressId : dynamicData['delivery_address_id'],
        billingAddressId : dynamicData['billing_address_id'],
        discount : dynamicData['discount'],
        deliveryCharge : dynamicData['delivery_charge_amt'],
        finalPrice : dynamicData['final_price'],

      );
    }
    else
    {
      return null;
    }
  }

  @override
  Map<String, dynamic> toMap()
  {
    var data = Map<String, dynamic>();

    data['cartList']=cartList;
    data['payment_id']=paymentId;
    data['price']=price;
    data['delivery_address_id']=deliveryAddressId;
    data['billing_address_id']=billingAddressId;
    data['discount']=discount;
    data['delivery_charge_amt']=deliveryCharge;
    data['final_price']=finalPrice;

    return data;
  }

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

    cartList = (json['cartList']);
    paymentId = (json['payment_id']);
    price = (json['price']);
    deliveryAddressId = (json['delivery_address_id']);
    billingAddressId = (json['billing_address_id']);
    discount = (json['discount']);
    deliveryCharge = (json['delivery_charge_amt']);
    finalPrice = (json['final_price']);

  }
}

A: Post method call
    @override
  Future<ResponseFormat<ResponseAddOrder>> doAddOrderApiCall(
      RequestCheckOut requestCheckOut) async {
    final String url = liveUrl + "user/order/product";
    print("Add Order ");
    print(url);
    return await dopostOApiCallWithToken<ResponseAddOrder, ResponseAddOrder>(
        ResponseAddOrder(), url, requestCheckOut);
  }

Changed post method as follows:
    @override
  Future<ResponseFormat<R>> dopostApiCallWithToken<T extends ResponseUni, R>(
    T obj,
    String url,
    var map,
  ) async {
    print(map);
    Map valueMap = json.decode(JsonEncoder().convert(map));
    var value = json.encode(map);

    print("Map value");

    print(value);

    SecureStorageRepositoryImpl secureStorageRepositoryImpl =
        SecureStorageRepositoryImpl();
    String apiToken = await secureStorageRepositoryImpl.getApiToken();

    if (apiToken == null) {
      apiToken = "";
    }

    final Client client = http.Client();

    Map<String, String> requestHeaders = {
      "Content-type": "application/json",
      "Authorization": apiToken

    };
    try {
      final response = await http
          .post(
        '$url',
        headers: requestHeaders,
        body: value,
      )
          .catchError((dynamic e) {
        print("Error");
        print("${e.toString()}");
      });
      print("Response");
      print(response.statusCode);
      print(json.decode(response.body));

      final ResponseApi psApiResponse = ResponseApi(response);
      print(psApiResponse.errorMessage);
      print(psApiResponse.code);
      if (psApiResponse.isSuccessful()) {
        final dynamic hashMap = json.decode(response.body);
        if (!(hashMap is Map)) {
          print("hash");
          print(hashMap);
          final List<T> tList = <T>[];
          hashMap.forEach((dynamic data) {
            tList.add(obj.fromMap(data));
            print("tList");
            print(tList);
          });
          return ResponseFormat<R>(Status.SUCCESS, '', tList ?? R);
        } else {
          return ResponseFormat<R>(Status.SUCCESS, '', obj.fromMap(hashMap));
        }
      } else {
        print("Error");
        return ResponseFormat<R>(
            Status.ERROR, psApiResponse.errorMessage, null);
      }
    } finally {
      client.close();
    }
  }


text:
Q: Passwords On Remote Server Code Security I am building a web app which will be sending out emails for sign up verification. I will be using https://github.com/RGBboy/express-mailer. I wanted to know whether it is safe for me to display the email password in the code and push it to the server (Heroku, AWS etc.) where the app is hosted. If not, what alternative methods should I use to 'hide' the password?

A: It is usually considered bad practice to have plaintext secrets/credentials stored under version control. As that could lead to security issues
Usually these sorts of info are set as environment variables. Heroku has a pretty straightforward way of doing this configuration. You can either use their web admin, or set them via command line.
As for other cases, like your development setup, this could be done with the use of .env files, which are loaded and have its values exposed to your running code. Since [express-mailer][2] is a node application, I suggest using some npm package like dotenv or node-env-file automatically do this loading.I personally prefer dotenv which I feel is simpler.
You should also check out this article regarding the use of .env files. The basic idea is to have your .gitignore(or equivalent) to ignore your .env file, thus ensuring your secret credentials are never introduced in your version control. And then setup an .env.sample file to show the developer which data needs to be declared on said .env file.
Example:
.env
EMAIL=foo@bar.com
PASSWORD=AahUbf796
S3_TOKEN=ASVNS7843NCA87SDVNBRT9

.env.sample
EMAIL=<email to access the account>
PASSWORD=<secret password>
S3_TOKEN=<s3 token for application foobar>

A: You shouldn't ever store secrets in version control.
One alternative (which I personally like the best) is setting secrets as environment variables for your application in your production environment. Heroku I think supports this. This is also the approach that for example Rails takes. Dev/test "secrets" (which are not actually real credentials to anything valuable) can still of course be stored in your VCS.

A: Another option is to encrypt the user credentials in your source code and decrypt them from your source code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Will it ever be the year 2000 in The Matrix? A comment on this question raised another interesting question, specifically this comment:
If they kept it in 1999, they'd have no y2k bug to deal with.{/tongue-in-cheek}

And it got me thinking...The Matrix is a simulation of the year 1999.  Everybody in The Matrix thinks that it is the real world, and pass their lives as if it were exactly that.
But if that is the case, it wouldn't be 1999 forever.  Years pass.  People keep track of time and have children that grow up and have birthdays.  They're going to keep track of what year it is.
Will it ever be the year 2000 in The Matrix, or do the machines 'reset' people's memory of what year it is, so that it is perpetually 1999?

A: During the scene in Architect's room in The Matrix Reloaded, video of human civilization is shown on the television screens, including video of President George W. Bush (here around 3:05). So if the Matrix is trying to accurately represent human history, it definitely continued into the 2000's.
I think we have to consider the point of the Matrix. The Machines weren't overly concerned with arbitrary dates, they wanted to reconstruct the "pinnacle of human civilization." So long as they prevent whatever made human civilization go into decline to begin with, they'd presumably be fine with the timeline continuing. The only thing I think they'd take steps to completely prevent would be the invention of AI.

A: In my opinion, yes, time will pass and year 2000 will be reached. There is no need to reset because of that. The only reason to reset the memory of people in Matrix is because reaching the year when the machines start to think, IMHO.
They can deal with the y2k bug on the Matrix fake world. Just a recreation like everything else.
The Matrix recreate all physic laws, and all the history at that moment, including the computers way of working and programming codes as humans made it on the first place. The bug will not scale to the machines, so I think it won't be a problem to recreate it.


text:
Q: # added to URL when clicking link_to_add OR link_to_remove_association I'm using Rails 6 and I'm trying to make nested_fields work. I'm using Cocoon. There is no JS error, JQuery is correctly loaded. The nested_form loads the nested data correctly, but I'm unable to add a new line or remove an existing line. This is my code:
In _form.html.erb

     <%= f.fields_for :entry_links do |ff| %>
          <%= render 'entry_link_fields', f: ff %>
     <% end %>

     <%= link_to_add_association ' Add Link '.html_safe, f, :entry_links, class: "btn btn-primary" %>

_entry_link_fields.html.erb

            <%= f.text_field :link_type, class: "form-control" %>

            <%= f.text_field :label, class: "form-control" %>

            <%= f.text_field :link, class: "form-control" %>

            <%= f.number_field :line, class: "form-control" %>

            <%= link_to_remove_association ''.html_safe, f, class: "btn btn-danger" %>

Just in case, here's a snippet of my package.json file which lists jQuery and coocon
{
     "cocoon-js": "^0.0.5",
     "jquery": "^3.5.1",
}

I've tried with both @nathanvda/cocoon AND cocoon-js-vanilla to no avail.
The only thing that happens when I click either of those links is that a "#" is added to the URL box. I read in another answer that it might be related to a JQuery error but that's not my case since my JS log doesn't show any error and I'm able to call other JQuery functions correctly from within the same app.

A: So it turns out that everything was correct, except I completely missed this line:
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

After adding that line to my application.html.erb file, everything is correctly loaded and my links are working as expected.


text:
Q: (Mql4) What differentiates a "Method" from a "Constructor"? My question refers to Methods inside of Classes via "public" access.
As referring to mql4 documentation, there seems to be no listed source on how to properly instantiate a Method into a Class, or what even makes a Method a Method in the first place.
To me it seems that if you place a function inside of a Class, that in itself makes it a Method? Or am I wrong. Is anyone able to clear this up for me?

A: Basic information and differences between constructor and method:
Constructor:

*

*A constructor is a special function, which is called automatically when creating an object of a structure or class and is usually used to initialize class members,

*The name of a constructor must match the class name,

*The constructor has no return type (you can specify the void type).

(docs)
Method:

*

*A method is a function that belongs to a class or an object, i.e. it cannot exist without the class.

*You need to declare class methods in the class. Else it wouldn't be a class method.

*Method can return value with type specified in the method declaration.

Simple example:
class MyClass {                            // Declaration
    private:
        string myName;                     // Property
    public:
        void printName();                  // Method of void return type
        int sumIntegers(int a, int b);     // Method of int return type
        MyClass(string name);              // Constructor declaration
};

MyClass::MyClass(string name) {            // Constructor body
    this.myName = name;
}

int MyClass::sumIntegers(int a, int b) {   //Method body
    return a + b;
}

void MyClass::printName() {
    Print("Your name is: ", this.myName);
}

int sumIntegers(int a, int b){             //Function body
    return a + b;
}

Class member (object) initialization:
MyClass *myObject = new MyClass("SO example");

Example usage inside OnInit:
int OnInit() {
    myObject.printName();                            // Method call by object (MyClass)
    Alert("2 + 2 = ", myObject.sumIntegers(2, 2));   // Same as above
    Alert("2 + 2 = ", sumIntegers(2, 2));            // Function call

    return(INIT_SUCCEEDED);
}

To me it seems that if you place a function inside of a Class, that in
itself makes it a Method?

Yes, but remember that a function is a block of code which only runs when it is called, and it's not related with a class.
Methods are related with class, and can not exists without a class.


text:
Q: How can i separate the second set from this object? I've an javascript map in which i would like to separate the last set of objects,
{
    "97483": {
        "_index": 0,
        "text_html": "sadf"
    },
    "97484": {
        "_index": 1,
        "text_html": "sfhsdfasdfsdf"
    },
    "97485": {
        "_index": 2,
        "text_html": "test1"
    },
    "97486": {
        "_index": 3,
        "text_html": "test2"
    },
    "97487": {
        "_index": 4,
        "text_html": "test3"
    },
    "97493": {
        "_index": 0,
        "text_html": "test9"
    },
    "97494": {
        "_index": 1,
        "text_html": "test10"
    },
    "97495": {
        "_index": 2,
        "text_html": "test11"
    },
    "97496": {
        "_index": 3,
        "text_html": "test11"
    },
    "97893": {
        "_index": 0,
        "text_html": "test99"
    },
    "97894": {
        "_index": 1,
        "text_html": "test999"
    },
    "97895": {
        "_index": 2,
        "text_html": "test9999"
    },

}

In this javascript map how i can separate out the
"97893": {
        "_index": 0,
        "text_html": "test99"
    },
    "97894": {
        "_index": 1,
        "text_html": "test999"
    },
    "97895": {
        "_index": 2,
        "text_html": "test9999"
    },

Actually the main motive is to separate out the last set of elements whose _index starts from 0.
Any help would be greatly appreciated.

A: Try to write your code like,
var mainObj = {...}; //your object
var result = {};

Object.keys(mainObj).forEach(function(itm){
 if(mainObj[itm]._index == 0) result = {};
 result[itm] = mainObj[itm];
});

The above code will collect the last set of objects from the main object.
DEMO

A: A proposal for unordered properties.

var object = { "97483": { "_index": 0, "text_html": "sadf" }, "97484": { "_index": 1, "text_html": "sfhsdfasdfsdf" }, "97485": { "_index": 2, "text_html": "test1" }, "97486": { "_index": 3, "text_html": "test2" }, "97487": { "_index": 4, "text_html": "test3" }, "97493": { "_index": 0, "text_html": "test9" }, "97494": { "_index": 1, "text_html": "test10" }, "97495": { "_index": 2, "text_html": "test11" }, "97496": { "_index": 3, "text_html": "test11" }, "97893": { "_index": 0, "text_html": "test99" }, "97894": { "_index": 1, "text_html": "test999" }, "97895": { "_index": 2, "text_html": "test9999" } },
    keys = Object.keys(object).map(Number).sort((a, b) => a - b),
    key = keys.filter(a => object[a]._index === 0),
    result = {};

keys.forEach(function (a) {
    if (a >= this) {
        result[a] = object[a];
    }
}, key[key.length - 1]);

document.write('
' + JSON.stringify(result, 0, 4) + '
');

A: Can be done with pure JS in an assignment instruction.

var dataObj = { "97483": { "_index": 0, "text_html": "sadf" }, "97484": { "_index": 1, "text_html": "sfhsdfasdfsdf" }, "97485": { "_index": 2, "text_html": "test1" }, "97486": { "_index": 3, "text_html": "test2" }, "97487": { "_index": 4, "text_html": "test3" }, "97493": { "_index": 0, "text_html": "test9" }, "97494": { "_index": 1, "text_html": "test10" }, "97495": { "_index": 2, "text_html": "test11" }, "97496": { "_index": 3, "text_html": "test11" }, "97893": { "_index": 0, "text_html": "test99" }, "97894": { "_index": 1, "text_html": "test999" }, "97895": { "_index": 2, "text_html": "test9999" } },
         ok = Object.keys(dataObj),
    reduced = ok.fill(false,0,ok.reduce((p,c) => (p.push(dataObj[c]._index),p),[]).lastIndexOf(0)).reduce((p,c) => (c && (p[c] = dataObj[c]),p),{});

document.write("
" + JSON.stringify(reduced,null,2) + "
");


text:
Q: What file access problems does the "You are about to change permissions on the root directory of the startup disk..." warning refer to? In an AD environment as a local admin to a server, I went to give a colleague full permissions to a drive (right-click the drive, Security, Edit, add him and give him some rights) temporarily while waiting for him to be added to the correct AD group, and got this warning:

You are about to change permissions on the root directory of the startup disk. This can reduce the security of your computer and cause users to have problems accessing files. Do you want to continue?

I get the first part (security), but what is "cause users to have problems accessing files" talking about? Is that a catch-all in case the change I'm making reduces someone's access to the drive, or...?

A: I think it means user with full permissions of hdd will also has read permission on all file on that hdd, this may consider as insecure.  The user can also change some permisson on files on that hdd so other users may not able to access them. This situation can consider like give someone sudo permisson on linux.


text:
Q: How to loop through a list of arrays, created in the bash script I am creating a list of arrays in a bash script, per the suggestion in this post-
How to declare 2D array in bash (Edit 2 by Sir Athos)-

Edit 2: To declare and initialize a0..a3[0..4] to 0, you could run:
for i in {0..3}; do
    eval "declare -a a$i=( $(for j in {0..4}; do echo 0; done) )"
done

Now I am having difficulty accessing the newly created arrays.  I am trying to loop through and recreate the array name the same as they were created, but resulting in 'bad substitution' error.
for j in {0..3}; do
    echo ${a$j[@]:0}
done

error received:
${a$i[@]:0}: bad substitution

Any thoughts on how to access the arrays?  Ultimately the list of arrays will be much larger and created dynamically.  This is simply an example

A: The approach you are using is bad. Use jm666's accepted answer from the same question instead.
With that out of the way:
a1=("foo" "bar")
a2=("baz" "etc")

j=1
var="a$j[@]"
echo "The value of $var is:" "${!var}"

i=0;
var2="a$j[$i]"
echo "The value of $var2 is ${!var2}"

will print
The value of a1[@] is: foo bar
The value of a1[0] is: foo


text:
Q: Mongo querying times issue in multiple environments (Spring Boot) I work on a project with two environments, A & B, each with its own database. My spring boot (1.5.3) application uses mongodb, where I am querying a collection based on an enum EnumType with values TYPE1 and TYPE2.
Now, in env. A, when trying to fetch all entries where EnumType = TYPE1, which I can see in my database are about 2000, this takes a long time. Fetching entries where EnumType = TYPE2 takes a normal amount of time.
In env. B, when fetching the TYPE1 entries, which are far more (approx 2M), this takes very little to happen. Fetching the TYPE2 entries (450 entries) takes a ridiculous amount of time.
I have added a type_1 index in both cases (get by EnumType ascending), but these odd times remain, to the point where if I try to fetch the TYPE2 entries in env B, my application crashes. Since the search logic is the same in both environments (the exact same application runs in both cases), I'm not sure what else to do in order to fix this issue.
The code is simple:
EntityController:
@GetMapping
public Page<Entity> getAll(@RequestParam EnumType type, OffsetPageRequest page) {
    return entityService.getAll(type, page);
}

EntityService:
public Page<Entity> getAll(EnumType type, OffsetPageRequest page) {
    return entityRepository.findByCriteria(type, page);
}

CustomizedEntityRepository:
Page<Entity> findByCriteria(EnumType type, Pageable page);

UserProfileRepositoryImpl:
@Override
public Page<Entity> findByCriteria(EnumType type, Pageable page) {
    Query query = new Query().with(page);
    List<Criteria> andCriteriaList = new ArrayList<>();
    andCriteriaList.add(Criteria.where("type").is(type));
    query.addCriteria(new Criteria().andOperator(andCriteriaList.toArray(new Criteria[0])));
    return PageableExecutionUtils.getPage(mongoTemplate.find(query, Entity.class), page, () -> mongoTemplate.count(query, Entity.class));
}

EnumType:
public enum EnumType {
    TYPE1,TYPE2;

    private EnumType() {
    }
}

Both applications have the same configuration files, with the only differences being the corresponding database URLs.


text:
Q: What is the name of this plot?
I would like to redo this plot, which was published in one of the newspaper about Covid 19 death toll. I am not sure what kind of graph is this, I am assuming this is percent stacked area plot.

A: It is probably a streamgraph of some kind. So, a streamgraph is a type of stacked area chart. It represents the evolution of a numeric variable for several groups. Areas are usually displayed around a central axis, and edges are rounded to give a flowing shape.
I found it hard to install streamgraph from git hub repository, however, there is a ggplot alternative available called "ggTimeSeries". Below is the link for streamgraph R documentation.
https://www.r-graph-gallery.com/streamgraph.html


text:
Q: How do you remove margin/padding from a GraphViz node using an image? I am using GraphViz with user defined shapes for nodes using the image tag.  The images are png files, and contain lines to the edge of the image to link up with edges drawn by GraphViz.  But if I try to make a rudimentary graph using neato with a defined layout, you can still see some margin or padding between the images and the graph edges that show up as small gaps in the lines.  There is no border in the images themselves.  (I also need to re-center some of the images.)  How does one remove the gaps?
Here is my .dot, with several attempts inspired by other answers, but nothing seems to remove the gaps.
graph G {

  pad = 0.0;

  a  [ label="",  pos="0,0",       shape=none,      width=0, height=0, image="LnLft.png"     ];
  b  [ label="",  pos="100,0",     shape=none,      width=0, height=0, image="BrkClsHrz.png", penwidth=0 ];
  h1 [ label="",  pos="200,0",     shape=none,      width=0, height=0                        ];
  c  [ label="",  pos="200,-100",  shape=plaintext, width=0, height=0, image="BrkClsVrt.png", penwidth=0 ];
  d  [ label="",  pos="200,-200",  shape=plaintext, width=0, height=0, image="BrkOpnVrt.png" ];
  h2 [ label="",  pos="200,-300",  shape=none,      width=0, height=0                        ];
  e  [ label="",  pos="100,-300",  shape=none,      width=0, height=0, image="BrkClsHrz.png", margin="0,0"];
  f  [ label="",  pos="0,-300",    shape=none,      width=0, height=0, image="LnLft.png"     ];
  a -- b  [len=1.5, penwidth=2];
  b -- h1 [len=1.5, penwidth=2];
  h1 -- c [len=1.5, penwidth=2];
  c -- d  [len=1.5, penwidth=2];
  d -- h2 [len=1.5, penwidth=2];
  h2 -- e [len=1.5, penwidth=2];
  e -- f  [len=1.5, penwidth=2];
}

And here is the output:


text:
Q: How do I add an svg icon to Material ui helper text generated by Formik and Yup In my React form I am using Formik, Yup and Material ui form and textfield:
import { TextField } from '@material-ui/core';

for my E-mail form.
When I blur out the field it's generating the following HTML:

This field is required.

How do I add an svg icon to this helper text?
For example a React component <HelperText icon={MyIcon} />, is that possible?

A: You can add the svg with css class from the global styles.css file, it is not a best practice but it's a nice workaround if there is no other solution for this situation.
Similarly easy to using SVG as an img, you can use it in CSS as a background-image.
for example:
.MuiFormHelperText-root MuiFormHelperText-contained Mui-error {
  display: block;
  text-indent: -9999px;
  width: 100px;
  height: 82px;
  background: url(example.svg);
  background-size: 100px 82px;
}

Notice we set the background-size to the size of the logo element. We have to do that otherwise we'll just see a bit of the upper left of our much larger original SVG image. These numbers are aspect-ratio aware of the original size. But you could use a background-size keywords like contain if you want to make sure the image will fit and can't know the parent image will be of the exact right size.


text:
Q: How can I convert the block number into the Integer type in substrate module? I'm testing the substrate off-chain worker, what I want to do is receive the current block number, and then do some calculation, just like the below code if (get_block / 10 == 0), and I get some error. How can I convert the block number into the Integer type?
my code
use frame_support::{decl_storage, decl_module, dispatch::DispatchResult, debug};

use frame_system::{ensure_signed, offchain};

use sp_runtime::{
  offchain::http,
  transaction_validity::{
    TransactionValidity, TransactionLongevity, ValidTransaction, InvalidTransaction
  }
};

pub trait Trait: frame_system::Trait {}

decl_storage! {
    trait Store for Module<T: Trait> as Runtime_example {
        SubjectCount: u32;
    }
}
decl_module! {
    pub struct Module<T: Trait> for enum Call where origin: T::Origin {
        fn offchain_worker(block: T::BlockNumber){
            let get_block = block;
            if (get_block / 10 == 0) {
               debug::info!("print !!!!!!!!!!!!!!!!");
            }
        }
    }
}

Error logs
error[E0308]: mismatched types
  --> /home/substrate-node-template/runtime/src/runtime_example.rs:32:29
   |
32 |             if (get_block / 10 == 0) {
   |                             ^ expected associated type, found integer
   |
   = note: expected associated type `<T as frame_system::Trait>::BlockNumber`
                         found type `{integer}`
   = help: consider constraining the associated type `<T as frame_system::Trait>::BlockNumber` to `{integer}` or calling a method that returns `<T as frame_system::Trait>::BlockNumber`

error[E0308]: mismatched types
  --> /home/substrate-node-template/runtime/src/runtime_example.rs:32:34
   |
32 |             if (get_block / 10 == 0) {
   |                                  ^ expected associated type, found integer
   |
   = note: expected associated type `<T as frame_system::Trait>::BlockNumber`
                         found type `{integer}`
   = help: consider constraining the associated type `<T as frame_system::Trait>::BlockNumber` to `{integer}` or calling a method that returns `<T as frame_system::Trait>::BlockNumber`

A: @kmdreko is right. You do not want to convert the block number to an integer, but convert the integer into a block number and then do the math.
So replace:
get_block / 10 == 0

With:
(get_block / 10.into()).is_zero()


text:
Q: Update multiple rows into one query I need to update multiple rows and same column name with faster way.
Till now i'm using this;
Begin Transaction;
Update Inventory set Quantity-=1 where ID=1;
Update Inventory set Quantity-=4 where ID=2;
Update Inventory set Quantity-=1 where ID=1;
Update Inventory set Quantity-=5 where ID=4;
Commit;

This method works well, but i dont if it fast to write all the query for each value in same table.Any suggestions?
As i read sql server doesnt support duplicate key update...

A: For simple updates you could use a CASE statement:
UPDATE Inventory
SET Quantity += CASE ID
    WHEN 1 THEN -1
    WHEN 2 THEN -4
    WHEN 4 THEN -5
    ...
END
WHERE ID IN (1,2,4);

However, this would not be efficient for huge updates. In those cases I would prefer 'chunked' UPDATE grouped by ID values having the same update:
UPDATE Inventory
SET Quantity += a
END
WHERE ID IN (X...);

UPDATE Inventory
SET Quantity += b
END
WHERE ID IN (Y...);

...

A combination between the two is possible, also.
Good luck.


text:
Q: .net maui bottom (navigation) Tab Bar top(border) line How can I get a horizontal line above tab bar on Android and IOS?
Here is a similar question on stack overflow for xamarin forms. I tried to use the new handler. But I don't know if I am doing it right.
Microsoft.Maui.Handlers.TabbedViewHandler.Mapper.AppendToMapping(nameof(IView.Background), (handler, view) =>
        {
           if (view is BottomNavigationView )
            {
#if __ANDROID__

                Android.Graphics.Drawables.ShapeDrawable line = new()
                {
                    Alpha = 255
                };

                line.Paint.Color = Colors.Black.ToAndroid();
                line.Paint.SetStyle(Android.Graphics.Paint.Style.Fill);
                var layerDrawable = new LayerDrawable(new Drawable[] { line });
                layerDrawable.SetLayerInset(0, 0, 0, 0, int.Parse((view.Height - 4).ToString()));
                (handler.PlatformView as global::Android.Views.View).SetBackground(layerDrawable);

#endif
            }
        });

A: The process for creating a cross-platform .NET MAUI custom control, whose platform implementations are provided by handlers, is as follows:

*

*Create a class for the cross-platform control, which provides the
control's public API. For more information, see this.

*Create any required additional cross-platform types.

*Create a partial handler class. For more information, see Create the
handler.

*In the handler class, create a PropertyMapper dictionary, which
defines the Actions to take when cross-platform property changes
occur. For more information, see Create the property mapper.

*Optionally, in your handler class, create a CommandMapper
dictionary, which defines the Actions to take when the
cross-platform control sends instructions to the native views that
implement the cross-platform control. For more information, see
Create the command mapper.

*Create partial handler classes for each platform that create the
native views that implement the cross-platform control. For more
information, see Create the platform controls.

*Register the handler using the ConfigureMauiHandlers and AddHandler
methods in your app's MauiProgram class. For more information, see
Register the handler.
      .ConfigureMauiHandlers(handlers =>
            {
                handlers.AddHandler(typeof(CustomControl), typeof(CustomControlHandler));
            });

Reference link: https://learn.microsoft.com/en-us/dotnet/maui/user-interface/handlers/
Sample repo:https://github.com/dotnet/maui-samples/tree/main/6.0/UserInterface/Handlers/CreateHandlerDemo


text:
Q: How to plot timeseries(s) with different sampling rate and line styles within the same y axis with plotyy? Consider the following example. The requirements for line style and placement among the two y axises are in the comments.
Fs1 = 5;
Fs2 = 25;
t1 = (0:1:19)/Fs1;
t2 = (0:1:19)/Fs2;

fc = 5;
y11 = sin(2*pi*fc*t1); % In left y axis with style 'o' | legend entry - 'raw signal'
y12 = 2*sin(2*pi*fc*t2); % In left y axis with style '--' | legend entry - 'upsampled signal'

y21 = 5; % In right y axis with style ':' | legend entry - 'DC'


text:
Q: How to combine multiple formulas in 1 cell I am trying to combine the below two formulas in one cell, but no luck so far.
Both formulas work OK on their own, but I can not figure out how to combine them together to produce the result in same cell.
=IF(AND(C18>0, C6>J11), J11, C6)

=IF(AND(C17<K5, C6>J10), J10, C6)

A: You can nest functions inside each other, I think this is the one you need:
=IF(AND(C18>0, C6>J11), J11, IF(AND(C17 <K5, C6>J10), J10, C6))

A: Another way to combine multiple formulas, but for a different purpose:
=SUBSTITUTE(SUBSTITUTE(A1,"a","e"),"oo","o")

It also works in Google Sheets.


text:
Q: Black screen when trying to run DirectX application I have been trying to run a sample Directx-11 code from this website:tutorial 2. (source code download at the end).
All I get when I try to run the program is a black screen.
System Configuration:

*

*Windows 7 64 bit (SP1)

*Intel Core i5 M520 @ 2.4Ghz

*RAM: 4GB

*Intel HD Graphics on core i5 (latest driver )

*Lenovo Think pad X201

IDE:

*

*Microsoft Visual Studio 2013

*Microsoft Visual Studio 2010 Express with Service Pack.

*I also installed DirectX 9 SDK from here: DirectX 9 SDK June 2010
Diagnostics:

*

*I ran dxdiag and everything seems to be OK. (DirectDraw and Direct3D are enabled).

*I tried changing the refresh rate from 50Hz to 60Hz. (Control Panel->Appearance & Personalization->Display->Screen Resolution->Advanced Setting)

*Could not change the hardware acceleration. "Change Settings" option was diabled under "Troubleshooting" tab in the above menu.

*System Settings-->Performance Options-->"Let Windows Choose What's Best For My Computer"

How can I get this tutorial to run? My goal is to run any program in DirectX-11 on my laptop. I am using this to learn DirectX-11. Please let me know if I missed out some detail.
Thank you very much!

A: The tutorial only create a framework based on DirectX 11, there is no graphics output, so a black window is the expected result.


text:
Q: Replace substring in one column of dataframe with value from another column in same row I have dataframe of character columns named new_sgs that looks like this:
     SG.Name RegionCode
1 AW02PASGA001         01
2 AW02PASGA002         01
3 AW02PASGA003         01
4 AW02PASGA004         01
5 AW02PASGA005         01
6 AW02PASGA006         01
...

I want to replace '02' in the strings of column 1 with the string in column2. This does the job for row 1:
new_sgs$SG.Name[1] <- gsub("AW02", paste0("AW", new_sgs$RegionCode[1]), new_sgs$SG.Name[1])

Is there a way to make this change to every row using one of the apply functions? I've tried
sapply(new_sgs, function(x) gsub("AW02", paste0("AW", new_sgs$RegionCode[x]), new_sgs$SG.Name[x]))

but this is what I get:
    SG.Name RegionCode
[1,] NA      NA
[2,] NA      NA
[3,] NA      NA
[4,] NA      NA
[5,] NA      NA
[6,] NA      NA
...
Warning messages:
1: In gsub("AW02", paste0("AW", test$RegionCode[x]), test$SG.Name[x]) :
  argument 'replacement' has length > 1 and only the first element will be used
2: In gsub("AW02", paste0("AW", test$RegionCode[x]), test$SG.Name[x]) :
  argument 'replacement' has length > 1 and only the first element will be used

Thanks!
Luke

A: str_replace() from the stringr package will vectorise over a pattern and replacement as you need. See example below:
library(stringr)

x <- data.frame(
  SG.Name = c("AW02PASGA001", "AW02PASGA002", "AW02PASGA003"),
  RegionCode = c("01", "01", "01")
)

str_replace(x$SG.Name, "02", x$RegionCode)
#> [1] "AW01PASGA001" "AW01PASGA002" "AW01PASGA003"

A: If it is guaranteed that the string you want to replace comes at position of 3 and 4 of the Name, you can just use substr:
substr(df$SG.Name, 3, 4) <- df$RegionCode
df
#       SG.Name RegionCode
#1 AW01PASGA001         01
#2 AW01PASGA002         01
#3 AW01PASGA003         01
#4 AW01PASGA004         01
#5 AW01PASGA005         01
#6 AW01PASGA006         01

Alternatively you can use sub with mapply:
df$SG.Name = mapply(function(rc, nam) sub("\\d+", nam, rc), df$RegionCode, df$SG.Name, USE.NAMES = F)


text:
Q: Laravel 5.6 Nested Categories I am using Laravel 5.6. I am stuck with the following. The structure of my category model is below.
id  | name              | cat_parent_id | slug
--- | ------------------| ------------- | -------------
1   | Parent - 1        | NULL          | parent-1
2   | Parent - 2        | NULL          | parent-2
3   | Child-1- P - 1    | 1             | ch-1-p-1
4   | Child-1- P - 2    | 2             | ch-1-p-2
5   | sCh-1-Ch-1-P- 2   | 4             | sch-1-ch-1-p-2

To obtain children relationship I used the following method on the linkedin\Category model.
public function children()
{
  return $this->hasMany('linkedin\Category', 'cat_parent_id', 'id');
}

In my controller,
public function category(Category $category)
{
    $categories = $category->first()->children;

    return view('product.list', compact('categories'));
}

Here is my route
Route::get('/{category?}','ProductController@category');

I am able to fetch the first children using the following code. It shows the following, when I visit the url, http://trump.localhost/parent-2
Child-1- P - 2
However, it doesn't show anything when I visit http://trump.localhost/parent-2/ch-1-p-2
It should show following, but I don't see it.
sCh-1-Ch-1-P- 2

A: You have to adjust your route:
Route::get('{category1}/{category2?}/{category3?}/{category4?}',
    'ProductController@category');

And your controller:
public function category(Category $category1, Category $category2 = null,
        Category $category3 = null, Category $category4 = null) {
    $category = collect(func_get_args())->filter()->last();

    $categories = $category->children;

    return view('product.list', compact('categories'));
}

A: in model
public function children()
{
  return $this->hasMany('kblinked\Category', 'cat_parent_id');
}

in your controller send category id in argument then find that category;
public function category($category) // $category is id of category
{
    $category = Category::findOrFail($category);

    return view('product.list', compact('categories'));
}

in your view
@foreach($category->children as $child)
  {{$child->name}}
@endforeach

for more documentation


text:
Q: Multiple resources does not work in ipad - Kendo Scheduler I wrote below code to create an appointment for multiple attendees for web and worked perfectly. But for iPad it fails to submit selected attendees id to the model. I don't understand what's wrong here?
enter code here @(Html.Kendo().Scheduler<AppointmentSummaryModel>()
.Name("scheduler")
.Mobile(MobileMode.Auto)
.Date(DateTime.Today)
.Timezone("Etc/UTC")
.Height(700)
.DataSource(ds => ds
    .Read(read => read.Action("Schedules_Read", "Scheduler"))
    .Create(create => create.Action("Schedules_Create", "Scheduler"))
    .Update(update => update.Action("Schedules_Update", "Scheduler"))
    .Destroy(destroy => destroy.Action("Schedules_Destroy", "Scheduler"))
    .Model(m =>
    {
        m.Id("Id");
        m.Field(f => f.OwnerID);
    })
)
.Views(views =>
{
    views.WeekView(s => s.Selected(true));
})
.Resources(resource =>
{
    resource.Add(m => m.OwnerID)
        .Title("Owner")
        .DataTextField("Text")
        .DataValueField("Value")
        .DataColorField("Color")
        .Multiple(true)
        .BindTo(new[] {
            new { Text = "Alex", Value = 1, Color = "#f8a398" } ,
            new { Text = "Bob", Value = 2, Color = "#51a0ed" } ,
            new { Text = "Charlie", Value = 3, Color = "#56ca85" }
        });
})
)

Few screenshots of result
Console errors when I select attendees name

Other than attendees everything is available in e.event

Output needs to save the attendee name in the appointment which is not happening right now


text:
Q: How to create and assign events to dynamically loaded gui? I'm trying to create a WPF application where the users are allowed to create a custom gui dynamically loaded with some xaml files.
There are two files needed for this to happen:
The main xaml file which contains the gui elements
<Grid>
    <Button Name="button1" Height="82" Width="132">Button Text</Button>
    <TextBlock Text="Text Data"/>
</Grid>

and the events file with the events:
<Events>
    <Event Object="button1" Event="Click" File="button1OnClick"/>
</Events>

I load the files correct and the gui is shown but the events (in this example the button click event) are not triggered. I tried it with this code (and some varieties of it):
/*
scroll = parent object of the custom gui (ScrollViewer)
events = List of the events in the events file
evnt.Event == "Click"
evnt.ObjectName == "button1"
evnt.File == "button1OnClick"
*/

List<DependencyObject> childs = scroll.GetLogicalChilds();
foreach (DependencyObject control in childs)
{
    Control c = null;
    if(control is DependencyObject)
        c = control as Control;

    if (c == null)
        continue;

    foreach(PluginEvent evnt in events)
    {
        if (evnt.ObjectName == c.Name) //button1 == button1
        {
            RoutedEvent routedEvent = EventManager.RegisterRoutedEvent(
                evnt.Event,
                RoutingStrategy.Bubble,
                typeof(RoutedEventHandler),
                c.GetType());

            Action handler = () => Lua.DoFile(evnt.File + ".lua");
            c.AddHandler(routedEvent, handler);
        }
    }
}

In this example I try to run the button1OnClick.lua file when I click on the button named button1 but I get an error

Handler type is mismatched.

and I don't know how to fix this. Can somebody explain me how to run the lua file when the event is triggered?
The target is to run the the file which is declared inside the events file when the event is triggered.
Edit1:
I fixed the exception with this code
RoutedEvent routedEvent = EventManager.RegisterRoutedEvent(evnt.Event, RoutingStrategy.Bubble, typeof(RoutedEventHandler), c.GetType());
RoutedEventHandler handler = (s, a) => Lua.DoFile(evnt.File + ".lua");

c.AddHandler(routedEvent, handler);

but it don't trigger if i click the button

A: Change this
Action handler = () => Lua.DoFile(evnt.File + ".lua");
c.AddHandler(routedEvent, handler);

To more appropriate event handler
c.AddHandler(routedEvent, (delegate)(s, o) => Lua.DoFile(evnt.File + ".lua")); // not sure

Based on your comment (^^):
Action<object,RoutedEventHandler> handler = (s, o) => Lua.DoFile(evnt.File + ".lua");
c.AddHandler(routedEvent, handler);


text:
Q: python: scipy.spatial: draw a convex polygon and calculate the area I am using python. Now I have some coordinates (earth plane coordinates) and I want to draw a convex polygon based on these coordinates. Besides, I need to save the polygon into a GeoJSON format and calculate the polygon area.
I heard that scipy.spatial can do this but I have no idea how to do that, besides, how to extract the polygon coordinates and calculate the area on earth?
Thanks

A: As far as I know, scipy.spatial does not include the functions you need.
GeoPandas would be suitable for this task. See for instance this example for calculating areas of a polynomial. It also allows to convert between different coordinates system and support output to GeoJSON format.


text:
Q: Facebook login giving issues when users have Arabic name My app has facebook login to enable us to capture users email address and name. However,when a user who has an arabic name is logging in, the Firstname appears as ??????? and email also appears as ????????. I am not understanding where the ? is coming from.
My code for the facebook login is below.
 callbackManager = CallbackManager.Factory.create();
        LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);

        loginButton.setReadPermissions("email","public_profile");

        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    private ProfileTracker mProfileTracker;

                    @Override
                    public void onSuccess(final LoginResult loginResult) {
                        // App code
                        /*
                        String st= loginResult.getAccessToken().getApplicationId();
                        setFacebookData(loginResult);
                        System.out.println(st);
                        */

                        if(Profile.getCurrentProfile() == null) {
                            mProfileTracker = new ProfileTracker() {
                                @Override
                                protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
                                    // profile2 is the new profile
                                    Log.v("facebook - profile2", profile2.getFirstName());
                                   //

                                    mProfileTracker.stopTracking();
                                    profile.setCurrentProfile(profile2);
                                    setFacebookData(loginResult,profile2);
                                }
                            };
                            // no need to call startTracking() on mProfileTracker
                            // because it is called by its constructor, internally.
                        }
                        else {
                            Profile profile = Profile.getCurrentProfile();
                            Log.v("facebook - profile1", profile.getFirstName());
                            setFacebookData(loginResult,profile);
                        }

                    }

                    @Override
                    public void onCancel() {
                        // App code
                        Toast toast=Toast.makeText(context, "Aww!! The connection to Facebook seems to have broken.Please restart Docuwind!!", Toast.LENGTH_SHORT);
                        TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
                        v.setTextColor(Color.RED);
                        toast.show();
                        Intent intent = new Intent(context, RegisterActivity.class);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        // App code
                        Toast toast=Toast.makeText(context, "Aww!! The connection to Facebook seems to have broken.Please try again!!", Toast.LENGTH_SHORT);
                        TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
                        v.setTextColor(Color.RED);
                        toast.show();
                        Intent intent = new Intent(context, RegisterActivity.class);
                        startActivity(intent);
                        finish();

                    }
                });

    }

    public void disconnectFromFacebook() {

        if (AccessToken.getCurrentAccessToken() == null) {
            return; // already logged out
        }

        new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest
                .Callback() {
            @Override
            public void onCompleted(GraphResponse graphResponse) {

                LoginManager.getInstance().logOut();

            }
        }).executeAsync();
    }

The function where the profile information is taken is:
private void setFacebookData(final LoginResult loginResult,final Profile mprofile)
    {
        GraphRequest request = GraphRequest.newMeRequest(
                loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        // Application code
                        try {
                            Log.i("Response",response.toString());

                            String emailadd=null;

                           final String firstName = response.getJSONObject().getString("first_name");
                           final String lastName = response.getJSONObject().getString("last_name");
                            String gender = response.getJSONObject().getString("gender");

                            try {
                                emailadd = response.getJSONObject().getString("email");
                            }
                            catch(Exception e){
                                int n1= 1 + (int)(Math.random() * ((100 - 1) + 1));
                                emailadd=firstName.toLowerCase()+lastName.toLowerCase()+String.valueOf(n1);
                            }
                            final String email=emailadd;

                            savenameinsharedpref(firstName);
                            saveemailinsharedpref(email);
                            final String refreshedToken = FirebaseInstanceId.getInstance().getToken();
                          //  Profile profile = Profile.getCurrentProfile();

                          //  String link = profile.getLinkUri().toString();
                           // Log.i("Link",link);

                                Log.i("Login", "ProfilePic" + mprofile.getProfilePictureUri(200, 200));
                                Uri imageUri = mprofile.getProfilePictureUri(200, 200);

                                ImageView targetImageView = (ImageView) findViewById(R.id.imgview);

                                Glide
                                        .with(context)
                                        .load(imageUri)
                                        .into(targetImageView);

                                int myWidth = 512;
                                int myHeight = 384;

                                Glide.with(context)
                                .load(imageUri)
                                    .asBitmap()
                                    .into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
                                        @Override
                                        public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
                                            // Do something with bitmap here.
                                            ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
                                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos1);

                                          saveinsharedpref(bitmap);

                                        }
                                    });

                            Log.i("Login" + "Email", email);
                            Log.i("Login"+ "FirstName", firstName);
                            Log.i("Login" + "LastName", lastName);
                            Log.i("Login" + "Gender", gender);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,email,first_name,last_name,gender");
        request.setParameters(parameters);
        request.executeAsync();
    }

Is there any way this function could be modified to read arabic characters?

A: I do not think names with Arabic letters would be read through Facebook login.you will have to use a separate login for that which captures string which could have Arabic letters also.


text:
Q: VBA Highlight multiple keywords with wildcard from text strings Any help here would be appreciated please.
The included VBA code almost meets the intended purpose, however, I need a solution that enables the use of wildcards and highlights all parameters contained between "##", "%%" or potentially other special characters (special characters included).
For instance, lets say in the cell range B2:B10 we would find something like:

Checked at ##date1## and ##hour1##

But I want to be able to do a search and highlight using # * # or % * % within a selected determined cell range with the end result (bold being color):

Checked at ##date1## and ##hour1##

Sub HighlightStrings()
    Application.ScreenUpdating = False
    Dim Rng As Range
    Dim cFnd As String
    Dim xTmp As String
    Dim x As Long
    Dim m As Long
    Dim y As Long
    Dim xFNum As Integer
    Dim xArrFnd As Variant
    Dim xStr As String
    cFnd = InputBox("Please enter the text, separate them by comma:")
    If Len(cFnd) < 1 Then Exit Sub
    xArrFnd = Split(cFnd, ",")
    For Each Rng In Selection
    With Rng
    For xFNum = 0 To UBound(xArrFnd)
    xStr = xArrFnd(xFNum)
    y = Len(xStr)
    m = UBound(Split(Rng.Value, xStr))
    If m > 0 Then
    xTmp = ""
    For x = 0 To m - 1
    xTmp = xTmp & Split(Rng.Value, xStr)(x)
    .Characters(Start:=Len(xTmp) + 1, Length:=y).Font.ColorIndex = 3
    xTmp = xTmp & xStr
    Next
    End If
    Next xFNum
    End With
    Next Rng
    Application.ScreenUpdating = True
End Sub

Thank you

A: Okay This seems to work for me. There is a limitation we can work on if required: the phrase to highlight must be padded with spaces on both sides.
Option Explicit
Option Base 0
Sub testreplace()

Dim I As Integer        'Iteration
Dim FlagNum As Integer  'Flag Number
Dim RG As Range         'Whole range
Dim CL As Range         'Each Cell
Dim FlagChar As String  'Flag characters
Dim ArrFlag             'Flag Char Array
Dim TextTemp As String  'Cell Contents

Set RG = Selection
FlagChar = "##"
FlagChar = InputBox("Enter 'Flag Characters' separated by a comma." & vbCrLf & vbCrLf & _
                "Example:" & vbCrLf & vbCrLf & _
                "##,%%,&&" & vbCrLf & _
                "$$,XX", "Flag Characters to Highlight", "##,%%")

ArrFlag = Split(FlagChar, ",")

For Each CL In RG.Cells
    TextTemp = CL.Value
    For FlagNum = 0 To UBound(ArrFlag)
        For I = 1 To Len(TextTemp)
            'Debug.Print "<<" & Mid(TextTemp, I, Len(ArrFlag(Flagnum)) + 1) & _
                "=" & " " & ArrFlag(Flagnum) & ">>"
            If Mid(TextTemp, I, Len(ArrFlag(FlagNum)) + 1) = " " & ArrFlag(FlagNum) Then
                CL.Characters(I + 1, InStr(I, TextTemp, ArrFlag(FlagNum) & " ") + _
                    Len(ArrFlag(FlagNum)) - I).Font.ColorIndex = 3
            End If
        Next I
    Next FlagNum
Next CL

End Sub
Here's an example of it working:


text:
Q: Can't use facebook's quick replies I want to use facebook's quick replies -
at first I tried to use IMessageActivity's SuggestedActions property
IMessageActivity result = Activity.CreateMessageActivity();
result.Type = ActivityTypes.Message;
result.TextFormat = TextFormatTypes.Plain;
result.SuggestedActions = suggestedActions.Select(x => new CardAction()
                {
                    Title = x,
                    Type = ActionTypes.ImBack,
                    Value = x
                }).ToList()

but, as it didn't work for facebook, I found another solution based on ChanelData
result.ChannelData = JObject.FromObject(new {
                quick_replies = suggestedActions.Actions.Select(x => new
                {
                    content_type = "text",
                    title = x.Title,
                    payload = x.Value is null ? x.Title : x.Value
                }).ToArray()
            });

sadly it still doesn't work. Is there anything else to do?

A: Try using a TextPrompt with the PromptOptions like this:
await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
{
    Prompt = new Activity
    {
        Type = ActivityTypes.Message,
        Text = "¡Bien! Ahora te envié un código de acceso a tu teléfono. Por favor ingrésalo aquí cuando lo recibas.",
        SuggestedActions = new SuggestedActions()
        {
            Actions = new List<CardAction>()
            {
                new CardAction() { Title = "Reenviar token", Type = ActionTypes.ImBack, Value = "Reenviar token" }
            },
        },
    }
});

Result:

Edit:
If you dont want to use prompts, try this:
Activity activity = stepContext.Context.Activity.CreateReply();
activity.Type = ActivityTypes.Message;
activity.Text = "This is an example of SuggestedAction";
activity.SuggestedActions = new SuggestedActions()
{
    Actions = new List<CardAction>()
    {
    new CardAction() { Title = "Action", Type = ActionTypes.ImBack, Value = "Action" }
    }
};
await stepContext.Context.SendActivityAsync(activity);
return await stepContext.EndDialogAsync();

Result:

A: I beleive you can use HeroCards and attach them to an activity and send that via SendActivityAsync.
Activity activity = _context.Context.Activity.CreateReply();
        var buttonList = new List<CardAction>();

        foreach (var prompt in Prompts)
        {
            buttonList.Add(
                new CardAction { Value = prompt.DisplayText, Type = "imBack", Title = prompt.DisplayText, });
        }

        var heroCard = new HeroCard { Text = "message text", Subtitle = string.Empty, Buttons = buttonList };

        activity.Attachments.Add(heroCard.ToAttachment());

        await stepContext.Context.SendActivityAsync(activity).ConfigureAwait(false);


text:
Q: How to put a button in the middle of a div in bootstrap 3? In my html with bootstrap 3 I have 3 columns defined in divs with col-xs- classes .
The first and third are lists.
In the middle column I want to put a button that transfers elements from the first list to the third by jquery.
I would like the button to be in the middle of both lists and to be responsive.
I have tried this but the button is not well centered in the middle and does not adapt well to the different widths of the screen.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    ... list1 code

              <button type="button" class="btn btn-default child"> > </button>

    ... list3 code

div{
    height: 50rem;
}

.contenedor-de-lista {
  height: 50rem;
}

.father{
  position: relative;
}
.child {
  /* Center vertically and horizontally */
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -25px 0 0 -25px; /* apply negative top and left margins to truly center the element */
}

https://jsfiddle.net/JorgePalaciosZaratiegui/vn8sgrcq/18/
How can I make the button stay in the middle and fit the screen size as the bootstrap class col-md-x works.
Thanks in advance

A:

#container{
display:flex;
justify-content:space-between;
align-items:flex-start;
}

.father{
display:flex;
flex-direction:column;
justify-content:center;
height:100vh;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    ... list1 code

              <button type="button" class="btn btn-default child"> > </button>

    ... list3 code

A: You could use flex to center element. I hav edited your code.
Added display: flex to the class .text-center

div{
    height: 50rem;
}

.contenedor-de-lista {
  height: 50rem;
}

.father{
  position: relative;
}
.text-center{
  display:flex;
  justify-content:center;
  align-items:center;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    ... list1 code

              <button type="button" class="btn btn-default child"> > </button>

    ... list3 code


text:
Q: Relative positioning with z-index I have 2 divs. Second is under first.

2nd div has z-index: -1; top: -20px; position: relative. Now I want to put some links(a-tag) into 2nd div: test. Now I see my link but it's inactive. I can't click at it. When I remove z-index: -1 it works. What's wrong?

A: A negative z-index can behave buggy. I would give the top div a higher z-index. You can better have something like this:
div.1 {
  position: relative;
  z-index: 3;
}
div.2 {
  position: relative;
  top: -20px
}

You're links should be clickable, if they are visible of course.


text:
Q: create insert if not exist in mysql In MySql we can choose INSERT IGNORE(do not update existing) to generate a sql file with query CREATE TABLE IF NOT EXISTS and  INSERT IGNORE INTO.
But in this case,if the table exists, the "INSERT IGNORE INTO" will insert data again.
   I'd like to ask,is there a method, to realize the function: If table doesn't exist, it will create the table and insert data.
If the table exists, it will not insert data.
In fact I have tried how to realize, I know with a stored procedure it is possible, but with a sql file which will be executed by batch file, how to realize the function?
My curent code is like this
CREATE DATABASE IF NOT EXISTS martintest;

USE martintest;
CREATE TABLE IF NOT EXISTS `martin1` (
  `col1` int(11) default NULL,
  `col2` text
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT IGNORE INTO `martin1` (`col1`, `col2`) VALUES    (2, 'bbb'), (1, 'aaa');

A: One option, perhaps not recommended (one must be careful with session variables, in this case, with: @`table_exists?`), but an option in the end, is something like:
/* CODE FOR DEMONSTRATION PURPOSES */

USE `martintest`;

SET @`table_schema` := 'martintest', @`table_name` := 'martin1';

SELECT EXISTS
    (
        SELECT NULL
        FROM `information_schema`.`TABLES` `ist`
        WHERE `ist`.`TABLE_SCHEMA` = @`table_schema` AND `ist`.`TABLE_NAME` = @`table_name`
    )
INTO @`table_exists?`;

CREATE TABLE IF NOT EXISTS `martin1` (
  `col1` int(11) DEFAULT NULL,
  `col2` text
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `martin1` SELECT 2, 'bbb' FROM DUAL WHERE 0 = @`table_exists?`;
INSERT INTO `martin1` SELECT 1, 'aaa' FROM DUAL WHERE 0 = @`table_exists?`;

/* CODE FOR DEMONSTRATION PURPOSES */

A: Use CREATE TABLE without IF NOT EXISTS.
If the table exists, it will fail and the rest of the file will not be imported .
Do not use --force parameter,.

A: Check if the table exists first:
USE martintest;
SET @tablecount := 0

SELECT @tablecount := count(*)
INTO @tablecount
FROM information_schema.tables
WHERE table_schema = 'martintest'
AND table_name = 'martin1'

--check if table count = 0
IF @tablecount = 0
(

CREATE TABLE `martin1` (
  `col1` int(11) default NULL,
  `col2` text
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `martin1` (`col1`, `col2`) VALUES    (2, 'bbb'), (1, 'aaa');

)


text:
Q: Spring MVC, Spring Data JPA, Spring Security integration I have a Spring MVC web app which uses JPA and Hibernate to map objects to a MySQL database. I have added Spring Security and have it working so far as using an in memory model. I want to add user and role entities to integrate with Spring Security.
I was wondering if someone could point me in the direction of how to do this or any tutorials on how to accomplish this?

A: Implement an UserDetailsService which loads your User- and Rolemodel. Its just the loadUserByUsername which will return a UserDetails Object. The UserDetails itself will have a list of all roles. A role is here called know as GrantedAuthority. Theres a SimpleGrantedAuthority to create it from a simple Rolename (String).
But maybe JdbcDaoImpl is enough for your needs.
Update due question in comment:
Just design your User Role relation as you would normally do. In your UserDetails Implementation you need to return your roles in getAuthorities as GrantedAuthority.
Example:
reduced to the minimum.
Role
@Entity(name = "auth_role")
public class Role {

  @Id
  @Column
  private String id;

  @Column(nullable = false, unique = true)
  /**
   *unique and transformed to GrantedAuthority,can be used in Spring expression hasRole, etc
  **/
  private String name;

  @Column(nullable = true)
  private String description;
}

User
@Entity(name = "auth_user")
public class User implements UserDetails {

   @Id
   @Column
   private String id;

   @Column(nullable = false, unique = true)
   private String name;

   @ManyToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
   /**
    * relation to our roles
   **/
   private Set<Role> roles = new HashSet<Role>();

   /**
   * implements getAuthorities and transformes our Roles using the unique names to
   * SimpleGrantedAuthority
   **/
   public Collection<? extends GrantedAuthority> getAuthorities() {
     Set<GrantedAuthority> authList = new HashSet<GrantedAuthority>();

     for (Role role : user.getRoles()) {
       authList.add(new SimpleGrantedAuthority(role.getName()));
     }

     // Return list of granted authorities
     return authList;
   }
}


text: Q: Dissolve polygons using clustering The attached vector file contains thousands of individual polygons (a byproduct of the underlying raster image). The result of using polygonize function in qgis. My intent is to dissolve the polygons into few continuous polygons using clustering or some other prudent algorithm. Alternately not sure if i could make changes to raster file.


text:
Q: How can I do this in Jade (pug)?

      Profile

I don't know how to put i and "Profile" in a. Please help me!

A: I found that the inline tags can solve it!
ul(class='dropdown-menu')
  li #[a(href="javascript:void(0)") #[i(class=['ti-user', 'm-r-5'])] Profile]

A: You can use online service to convert HTML to Jade, for example: http://html2jade.org/
Here is an answer:
html
  body
    ul.dropdown-menu
      li
        a(href='javascript:void(0)')
          i.ti-user.m-r-5
            | Profile


text:
Q: handle 'URL prompts save file' python Please don't say selenium.
it should be an easy step. thank you!
    #usr/bin/python 3.6 on win10x64

    from datetime import datetime
    import json
    import requests

    current_time = datetime.datetime.now(datetime.timezone.utc)
    url = 'https://api.nicehash.com/livePubJSON?l=0&a=07callback=superagentCallback'+str(round(int(current_time.timestamp()), 2)).replace('.','')
    js_file = requests.get(url).json() #this is not correct, and also it will always send the 'livePubJSON.js' file
    with open(r'C\Users\[myusername]\Downloads\livePubJson.js') as json_data: # being API file.js i would like to be replaced
        d = json.load(json_data)
        print(d)

please help me to make this a loop because it's an API
to save time:
response is 200 but I think i need headers HTTP error 403 so here are some copy paste i grabbed from youtube:
headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux i868) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17'
Next is the livePubJSON.js output(from browser UI) and have to read parse it as JSON:
superagentCallback1518811920564( {"eu":{"valid":true,"updated":1518811927,
"totalSpeed":6.6999,"orders":[[720747,1,1,2.3261,0.01,29,0.0105],...


text:
Q: Mybatis: Map part of the SQL to HashMap inside POJO In my daily work, I found the necessity of mapping a SQL to its POJO. Besides the columns of the POJO itself, I had some calculated columns that needed to map somewhere. Mapping it to new variables in the POJO didn't seem the best option, as I actually didn't know how many new columns I would need (now and in the future).
Example SQL:
select id, name, surname,
  calculated_column_1, calculated_column_2, ...
  from person
  left outer join ...

calculated_column_1 and calculated_column_2 are -- as their name say -- calculated columns depending of another table.
I didn't know if I was going to need 1, 2 or N calculated columns.
How can it be mapped to the pojo?

A: After many tries, I found the solution as follows:
POJO:
private int id;
private String name;
private String surname;
private HashMap<String, Object> aditionalColumns;

// getters & setters

MyBatis Mapper:
<resultMap id="BaseResultMap" type="Person" automapping="true">
  <id column="id" property="id"/>
  <association
      property="aditionalColumns"
      resultMap="aditionalColumnsMapper"
      columnPrefix="calculated_" />
</resultMap>

<resultMap id="aditionalColumnsMapper" type="map" autoMapping="true"/>

In this case, my aditionalColumns HashMap would look like this after mapping:
{column_1=value1, column_2=value2}

Note: I didn't know how many columns I needed, if you know exactly how many you need, and it won't change, you can map only your columns changing the second resultMap as follows:
<resultMap id="aditionalColumnsMapper" type="map">
    <result column="calculated_column_1" property="calculated_column_1"/>
    <result column="calculated_column_2" property="calculated_column_2"/>
</resultMap>


text:
Q: Is there a way to specify an input file containing the files to include when creating a zip? I have a list of files paths which I am gathering via a script I wrote. These paths are several thousand. Is there a way to have them stored in an input file and then passed into to zip when creating the zip?

A: From the man page:

-@ file lists.  If a file list is specified as -@ [Not on MacOS], zip takes the list of input files from standard input instead of from the
         command line.

So you can do:
zip file.zip -@ < file_containing_list_of_paths

You don't even need the file, you can pipe directly to zip. The example in the man page is:
find . -name "*.[ch]" -print | zip source -@


text:
Q: Convert xml file to pandas dataframe I am new to using pandas with xml data and I can't figure out how to convert an xml file to pandas dataframe using the standard read_xml function. I tried the following code, but it is not picking up the data fields
import pandas as pd

xml='''
<TimeSeries xmlns="http://www.wldelft.nl/fews/PI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.wldelft.nl/fews/PI http://fews.wldelft.nl/schemas/version1.0/pi-schemas/pi_timeseries.xsd" version="1.26" xmlns:fs="http://www.wldelft.nl/fews/fs">
    <timeZone>1.0</timeZone>
    <series>
        <header>
            <type>instantaneous</type>
            <moduleInstanceId>pr.pompvolumes</moduleInstanceId>
            <locationId>SL000246</locationId>
            <parameterId>Q.B.d</parameterId>
            <timeStep unit="second" multiplier="86400"/>
            <startDate date="2018-01-01" time="00:00:00"/>
            <endDate date="2022-01-01" time="00:00:00"/>
            <missVal>NaN</missVal>
            <stationName>Putten vijzel</stationName>
            <lat>52.263570497449855</lat>
            <lon>5.495717667656339</lon>
            <x>162408.0</x>
            <y>475066.0</y>
            <units>m3/s</units>
        </header>
        <event date="2018-01-01" time="00:00:00" value="1.262" flag="0"/>
        <event date="2018-01-02" time="00:00:00" value="1.456" flag="0"/>
        <event date="2018-01-03" time="00:00:00" value="0.845" flag="0"/>
        <event date="2018-01-04" time="00:00:00" value="1.507" flag="0"/>
        <event date="2018-01-05" time="00:00:00" value="1.083" flag="0"/>
        <event date="2018-01-06" time="00:00:00" value="0.516" flag="0"/>
        </series>
</TimeSeries>
'''

df = pd.read_xml(xml)

The resulting dataframe should have a format such as:
data = [['2018-01-01', 1.262, 0], ['2018-01-02', 1.456, 0], ['2018-01-03', 0.845, 0]]
df = pd.DataFrame(data, columns=['event date', 'value', 'flag' ])

Any help greatly appreciated!

A: *

*Use pd.read_xml with a dict assigned to the namespaces parameter, where the key is a "temporary namespace prefix" (e.g. doc), and the value references the namespace denoted as xmlns (so: http://www.wldelft.nl/fews/PI).

*This dict is then used to find the correct xpath. Here: 'doc:series/doc:event'.

df = pd.read_xml(xml, xpath='doc:series/doc:event',
                 namespaces={'doc':'http://www.wldelft.nl/fews/PI'})

print(df)

         date      time  value  flag
0  2018-01-01  00:00:00  1.262     0
1  2018-01-02  00:00:00  1.456     0
2  2018-01-03  00:00:00  0.845     0
3  2018-01-04  00:00:00  1.507     0
4  2018-01-05  00:00:00  1.083     0
5  2018-01-06  00:00:00  0.516     0

# drop `time`
df.drop('time', axis=1, inplace=True)


text:
Q: Iterate through Flux items and add them in to Mono object I am working on the api, which takes ids. For the given id, I want to download related data from s3 and put them in a new object lets call it data
class Data {
  private List<S3Object> s3Objects;
  //getter-setter
}

   public Mono<ResponseEntity<Data>> getData(@RequestParam List<String> tagIds){
        Data data = new Data();
        Flux<S3Object> s3ObjectFlux = Flux.fromStream(tagIds.stream())
                .parallel()
                .runOn(Schedulers.boundedElastic())
                .flatMap(id -> fetchResources(id))
                .flatMap(idS3Object -> Mono.just(s3Object))
                .ordered((u1, u2) -> u2.hashCode() - u1.hashCode());

        //how do i add it in data object to convert Mono<Data>?
    }

A: You need to collect it into a list and then map it to create a Data object as follows:
public Mono<ResponseEntity<Data>> getData(@RequestParam List<String> tagIds){

   Flux<S3Object> s3ObjectFlux = Flux.fromStream(tagIds.stream())
           .parallel()
           .runOn(Schedulers.boundedElastic())
           .flatMap(id -> fetchResources(id))
           .flatMap(idS3Object -> Mono.just(s3Object))
           .ordered((u1, u2) -> u2.hashCode() - u1.hashCode());

   Mono<Data> data = s3ObjectFlux.collectList()
           .map(s3Objects -> new Data(s3Objects));
}

Creating a constructor that accepts the S3 objects list is helpful:
class Data {
  private List<S3Object> s3Objects;

  public Data(List<S3Object> s3Objects) {
      this.s3Objects = s3Objects;
  }

  //getter-setter
}


text:
Q: Detect whether system supports an alpha channel (via wxWidgets) I've got a wxWidgets program. For one piece of it, I want to use an alpha channel to "fade" a set of icons if the system supports alpha-blending, and grayscale them if it doesn't, but I can't seem to find any way to tell whether the system supports alpha-blending or not.
Is there something I'm missing, or is there no wxWidgets and/or cross-platform way to do this?
(I'm fairly well conversant with wxWidgets, but I've never done alpha-blending before.)

A: From what I can tell, you call CanSetTransparent on a top-level window, and if it returns true, call SetTransparent with a value < 255. If that returns true, then the system supports alpha transparency. You must do this after the top-level window you're working with is shown.
(CanSetTransparent just checks the OS version under Windows, always returns true under Mac OS, and checks both the compile-time GTK version and a function on wxGTK. SetTransparent takes different paths on Windows and GTK depending on whether the value is 255 or something less.)


text:
Q: Parsing dates with correct time zone in perl with core modules only I have to do several checks with dates I read from a database.
For instance, I have to compare them with a perl script's local time.
I also have to determine the calendar date of a parsed date.
In order to have readable code, I I would like to have identical time zone information in both generated (localtime) and parsed (strptime) time objects.
The solution should be 1-file only, so the task should be done with core perl modules only (version 5.10). So the DateTimemodule doesn't seem like an option.
The closest I have come is Time::Piece, but there seems to be no way to get a time object by parsing that is identical to one obtained by Time::Piece::localtime().
use Time::Piece;
use strict;
use warnings;
use 5.010;

sub mystrptime1 {
    my $datestr = shift;
    my $tzoffset = sprintf '%+03d00', localtime->tzoffset->hours;
    my $t = Time::Piece->strptime("$datestr $tzoffset", '%Y%m%d %H:%M:%S %z');
}

sub mystrptime2 {
    my $datestr = shift;
    my $t = Time::Piece->strptime($datestr, '%Y%m%d %H:%M:%S');
    # it will be interpreted as GMT, so subtract the time zone offset :-(
    return $t - Time::Piece::localtime->tzoffset;
}

my $FORMAT = '%Y%m%d %H:%M:%S';

for my $strptime (\&mystrptime1, \&mystrptime2) {
    my $lt = Time::Piece::localtime();
    say "localtime is $lt, tz offset is ", $lt->tzoffset();

    my $str = $lt->strftime($FORMAT);
    say "str is $str";
    my $g = $strptime->( $str );

    say "parsed time is $g, tz offset is ", $g->tzoffset();

    say "time difference is: ", $lt-$g;
    say "hour difference is: ", $lt->hour - $g->hour;
}

What I want is both hour difference and time difference of zero, which seems to be impossible.

A: I was able to make both solutions work by by calling localtime on the strptime result:
sub mystrptime1 {
    my $datestr = shift;
    my $tzoffset = sprintf '%+03d00', localtime->tzoffset->hours;
    my $t = Time::Piece->strptime("$datestr $tzoffset", '%Y%m%d %H:%M:%S %z');
    return Time::Piece::localtime($t->epoch);
}

sub mystrptime2 {
    my $datestr = shift;
    my $t = Time::Piece->strptime($datestr, '%Y%m%d %H:%M:%S');
    # it will be interpreted as GMT, so subtract the time zone offset :-(
    $t -= Time::Piece::localtime->tzoffset;
    return Time::Piece::localtime($t->epoch);
}


text:
Q: How can to show more than one form value in a alert? I'm submitting a form which its deleting record.
It's a simple checkbox, if the user check the box then
that record will be deleted from the table , which works.
What I would like to do its have a alert box which shows
the name of the person(s) they are deleting before and then they confirm it which then it will be deleted.
Right now im using ajax to show the alert but its only showing the first record I check ,
It still deleting all the records but I would like it to show all all the names before the user confirm it.
How would I be able to accomplish this?
function sub_keys()
    {
    alert_string='Are you sure you want to delete ';
    var con=confirm( alert_string + document.getElementById("name_id").value + '?');
               if(con)
               {
               var formData = $("#confrm_key").serializeArray();

                var URL = 'quality_time_delete_table2.cfc?method=getkeyDetail';

                more code.....
    }

form:
<input type="hidden" name="name_Id" id="name_id" value="#emp_namefirst# #emp_namelast# ">

A: You can add a class in your checkboxes and use js querySelectorAll and Array.prototype.map():

var text = document.querySelectorAll('.name');
var values = [].map.call(text, function(obj) {
  return obj.innerHTML;
});
confirm(values);

test1

test2

test3

test4

And one example close to your needs:

function deletePeople() {
    var text = document.querySelectorAll('input[type=checkbox]:checked');
    var values = [].map.call(text, function (obj) {
        return obj.value;
    });
    var res = confirm(values);
    res ? alert("records deleted") : alert("no action");
}
<input type="checkbox" value="test1" />
<input type="checkbox" value="test2" />
<input type="checkbox" value="test3" />
<input type="checkbox" value="test4" />
<input type="button" onclick="deletePeople();return false;" value="Delete" />

Also keep in mind that id must be unique.
References:
Array.prototype.map()
document.querySelectorAll


text:
Q: PHP OOP how to group configuration data i wanna store some configuration data in some objects, and i've a problem...
class B {
  const attr1 = 'something1';
  const attr2 = 'something2';
  const attr3 = 'something3';
}

class A {
  const attr1 = 'somethingA1';
  const attr2 = 'somethingA2';
  const attr3 = 'somethingA3';
  const b = <---- i wanna put here a reference of B, but B as a class (not an object...), i'm crazy?
}

I'm not sure if my example is clear... from A, i want to access to attr1 of B, like A::B::attr1, or something like this, there's another way to do this? Or i'm wrong?

A: There is no way to assign reference to a Class, nor is there a way to assign class constants at runtime. So your entire approach is pretty much impossible. What you can do is
const b = 'B'

and as of PHP 5.3.0 you could then do
$b = A::b;
echo $b::attr1;

but you cannot do A::b::attr1. This will raise a T_PAAMAYIM_NEKUDOTAYIM error. It's a parser limitation. PHP cannot do this as of this writing.

Because the class B contains a group of data of A, i want to store in b (of A) a complex data, i want to do like this because i wanna keep the code clean

You can solve this easily by making B a composite of A, e.g. you either inject B into A when you create A
class A
{
    private $b;

    public function __construct(B $b)
    {
        $this->b = $b;
    }
}
$a = new A(new B);

or create B inside A, e.g.
class A
{
    private $b;

    public function __construct()
    {
        $this->b = new B;
    }
}

Because B is just the data parts of A, you tunnel all public access through A instead of getting hold of B and then using B's methods. So any code using A does not need to know there is some B inside A. This will allow you to change B easily without needing to worry about code that consumes A, e.g. to get attr1 you add a getter to A:
public function getAttr1()
{
    $b = $this->b;
    return $b::attr1;
}

You can mitigate the clumsy need for assignment when using properties instead of constants in B (constants are stupid in PHP anyway as you have to treat them as public API), e.g.
class B
{
    private $attr1;

    public function getAttr1()
    {
        return $this->attr1;
    }
}

And then you can do in A:
public function getAttr1()
{
    return $this->b->getAttr1();
}

Even better would be not to expose the internals of B through A altogether though and only add public methods that do something with A. This will make your API much smaller and your code more OO.

A: You cannot reference to a class like that, because the only way you will ever use the class is through an object, so there is no point trying to do that either.
User this:
class A {
  const attr1 = 'somethingA1';
  const attr2 = 'somethingA2';
  const attr3 = 'somethingA3';
  public $b;

  function __construct() {
    $this -> b = new b();
}

A: You can simply say b = "B" ..
and if you want to create object of B , You can do  new b or access the properties


text:
Q: regex using positive lookahead My source data text looks something like this:
a1,a2,a3
a4,a5,a6
a7,a8,a9
test="1"
b1,b2,b3
b4,b5,b6
b7,b8,b9
test="2"
c1,c2,c3
c4,c5,c6
c7,c8,c9
test="3"

I need to parse this so the end result looks like this (appropriate "test" field included in each row):
a1,a2,a3,1
a4,a5,a6,1
a7,a8,a9,1
b1,b2,b3,2
b4,b5,b6,2
b7,b8,b9,2
c1,c2,c3,3
c4,c5,c6,3
c7,c8,c9,3
...etc

this what I started with and captures the fields correctly:
(?<f1>.*?),(?<f2>.*?),(?<f3>.*?)\s+

I understand I need to use lookarounds to capture and include the "test" field on each line.
So something like this added (using a positive lookahead)…
(?<f1>.*?),(?<f2>.*?),(?<f3>.*?)\s+(?=test="(?<test>.*?)")

This seems close but is not yielding all rows of data, but instead only the last row of data with the included test value as if it is consuming the look ahead row.
This expression with its captured groups are input into a .NET application that inserts these captured groups as fields within a database table. Number of fields is always static (4 in the example above; field1=f1, field2=f2, field3=f3, field4=test), but the number of records will be variable.
Any guidance would be appreciated.

A: Parsing your data to extract the relevant values
You are almost there, but need to allow the look ahead to skip the rows between the current one and the test line:
(?ms)(?<f1>\w+),(?<f2>\w+),(?<f3>\w+)\R(?=.*?^test="(?<test>\d+)")

\R matches all sort of newlines, (?ms) is the inline way of turning on the multiline and dot match all modifiers, so that .*?^test matches every line up to the test one, see demo here.
Again, your issue was that \s+ forced the lookahead to be on the line right after the one your were matching.


text:
Q: Criteria to perform Cross Validation Now I know why we do Cross Validation. And how we do it. I have few questions around it though:

*

*Why can't we do that on every dataset we work on? Like, why shouldn't it be a standard, or a rule of thumb, if you may - "Instead of train-test split, do Cross Validation" ...

*Is there a certain size of dataset we need to consider before performing it? Like, can it be done on like dataset with 6 to 9 digit rows? If not, what's the alternate? Bootstrapping? I heard from someone that it may not perform well with huge dataset.

*Does it make sense in performing it on a heavily biased data set?

Thanks in advance.

A: As @Henry pointed out Cross Validation is a method of training the model and figuring out the best set of parameters. If you just have 1 test set it can be that your hyperparameters are overfitted to that set.
• We always try to do cross-validation. If however, you have a large enough dataset that captures your data distribution well then it's not necessary to do cross-validation ( in cases of Big data ). This assumption heavily depends on the test set. Cross-validation takes a lot of time for computation since you have to tune K such models hence you avoid in cases when the time is of the essence.
• In small datasets one thing that's famous is setting K = size of data - 1 in cross-validation aka OOB error since you already have low enough data and should be trying to use each data point while modelling.
• I don't particularly understand what you mean biased. There are splitting like stratified that ensure the same distribution of labels is in the test dataset as compared to train

A: *

*You can do it in every dataset you work on. The major drawback (and the reason why train-test split approach is  still widely used) is that CV is computationally expensive. If you are dealing with huge datasets and you use a n-fold CV, then the model has to be trained n times. On the contrary, with train-test it only has to be trained once.

*There is no specific criteria regarding the size of the dataset, although the smaller the dataset the less number of folds should be used. It is worth to point out  that 6 to 9 digit rows is minuscule amount of data to perform neither CV nor any other approach.

*If for heavily biased dataset you mean that imbalancement exists, then you should deal with it regardless of the performance assessment method used.