问:
Python - Data manipulation in a file
I'm at the stage where I've a txt file in the form:

```<code>text1;10;20;11
text2;3;4;5
text3;4;5;7
</code>```

Anyone got any idea what function to use to get rid of the numbers in the middle of each line?
I would like to have in output:

```<code>text1;11
text2;5
text3;7
</code>```

Currently I have done:

```<code>    for ii in files:
        if ii.endswith(".txt"):  # only txt files
            with open(ii, 'r') as f:
                content = f.read()
                f.close()
                content1 = re.sub('\t', '', content, flags=re.M)
                content2 = re.sub(' ', '', content1, flags=re.M)
                f = open(ii, "w+")
                f.write(content2)
                f.close()
</code>```

答:
You can just split the String with the split method and get the first and last element together

```<code>s = "text1;10;20;11"
result = s.split(";")[0] + ";" + s.split(";")[-1]
</code>```

output will be text1;11

Title: Python - Data manipulation in a file

Body:
I'm at the stage where I've a txt file in the form:

text1;10;20;11
text2;3;4;5
text3;4;5;7

Anyone got any idea what function to use to get rid of the numbers in the middle of each line?
I would like to have in output:

text1;11
text2;5
text3;7

Currently I have done:

    for ii in files:
        if ii.endswith(".txt"):  # only txt files
            with open(ii, 'r') as f:
                content = f.read()
                f.close()
                content1 = re.sub('\t', '', content, flags=re.M)
                content2 = re.sub(' ', '', content1, flags=re.M)
                f = open(ii, "w+")
                f.write(content2)
                f.close()

Body:
You can just split the String with the split method and get the first and last element together

s = "text1;10;20;11"
result = s.split(";")[0] + ";" + s.split(";")[-1]

output will be text1;11


来源: stackexchange

问:
How do I delete a commit from a branch?
How do I delete a commit from my branch history? Should I use git reset --hard HEAD?

答:
With more than 30 ansers here, I'll keep it simple with what works for me

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

Checkout

```<code>git checkout --orphan latest_branch
</code>```

Add all the files

```<code>git add -A
</code>```

Commit the changes

```<code>git commit -m "commit message"
</code>```

Delete the branch

```<code>git branch -D master
</code>```

Rename the current branch to master

```<code>git branch -m master
</code>```

Finally, force update your repository

```<code>git push -f origin master
</code>```

PS: this will not keep your old commit history around.

ContentLicense: CC BY-SA 4.0

Title: How do I delete a commit from a branch?

Body:
With more than 30 ansers here, I'll keep it simple with what works for me

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

Checkout

git checkout --orphan latest_branch

Add all the files

git add -A

Commit the changes

git commit -m "commit message"

Delete the branch

git branch -D master

Rename the current branch to master

git branch -m master

Finally, force update your repository

git push -f origin master

PS: this will not keep your old commit history around.


问:
How to make data model of this api?
I want to make a data model for my cartList api. if you hit following api in your browser 5 product will be added to your cart.

https://www.moharaj.com.bd/_public/addToCart?quantity=5&slug=cotton-fleece-hoodie-for-men-tekka-8486&variant_id=$variant_id=24469

you can check your cart list through this api:

https://www.moharaj.com.bd/_public/cartToContent

But my problem is when I try to make a model of this cartToContent that means cart list api there always generate a unique row Id or token which I can't store. can anyone has any idea how to make a data model of this api?? I have made a data model. I have given below:

```<code>// To parse this JSON data, do
//
//     final cartToContentModel = cartToContentModelFromJson(jsonString);

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

CartToContentModel cartToContentModelFromJson(String str) => CartToContentModel.fromJson(json.decode(str));

String cartToContentModelToJson(CartToContentModel data) => json.encode(data.toJson());

class CartToContentModel {
    CartToContentModel({
        required this.cartTotal,
        required this.cartContent,
        required this.itemCount,
    });

    String cartTotal;
    CartContent cartContent;
    int itemCount;

    factory CartToContentModel.fromJson(Map<String, dynamic> json) => CartToContentModel(
        cartTotal: json["cart_total"],
        cartContent: CartContent.fromJson(json["cart_content"]),
        itemCount: json["item_count"],
    );

    Map<String, dynamic> toJson() => {
        "cart_total": cartTotal,
        "cart_content": cartContent.toJson(),
        "item_count": itemCount,
    };
}

class CartContent {
    CartContent({
        required this.c827Cdf7Ba8F3127F293690569Aff167,
    });

    C827Cdf7Ba8F3127F293690569Aff167 c827Cdf7Ba8F3127F293690569Aff167;

    factory CartContent.fromJson(Map<String, dynamic> json) => CartContent(
        c827Cdf7Ba8F3127F293690569Aff167: C827Cdf7Ba8F3127F293690569Aff167.fromJson(json["c827cdf7ba8f3127f293690569aff167"]),
    );

    Map<String, dynamic> toJson() => {
        "c827cdf7ba8f3127f293690569aff167": c827Cdf7Ba8F3127F293690569Aff167.toJson(),
    };
}

class C827Cdf7Ba8F3127F293690569Aff167 {
    C827Cdf7Ba8F3127F293690569Aff167({
        required this.rowId,
        required this.id,
        required this.name,
        required this.qty,
        required this.price,
        required this.weight,
        required this.options,
        required this.discount,
        required this.tax,
        required this.subtotal,
    });

    String rowId;
    int id;
    String name;
    String qty;
    int price;
    int weight;
    Options options;
    int discount;
    int tax;
    int subtotal;

    factory C827Cdf7Ba8F3127F293690569Aff167.fromJson(Map<String, dynamic> json) => C827Cdf7Ba8F3127F293690569Aff167(
        rowId: json["rowId"],
        id: json["id"],
        name: json["name"],
        qty: json["qty"],
        price: json["price"],
        weight: json["weight"],
        options: Options.fromJson(json["options"]),
        discount: json["discount"],
        tax: json["tax"],
        subtotal: json["subtotal"],
    );

    Map<String, dynamic> toJson() => {
        "rowId": rowId,
        "id": id,
        "name": name,
        "qty": qty,
        "price": price,
        "weight": weight,
        "options": options.toJson(),
        "discount": discount,
        "tax": tax,
        "subtotal": subtotal,
    };
}

class Options {
    Options({
        required this.attributeId,
        required this.variantId,
        required this.image,
    });

    dynamic attributeId;
    String variantId;
    List<Image> image;

    factory Options.fromJson(Map<String, dynamic> json) => Options(
        attributeId: json["attribute_id"],
        variantId: json["variant_id"],
        image: List<Image>.from(json["image"].map((x) => Image.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "attribute_id": attributeId,
        "variant_id": variantId,
        "image": List<dynamic>.from(image.map((x) => x.toJson())),
    };
}

class Image {
    Image({
        required this.id,
        required this.productId,
        required this.productImage,
        required this.createdAt,
        required this.prefixUrl,
        required this.updatedAt,
    });

    int id;
    int productId;
    String productImage;
    DateTime createdAt;
    String prefixUrl;
    DateTime updatedAt;

    factory Image.fromJson(Map<String, dynamic> json) => Image(
        id: json["id"],
        productId: json["product_id"],
        productImage: json["product_image"],
        createdAt: DateTime.parse(json["created_at"]),
        prefixUrl: json["prefix_url"],
        updatedAt: DateTime.parse(json["updated_at"]),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "product_id": productId,
        "product_image": productImage,
        "created_at": createdAt.toIso8601String(),
        "prefix_url": prefixUrl,
        "updated_at": updatedAt.toIso8601String(),
    };
}
</code>```

答:
You can make the map of cartitems values to list of cartitems.

Here's the updated model.

```<code>// To parse this JSON data, do
//
//     final cartToContentModel = cartToContentModelFromMap(jsonString);

import 'dart:convert';

class CartToContentModel {
    CartToContentModel({
        this.cartTotal,
        this.cartContent,
        this.itemCount,
    });

    final String cartTotal;
    final List<CartContent> cartContent;
    final int itemCount;

    factory CartToContentModel.fromJson(String str) => CartToContentModel.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory CartToContentModel.fromMap(Map<String, dynamic> json) => CartToContentModel(
        cartTotal: json["cart_total"],
        cartContent: List<CartContent>.from(json["cart_content"].values.map((item) => CartContent.fromMap(item))),
        itemCount: json["item_count"],
    );

    Map<String, dynamic> toMap() => {
        "cart_total": cartTotal,
        "cart_content": List<dynamic>.from(cartContent.map((x) => x.toMap())),
        "item_count": itemCount,
    };
}

class CartContent {
    CartContent({
        this.rowId,
        this.id,
        this.name,
        this.qty,
        this.price,
        this.weight,
        this.options,
        this.discount,
        this.tax,
        this.subtotal,
    });

    final String rowId;
    final int id;
    final String name;
    final String qty;
    final int price;
    final int weight;
    final Options options;
    final int discount;
    final int tax;
    final int subtotal;

    factory CartContent.fromJson(String str) => CartContent.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory CartContent.fromMap(Map<String, dynamic> json) => CartContent(
        rowId: json["rowId"],
        id: json["id"],
        name: json["name"],
        qty: json["qty"],
        price: json["price"],
        weight: json["weight"],
        options: Options.fromMap(json["options"]),
        discount: json["discount"],
        tax: json["tax"],
        subtotal: json["subtotal"],
    );

    Map<String, dynamic> toMap() => {
        "rowId": rowId,
        "id": id,
        "name": name,
        "qty": qty,
        "price": price,
        "weight": weight,
        "options": options.toMap(),
        "discount": discount,
        "tax": tax,
        "subtotal": subtotal,
    };
}

class Options {
    Options({
        this.attributeId,
        this.variantId,
        this.image,
    });

    final dynamic attributeId;
    final String variantId;
    final List<Image> image;

    factory Options.fromJson(String str) => Options.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory Options.fromMap(Map<String, dynamic> json) => Options(
        attributeId: json["attribute_id"],
        variantId: json["variant_id"],
        image: List<Image>.from(json["image"].map((x) => Image.fromMap(x))),
    );

    Map<String, dynamic> toMap() => {
        "attribute_id": attributeId,
        "variant_id": variantId,
        "image": List<dynamic>.from(image.map((x) => x.toMap())),
    };
}

class Image {
    Image({
        this.id,
        this.productId,
        this.productImage,
        this.createdAt,
        this.prefixUrl,
        this.updatedAt,
    });

    final int id;
    final int productId;
    final String productImage;
    final DateTime createdAt;
    final String prefixUrl;
    final DateTime updatedAt;

    factory Image.fromJson(String str) => Image.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory Image.fromMap(Map<String, dynamic> json) => Image(
        id: json["id"],
        productId: json["product_id"],
        productImage: json["product_image"],
        createdAt: DateTime.parse(json["created_at"]),
        prefixUrl: json["prefix_url"],
        updatedAt: DateTime.parse(json["updated_at"]),
    );

    Map<String, dynamic> toMap() => {
        "id": id,
        "product_id": productId,
        "product_image": productImage,
        "created_at": createdAt.toIso8601String(),
        "prefix_url": prefixUrl,
        "updated_at": updatedAt.toIso8601String(),
    };
}

</code>```

Title: How to make data model of this api?

Body:
I want to make a data model for my cartList api. if you hit following api in your browser 5 product will be added to your cart.

https://www.moharaj.com.bd/_public/addToCart?quantity=5&slug=cotton-fleece-hoodie-for-men-tekka-8486&variant_id=$variant_id=24469

you can check your cart list through this api:

https://www.moharaj.com.bd/_public/cartToContent

But my problem is when I try to make a model of this cartToContent that means cart list api there always generate a unique row Id or token which I can't store. can anyone has any idea how to make a data model of this api?? I have made a data model. I have given below:

// To parse this JSON data, do
//
//     final cartToContentModel = cartToContentModelFromJson(jsonString);

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

CartToContentModel cartToContentModelFromJson(String str) => CartToContentModel.fromJson(json.decode(str));

String cartToContentModelToJson(CartToContentModel data) => json.encode(data.toJson());

class CartToContentModel {
    CartToContentModel({
        required this.cartTotal,
        required this.cartContent,
        required this.itemCount,
    });

    String cartTotal;
    CartContent cartContent;
    int itemCount;

    factory CartToContentModel.fromJson(Map<String, dynamic> json) => CartToContentModel(
        cartTotal: json["cart_total"],
        cartContent: CartContent.fromJson(json["cart_content"]),
        itemCount: json["item_count"],
    );

    Map<String, dynamic> toJson() => {
        "cart_total": cartTotal,
        "cart_content": cartContent.toJson(),
        "item_count": itemCount,
    };
}

class CartContent {
    CartContent({
        required this.c827Cdf7Ba8F3127F293690569Aff167,
    });

    C827Cdf7Ba8F3127F293690569Aff167 c827Cdf7Ba8F3127F293690569Aff167;

    factory CartContent.fromJson(Map<String, dynamic> json) => CartContent(
        c827Cdf7Ba8F3127F293690569Aff167: C827Cdf7Ba8F3127F293690569Aff167.fromJson(json["c827cdf7ba8f3127f293690569aff167"]),
    );

    Map<String, dynamic> toJson() => {
        "c827cdf7ba8f3127f293690569aff167": c827Cdf7Ba8F3127F293690569Aff167.toJson(),
    };
}

class C827Cdf7Ba8F3127F293690569Aff167 {
    C827Cdf7Ba8F3127F293690569Aff167({
        required this.rowId,
        required this.id,
        required this.name,
        required this.qty,
        required this.price,
        required this.weight,
        required this.options,
        required this.discount,
        required this.tax,
        required this.subtotal,
    });

    String rowId;
    int id;
    String name;
    String qty;
    int price;
    int weight;
    Options options;
    int discount;
    int tax;
    int subtotal;

    factory C827Cdf7Ba8F3127F293690569Aff167.fromJson(Map<String, dynamic> json) => C827Cdf7Ba8F3127F293690569Aff167(
        rowId: json["rowId"],
        id: json["id"],
        name: json["name"],
        qty: json["qty"],
        price: json["price"],
        weight: json["weight"],
        options: Options.fromJson(json["options"]),
        discount: json["discount"],
        tax: json["tax"],
        subtotal: json["subtotal"],
    );

    Map<String, dynamic> toJson() => {
        "rowId": rowId,
        "id": id,
        "name": name,
        "qty": qty,
        "price": price,
        "weight": weight,
        "options": options.toJson(),
        "discount": discount,
        "tax": tax,
        "subtotal": subtotal,
    };
}

class Options {
    Options({
        required this.attributeId,
        required this.variantId,
        required this.image,
    });

    dynamic attributeId;
    String variantId;
    List<Image> image;

    factory Options.fromJson(Map<String, dynamic> json) => Options(
        attributeId: json["attribute_id"],
        variantId: json["variant_id"],
        image: List<Image>.from(json["image"].map((x) => Image.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "attribute_id": attributeId,
        "variant_id": variantId,
        "image": List<dynamic>.from(image.map((x) => x.toJson())),
    };
}

class Image {
    Image({
        required this.id,
        required this.productId,
        required this.productImage,
        required this.createdAt,
        required this.prefixUrl,
        required this.updatedAt,
    });

    int id;
    int productId;
    String productImage;
    DateTime createdAt;
    String prefixUrl;
    DateTime updatedAt;

    factory Image.fromJson(Map<String, dynamic> json) => Image(
        id: json["id"],
        productId: json["product_id"],
        productImage: json["product_image"],
        createdAt: DateTime.parse(json["created_at"]),
        prefixUrl: json["prefix_url"],
        updatedAt: DateTime.parse(json["updated_at"]),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "product_id": productId,
        "product_image": productImage,
        "created_at": createdAt.toIso8601String(),
        "prefix_url": prefixUrl,
        "updated_at": updatedAt.toIso8601String(),
    };
}

Body:
You can make the map of cartitems values to list of cartitems.

Here's the updated model.

// To parse this JSON data, do
//
//     final cartToContentModel = cartToContentModelFromMap(jsonString);

import 'dart:convert';

class CartToContentModel {
    CartToContentModel({
        this.cartTotal,
        this.cartContent,
        this.itemCount,
    });

    final String cartTotal;
    final List<CartContent> cartContent;
    final int itemCount;

    factory CartToContentModel.fromJson(String str) => CartToContentModel.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory CartToContentModel.fromMap(Map<String, dynamic> json) => CartToContentModel(
        cartTotal: json["cart_total"],
        cartContent: List<CartContent>.from(json["cart_content"].values.map((item) => CartContent.fromMap(item))),
        itemCount: json["item_count"],
    );

    Map<String, dynamic> toMap() => {
        "cart_total": cartTotal,
        "cart_content": List<dynamic>.from(cartContent.map((x) => x.toMap())),
        "item_count": itemCount,
    };
}

class CartContent {
    CartContent({
        this.rowId,
        this.id,
        this.name,
        this.qty,
        this.price,
        this.weight,
        this.options,
        this.discount,
        this.tax,
        this.subtotal,
    });

    final String rowId;
    final int id;
    final String name;
    final String qty;
    final int price;
    final int weight;
    final Options options;
    final int discount;
    final int tax;
    final int subtotal;

    factory CartContent.fromJson(String str) => CartContent.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory CartContent.fromMap(Map<String, dynamic> json) => CartContent(
        rowId: json["rowId"],
        id: json["id"],
        name: json["name"],
        qty: json["qty"],
        price: json["price"],
        weight: json["weight"],
        options: Options.fromMap(json["options"]),
        discount: json["discount"],
        tax: json["tax"],
        subtotal: json["subtotal"],
    );

    Map<String, dynamic> toMap() => {
        "rowId": rowId,
        "id": id,
        "name": name,
        "qty": qty,
        "price": price,
        "weight": weight,
        "options": options.toMap(),
        "discount": discount,
        "tax": tax,
        "subtotal": subtotal,
    };
}

class Options {
    Options({
        this.attributeId,
        this.variantId,
        this.image,
    });

    final dynamic attributeId;
    final String variantId;
    final List<Image> image;

    factory Options.fromJson(String str) => Options.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory Options.fromMap(Map<String, dynamic> json) => Options(
        attributeId: json["attribute_id"],
        variantId: json["variant_id"],
        image: List<Image>.from(json["image"].map((x) => Image.fromMap(x))),
    );

    Map<String, dynamic> toMap() => {
        "attribute_id": attributeId,
        "variant_id": variantId,
        "image": List<dynamic>.from(image.map((x) => x.toMap())),
    };
}

class Image {
    Image({
        this.id,
        this.productId,
        this.productImage,
        this.createdAt,
        this.prefixUrl,
        this.updatedAt,
    });

    final int id;
    final int productId;
    final String productImage;
    final DateTime createdAt;
    final String prefixUrl;
    final DateTime updatedAt;

    factory Image.fromJson(String str) => Image.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory Image.fromMap(Map<String, dynamic> json) => Image(
        id: json["id"],
        productId: json["product_id"],
        productImage: json["product_image"],
        createdAt: DateTime.parse(json["created_at"]),
        prefixUrl: json["prefix_url"],
        updatedAt: DateTime.parse(json["updated_at"]),
    );

    Map<String, dynamic> toMap() => {
        "id": id,
        "product_id": productId,
        "product_image": productImage,
        "created_at": createdAt.toIso8601String(),
        "prefix_url": prefixUrl,
        "updated_at": updatedAt.toIso8601String(),
    };
}


Title: How to compute the mean and standard deviation of columns ignoring NaN values

Body:
I have a dataframe of doubles with some NaN/Null/NA values:

val dfDouble = Seq(
  (1.0, 1.0, 1.0, 3.0),
  (1.0, 2.0, 0.0, 0.0),
  (1.0, 3.0, 1.0, 1.0),
  (1.0, NaN, 0.0, 2.0)).toDF("m1", "m2", "m3", "m4")

I would like to compute the mean, standard deviation, and # of non-null observations for each column, but it seems like the regular aggregate functions in spark returns NaN when there is a NaN value:

dfDouble.select(dfDouble.columns.map(c => mean(col(c))) :_*).show
// +-------+-------+-------+-------+
// |avg(m1)|avg(m2)|avg(m3)|avg(m4)|
// +-------+-------+-------+-------+
// |    1.0|    NaN|    0.5|    1.5|
// +-------+-------+-------+-------+
dfDouble.select(dfDouble.columns.map(c => stddev(col(c))) :_*).show
// +---------------+---------------+------------------+------------------+
// |stddev_samp(m1)|stddev_samp(m2)|   stddev_samp(m3)|   stddev_samp(m4)|
// +---------------+---------------+------------------+------------------+
// |            0.0|            NaN|0.5773502691896257|1.2909944487358056|
// +---------------+---------------+------------------+------------------+

How can I compute the mean, standard deviation, and # of non-null observations EXCLUDING NaN values?

Body:
You can replace the NaN values by null before applying mean and stddev functions:

val df = dfDouble.na.fill(dfDouble.columns.map((_, "null")).toMap)

df.select(df.columns.map(c => mean(col(c))) :_*).show

//+-------+-------+-------+-------+
//|avg(m1)|avg(m2)|avg(m3)|avg(m4)|
//+-------+-------+-------+-------+
//|    1.0|    2.0|    0.5|    1.5|
//+-------+-------+-------+-------+


问:
Please do I interprete this ternary operator?
Please if this function was to be converted to a "normal" if else statement, how would it look like?

```<code>export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));
</code>```

I want to add another condition, but I'm finding it hard to read or digest the current flow.

答:
Without any regards to logics, this is the if else version of the code:

const orderArr = (arr, key) => {
  return (
    arr.sort( (a,b) => {
      if(a[key] > b[key]) {
        return 1
    }
    else if(a[key] === b[key]) {
        if (a[key] > b[key])
        return 1
        else return -1
    } else {
      return -1
    }
    })
  )
}```

Body:
Please if this function was to be converted to a "normal" if else statement, how would it look like?

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));

I want to add another condition, but I'm finding it hard to read or digest the current flow.


问:
Setting the content size of my UIScrollView in viewDidLoad/viewWillAppear has no effect - why?
I'm trying to force the content size of my UIScrollVIew when it's container loads. I'm finding this much more difficult than I'd imagine it would be. I've tried setting the content size in both viewDidLoad and viewWillAppear, like so:

```<code>-(void)viewWillAppear:(BOOL)animated
{
    CGSize newContentSize = CGSizeMake(scrollView.contentSize.width, scrollView.frame.size.height + 80.0);
    [scrollView setContentSize:newContentSize];
}
</code>```

If I place a breakpoint right after I call setContentSize, I can see that the new content size is indeed what I set it to.

However, if I then check the content size at some arbitrary point after viewWillAppear, such as, say, scrollViewDidScroll, the content size has reverted back to the size of the "actual" content in the scroll view, and not the size I tried forcing it to be in viewDidAppear.

Why is this?

答:
I have no idea what is resetting it on you, but I can help you find the answer.

What I usually do in a situation like this is subclass UIScrollView (usually as "XXXUIScrollView"), override setContentSize: (to just call [super setContentSize:size], maybe with an NSLog), and set a breakpoint in the overridden method to see what is setting the value.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to force the content size of my UIScrollVIew when it's container loads. I'm finding this much more difficult than I'd imagine it would be. I've tried setting the content size in both viewDidLoad and viewWillAppear, like so:

-(void)viewWillAppear:(BOOL)animated
{
    CGSize newContentSize = CGSizeMake(scrollView.contentSize.width, scrollView.frame.size.height + 80.0);
    [scrollView setContentSize:newContentSize];
}

If I place a breakpoint right after I call setContentSize, I can see that the new content size is indeed what I set it to.

However, if I then check the content size at some arbitrary point after viewWillAppear, such as, say, scrollViewDidScroll, the content size has reverted back to the size of the "actual" content in the scroll view, and not the size I tried forcing it to be in viewDidAppear.

Why is this?


问:
two beans of same type collide even when given two different names and using @Qaulifier annotation, why?
here is the following code for configuring several datasources in a spring batch project

```<code>@Configuration
@RequiredArgsConstructor
public class DatasourceConfiguration {

    private final Environment env;

    @Bean(name = "batchDataSource")
    @ConfigurationProperties(prefix = "spring.batch-datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "customersDataSource")
    @ConfigurationProperties(prefix = "spring.customers-datasource")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    BatchConfigurer configurer(@Qualifier("batchDataSource") DataSource dataSource) {
        return new DefaultBatchConfigurer(dataSource);
    }
}
</code>```

when loading the app I get the following error:

```<code>Field dataSource in org.springframework.batch.core.configuration.annotation.AbstractBatchConfiguration required a single bean, but 2 were found:
    - batchDataSource: defined by method 'primaryDataSource' in class path resource [com/comp/lr/snapshot/customers/job/config/DatasourceConfiguration.class]
    - customersDataSource: defined by method 'secondaryDataSource' in class path resource [com/comp/lr/snapshot/customers/job/config/DatasourceConfiguration.class]
</code>```

But why is it happening if I'm using @Qaulifier annotation?

答:
If you want this to work create your own class AbstractBatchConfiguration and mark the datasource injection with a @qualifier (for your desired datasource bean)
Also exclude AbstractBatchConfiguration so that it does not get autoconfigured.

The reason is spring batch:

```<code>@Configuration(proxyBeanMethods = false)
@Import(ScopeConfiguration.class)
public abstract class AbstractBatchConfiguration implements ImportAware, InitializingBean {

    @Autowired
    private DataSource dataSource;

    private BatchConfigurer configurer;

    private JobRegistry jobRegistry = new MapJobRegistry();

    private JobBuilderFactory jobBuilderFactory;

    private StepBuilderFactory stepBuilderFactory;
</code>```

class has @Autowired on the Datasource field.
So Spring does not know which one of the 2 you defined to inject.

You could also annotate the batch datasource with @primary but then where ever you don't specify a datasource qualifier the batch datasource will be injected. So if another spring class has @Autowired Datasource you still have a problem.

Body:
here is the following code for configuring several datasources in a spring batch project

@Configuration
@RequiredArgsConstructor
public class DatasourceConfiguration {

    private final Environment env;

    @Bean(name = "batchDataSource")
    @ConfigurationProperties(prefix = "spring.batch-datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "customersDataSource")
    @ConfigurationProperties(prefix = "spring.customers-datasource")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    BatchConfigurer configurer(@Qualifier("batchDataSource") DataSource dataSource) {
        return new DefaultBatchConfigurer(dataSource);
    }
}

when loading the app I get the following error:

Field dataSource in org.springframework.batch.core.configuration.annotation.AbstractBatchConfiguration required a single bean, but 2 were found:
    - batchDataSource: defined by method 'primaryDataSource' in class path resource [com/comp/lr/snapshot/customers/job/config/DatasourceConfiguration.class]
    - customersDataSource: defined by method 'secondaryDataSource' in class path resource [com/comp/lr/snapshot/customers/job/config/DatasourceConfiguration.class]

But why is it happening if I'm using @Qaulifier annotation?

Body:
If you want this to work create your own class AbstractBatchConfiguration and mark the datasource injection with a @qualifier (for your desired datasource bean)
Also exclude AbstractBatchConfiguration so that it does not get autoconfigured.

The reason is spring batch:

@Configuration(proxyBeanMethods = false)
@Import(ScopeConfiguration.class)
public abstract class AbstractBatchConfiguration implements ImportAware, InitializingBean {

    @Autowired
    private DataSource dataSource;

    private BatchConfigurer configurer;

    private JobRegistry jobRegistry = new MapJobRegistry();

    private JobBuilderFactory jobBuilderFactory;

    private StepBuilderFactory stepBuilderFactory;

class has @Autowired on the Datasource field.
So Spring does not know which one of the 2 you defined to inject.

You could also annotate the batch datasource with @primary but then where ever you don't specify a datasource qualifier the batch datasource will be injected. So if another spring class has @Autowired Datasource you still have a problem.


问:
Django JSONField data with integer keys
I want to save a model instance with JSON dict with integer keys, like {2: 3}.

But after saving my dict turns into {"2": 3}. Is there any way to save integer keys into JSON?

```<code>class MyModel(models.Model):
    data = JSONField("data")

record = MyModel.objects.create(
    data={2: 3},
)
record.refresh_from_db()

print(record.data)

# > {"2": 3}
# And I want record.data == {2: 3}
</code>```

Behavior same for from django.contrib.postgres.fields import JSONField and for modern from django.db.models import JSONField

答:
I want to save a model instance with JSON dict with integer keys, like {2: 3}.

That is not possible: the JSON specifications say that keys are always strings. The JSON serializer in Python will convert the keys to their string counterparts (perhaps it was more appropriate to raise an error in that case).

If all keys are integers, you could make a subclass of a JSONField that will automatically cast the keys to ints, for example:

```<code>from django.db.models import JSONField

def outer_json_is_object(value):
    if not isinstance(value, dict):
        raise ValidationError(_('Outer JSON item should be an object'), code='invalid_json_object')

class IntKeyJSONField(JSONField):

    def __init__(self, *args, **kwargs):
        validators = kwargs.setdefault('validators', [])
        validators.append(outer_json_is_object)
        super().__init__(*args, **kwargs)

    def from_db_value(self, value, expression, connection):
        value = super().from_db_value(value, expression, connection)
        if value is not None:
            return { <strong>int(k)</strong>: v for k, v in value.items() }</code>```

then it will cast the outer keys to ints of a JSON object. You can thus then use an IntKeyJSONField, but this thus does not store the keys as integers, since again, that is simply not valid JSON, what we do is we post-process the dictionary when reading from JSON and thus replace the keys with their int counterparts.

Title: Django JSONField data with integer keys

Body:
I want to save a model instance with JSON dict with integer keys, like {2: 3}.

But after saving my dict turns into {"2": 3}. Is there any way to save integer keys into JSON?

class MyModel(models.Model):
    data = JSONField("data")

record = MyModel.objects.create(
    data={2: 3},
)
record.refresh_from_db()

print(record.data)

# > {"2": 3}
# And I want record.data == {2: 3}

Behavior same for from django.contrib.postgres.fields import JSONField and for modern from django.db.models import JSONField

Body:
I want to save a model instance with JSON dict with integer keys, like {2: 3}.

That is not possible: the JSON specifications say that keys are always strings. The JSON serializer in Python will convert the keys to their string counterparts (perhaps it was more appropriate to raise an error in that case).

If all keys are integers, you could make a subclass of a JSONField that will automatically cast the keys to ints, for example:

from django.db.models import JSONField

def outer_json_is_object(value):
    if not isinstance(value, dict):
        raise ValidationError(_('Outer JSON item should be an object'), code='invalid_json_object')

class IntKeyJSONField(JSONField):

    def __init__(self, *args, **kwargs):
        validators = kwargs.setdefault('validators', [])
        validators.append(outer_json_is_object)
        super().__init__(*args, **kwargs)

    def from_db_value(self, value, expression, connection):
        value = super().from_db_value(value, expression, connection)
        if value is not None:
            return { int(k): v for k, v in value.items() }

then it will cast the outer keys to ints of a JSON object. You can thus then use an IntKeyJSONField, but this thus does not store the keys as integers, since again, that is simply not valid JSON, what we do is we post-process the dictionary when reading from JSON and thus replace the keys with their int counterparts.


问:
How to use WHERE in CONCAT in mysql
Here is my scenario as beginner in mysql.

There are 2 tables.

usermeta has 3 columns user_id, meta_key, meta value

users_role has 2 columns uid, rid.

I need to insert rows in wp_usermeta based on users_roles.rid value.

User_id from users_roles (users_role.uid matches wp_usermeta.user_id).

Meta_key is set to dokan_profile_settings.

Meta_value should be a CONCAT of :

textA + meta_value from rows with meta_key dokan_site_name already existing in wp_usermeta + textB.

There is my problem. I can't figure out the right way to achieve the CONCAT properly.

When i run this i get : #1242 - Subquery returns more than 1 row

```<code>INSERT INTO usermeta (
    user_id,
    meta_key,
    meta_value
    )
SELECT
    uid,
    'dokan_profile_settings',
    CONCAT('textA', (SELECT usermeta.meta_value FROM usermeta WHERE usermeta.meta_key LIKE 'dokan_store_name'), 'textB')
AS meta_value
FROM users_roles WHERE rid LIKE '4';
</code>```

If i just run the SELECT part of the CONCAT, as pointed out in Paul's comment :

```<code>SELECT usermeta.meta_value FROM usermeta
WHERE usermeta.meta_key LIKE 'dokan_store_name'
</code>```

I get the intended result, but i can't figure out why the whole query fails.

答:
As the error message states, you can't use a subquery that returns more than one string value in a CONCAT() function.
An easy way to solve this would be to GROUP_CONCAT() the results of your subquery: CONCAT('textA', (SELECT GROUP_CONCAT(usermeta.meta_value) FROM usermeta WHERE usermeta.meta_key LIKE 'dokan_store_name'), 'textB')

Title: How to use WHERE in CONCAT in mysql

Body:
Here is my scenario as beginner in mysql.

There are 2 tables.

usermeta has 3 columns user_id, meta_key, meta value

users_role has 2 columns uid, rid.

I need to insert rows in wp_usermeta based on users_roles.rid value.

User_id from users_roles (users_role.uid matches wp_usermeta.user_id).

Meta_key is set to dokan_profile_settings.

Meta_value should be a CONCAT of :

textA + meta_value from rows with meta_key dokan_site_name already existing in wp_usermeta + textB.

There is my problem. I can't figure out the right way to achieve the CONCAT properly.

When i run this i get : #1242 - Subquery returns more than 1 row

INSERT INTO usermeta (
    user_id,
    meta_key,
    meta_value
    )
SELECT
    uid,
    'dokan_profile_settings',
    CONCAT('textA', (SELECT usermeta.meta_value FROM usermeta WHERE usermeta.meta_key LIKE 'dokan_store_name'), 'textB')
AS meta_value
FROM users_roles WHERE rid LIKE '4';

If i just run the SELECT part of the CONCAT, as pointed out in Paul's comment :

SELECT usermeta.meta_value FROM usermeta
WHERE usermeta.meta_key LIKE 'dokan_store_name'

I get the intended result, but i can't figure out why the whole query fails.


问:
Galleon: Adding ActiveMQ with CLI on Wildfly 23+ not working
Since Wildfly 23 i have the problem that i cant add the activemq configutration with cli anymore.
Executing /subsystem=messaging-activemq/server=:add return always an error stating that the default security domain "other" is missing (which was removed in version 23).

With the line /subsystem=messaging-activemq/server=default:write-attribute(name=elytron-domain, value=myDomain) i could add another security domain but thats not possible if the above command fails.
Is there a way to get this working? Overriding the default?

答:
You have to define an elytron security domain to secure your server (or before WildFly 25 a legacy security domain such as 'other').
With WildFly 26 you can just disable security (cf. https://issues.redhat.com/browse/WFLY-15236 )</p>


问:
Allow CodeBuildAction to update SSM parameter
I'm currently trying to set an SSM Parameter Store value via a CodeBuildAction. My first attempt resulted in a 254 return code, which I'm guessing is because the request was not authorized. I then attempted to attach a managed policy to the role associated with the CodeBuildAction, but the cdk deploy failed with:

```<code>Policy arn:aws:iam::aws:policy/AWSServiceRoleForAmazonSSM does not exist or is not attachable. (Service: AmazonIdentityManagement; Status Code: 404; Error Code: NoSuchEntity; Request ID: 2f65f8db-64a5-4173-ac45-de4c56bffa44; Proxy: nu
ll)
</code>```

Here is the role setup:

this.codeBuildRole = new Role(this, "application-build-project-role", {
  assumedBy: new ServicePrincipal("codebuild.amazonaws.com"),
  managedPolicies: [
    ManagedPolicy.fromAwsManagedPolicyName(
      "AmazonEC2ContainerRegistryPowerUser"
    ),
    ManagedPolicy.fromAwsManagedPolicyName("AWSServiceRoleForAmazonSSM"), // THIS IS THE NEW PART
  ],
});
```

I understand that this means that I'm using the wrong policy, but I'm struggling to find an alternative.

Is there a managed policy that will work here? If not, how would I set up an inline policy to achieve what I'm trying to do?

答:
The idiomatic way to solve this is to use CDK's abstractions to modify the role instead of creating your own.

Here's what it would look like, assuming you want to update a specific parameter. You'd do this for every parameter you have.

```<code>mySsmParameter.grantWrite(myCodeBuildAction.actionProperties.role);
</code>```

Alternatively, you can grant the access to the action's project:

```<code>mySsmParameter.grantWrite(myCodeBuildProject);
</code>```

And that's it, CDK will take care of the needed statements under the hood.

Body:
I'm currently trying to set an SSM Parameter Store value via a CodeBuildAction. My first attempt resulted in a 254 return code, which I'm guessing is because the request was not authorized. I then attempted to attach a managed policy to the role associated with the CodeBuildAction, but the cdk deploy failed with:

Policy arn:aws:iam::aws:policy/AWSServiceRoleForAmazonSSM does not exist or is not attachable. (Service: AmazonIdentityManagement; Status Code: 404; Error Code: NoSuchEntity; Request ID: 2f65f8db-64a5-4173-ac45-de4c56bffa44; Proxy: nu
ll)

Here is the role setup:

this.codeBuildRole = new Role(this, "application-build-project-role", {
  assumedBy: new ServicePrincipal("codebuild.amazonaws.com"),
  managedPolicies: [
    ManagedPolicy.fromAwsManagedPolicyName(
      "AmazonEC2ContainerRegistryPowerUser"
    ),
    ManagedPolicy.fromAwsManagedPolicyName("AWSServiceRoleForAmazonSSM"), // THIS IS THE NEW PART
  ],
});

I understand that this means that I'm using the wrong policy, but I'm struggling to find an alternative.

Is there a managed policy that will work here? If not, how would I set up an inline policy to achieve what I'm trying to do?

Body:
The idiomatic way to solve this is to use CDK's abstractions to modify the role instead of creating your own.

Here's what it would look like, assuming you want to update a specific parameter. You'd do this for every parameter you have.

mySsmParameter.grantWrite(myCodeBuildAction.actionProperties.role);

Alternatively, you can grant the access to the action's project:

mySsmParameter.grantWrite(myCodeBuildProject);

And that's it, CDK will take care of the needed statements under the hood.


问:
Accessing dict keys like an attribute?
I find it more convenient to access dict keys as obj.foo instead of obj['foo'], so I wrote this snippet:

```<code>class AttributeDict(dict):
    def __getattr__(self, attr):
        return self[attr]
    def __setattr__(self, attr, value):
        self[attr] = value
</code>```

However, I assume that there must be some reason that Python doesn't provide this functionality out of the box. What would be the caveats and pitfalls of accessing dict keys in this manner?

答:
After not being satisfied with the existing options for the reasons below I developed MetaDict. It behaves exactly like dict but enables dot notation and IDE autocompletion without the shortcomings and potential namespace conflicts of other solutions. All features and usage examples can be found on GitHub (see link above).

Full disclosure: I am the author of MetaDict.

Shortcomings/limitations I encountered when trying out other solutions:

Addict

No key autocompletion in IDE

Nested key assignment cannot be turned off

Newly assigned dict objects are not converted to support attribute-style key access

Shadows inbuilt type Dict

Prodict

No key autocompletion in IDE without defining a static schema (similar to dataclass)

No recursive conversion of dict objects when embedded in list or other inbuilt iterables

AttrDict

No key autocompletion in IDE

Converts list objects to tuple behind the scenes

Munch

Inbuilt methods like items(), update(), etc. can be overwritten with obj.items = [1, 2, 3]

No recursive conversion of dict objects when embedded in list or other inbuilt iterables

EasyDict

Only strings are valid keys, but dict accepts all hashable objects as keys

Inbuilt methods like items(), update(), etc. can be overwritten with obj.items = [1, 2, 3]

Inbuilt methods don't behave as expected: obj.pop('unknown_key', None) raises an AttributeError

Title: Accessing dict keys like an attribute?

Body:
I find it more convenient to access dict keys as obj.foo instead of obj['foo'], so I wrote this snippet:

class AttributeDict(dict):
    def __getattr__(self, attr):
        return self[attr]
    def __setattr__(self, attr, value):
        self[attr] = value

However, I assume that there must be some reason that Python doesn't provide this functionality out of the box. What would be the caveats and pitfalls of accessing dict keys in this manner?


问:
How to create a dynamic object from JSON that itself contains the structure of that object
There is a nice function in json.net to convert a json into a c# object:

```<code>CMyObject myObject = Newtonsoft.Json.JsonConvert.DeserializeObject<CMyObject>(json);
</code>```

Problem with that is that the structure needs to be known upfront.

Is there a lean way if the structre itself is coming from json itself?

Here an example of the json:

{
  "data": {
    "255622": {
      "2": {
        "value": "Active"
      },
      "3": {
        "value": null
      }
    }
  },

  "schema": {
    "255622": {
      "name": "NameOfStructure",
      "properties": {
        "2": {
          "multi_value": false,
          "name": "Status",
          "type_name": "String"
        },
        "3": {
          "multi_value": false,
          "name": "StatusDate",
          "type_name": "Date"
        }
      }
    }
  }
}
```
<p>This should convert to:</p>
```myObject (type NameOfStructure)
myObject.Status = "Active" (type String - single value)
myObject.StatusDate = null (type Date - single value)
```

Any ideas?

答:
actually I am pretty sure you can do that with the dynamic keyword.

I can't check right now but you should be able to do something like :

```<code>dynamic myObject = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
</code>```

or something along those lines, this is sometimes useful as you can still parse the tree for whatever you need or discover what the types are and then do something with that information, depending on your use case.

I also used another approach in the past with an ExpandoObject instead of dynamic.

It depends what your use case is, but those are the approaches I'd investigate more

Body:
There is a nice function in json.net to convert a json into a c# object:

CMyObject myObject = Newtonsoft.Json.JsonConvert.DeserializeObject<CMyObject>(json);

Problem with that is that the structure needs to be known upfront.

Is there a lean way if the structre itself is coming from json itself?

Here an example of the json:

{
  "data": {
    "255622": {
      "2": {
        "value": "Active"
      },
      "3": {
        "value": null
      }
    }
  },

  "schema": {
    "255622": {
      "name": "NameOfStructure",
      "properties": {
        "2": {
          "multi_value": false,
          "name": "Status",
          "type_name": "String"
        },
        "3": {
          "multi_value": false,
          "name": "StatusDate",
          "type_name": "Date"
        }
      }
    }
  }
}

This should convert to:

myObject (type NameOfStructure)
myObject.Status = "Active" (type String - single value)
myObject.StatusDate = null (type Date - single value)

Any ideas?

Body:
actually I am pretty sure you can do that with the dynamic keyword.

I can't check right now but you should be able to do something like :

dynamic myObject = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);

or something along those lines, this is sometimes useful as you can still parse the tree for whatever you need or discover what the types are and then do something with that information, depending on your use case.

I also used another approach in the past with an ExpandoObject instead of dynamic.

It depends what your use case is, but those are the approaches I'd investigate more


问:
loader is not working when I am clicking submit button
loader is not working when I am clicking submit button  on Register page. I hava added Thread.sleep(3000; in Register.java page

`
$(document).ready(function(){
console.log("Page is ready...... ") ;
$("#myform").on('submit',function(event){
event.preventDefault();
var f = $(this).serialize();
console.log(f);
$(".loader").show();
$(".form").hide();

```<code>                $.ajax({
                   url:"Register",
                   data:f,
                   type:'POST',
                   success:function(data,textStatus,jqXHR){
                       console.log(data);
                       console.log("Success......");
                       $(".loader").hide();
                       $(".form").show();
                       if(data.trim()==="Done"){
                           $("#msg").html("Succesfully Registered !!!");
                           $("#msg").addClass("green-text");
                       }else{
                           $("#msg").html("Something went wrong !!!");
                           $("#msg").addClass("red-text");
                       }

                   },
                   error:function(jqXHR,textStatus,errorThrown){
                       console.log(data);
                       console.log("error");
                       $(".loader").hide();
                       $(".form").show();
                       $("#msg").html("Something went wrong !!!");
                       $("#msg").addClass("red-text");
                   }
               });
            });
            });`
</code>```
```<code>package com.user;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;

public class Register extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            /*out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Register</title>");
            out.println("</head>");
            out.println("<body>");*/
            //Getting all the details from incoming from request
            String name=request.getParameter("user_name");
            String email=request.getParameter("user_email");
            String password=request.getParameter("user_password");
            //out.println(name);
            //out.println(email);
            //out.println(password);
            //connection
             try{
                 Thread.sleep(3000);
                 Class.forName("com.mysql.cj.jdbc.Driver");
                 Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/youtube1","root","Vandana");

                 //query
                 String q="insert into user(name,email,password) value(?, ?, ?)";
                 PreparedStatement pstmpt= con.prepareStatement(q);
                 pstmpt.setString(1, name);
                 pstmpt.setString(2, password);
                 pstmpt.setString(3, email);

                 pstmpt.executeUpdate();

                 out.println("Done");
             }

             catch (Exception e){
                e.printStackTrace() ;
                out.println("Error");
             }

            //......
            //out.println("</body>");
            //out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
</code>```
```<code>    Document   : signup
    Created on : 01-Feb-2022, 2:13:08 PM
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <!-- Compiled and minified CSS -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

        <!-- Compiled and minified JavaScript -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

    </head>
    <body style="background-image: url(images/bg.jpg); background-size: cover;background-attachment: fixed;">
        <div class="container">
            <div class="row">
                <div class="col m6 offset-m3">

                    <div class="card">
                         <div class="card-content">
                             <div class="form center-align">
                                 <h3 style="margin-top: 10px;"class="center-align">Register Here !!</h3>
                                 <h5 id="msg" class="center-align"</h5>
                                <div class="form">
                                <!-- creating form -->
                                <form action="Register" method="post" id="myform">
                                    <input type="text" name="user_name" placeholder="Enter user_name"\>
                                    <input type="password" name="user_password" placeholder="Enter password"\>
                                    <input type="email" name="user_email" placeholder="Enter your email"\>

                                    <button type="submit" name="btn" style="background-color:#b3e5fc;">Submit</button>

                                </form>
                                <div class="loader center-align" style="margin-top: 10px; display: none;" >
                                        <div class="preloader-wrapper big active">
                                            <div class="spinner-layer spinner-blue-only">
                                              <div class="circle-clipper left">
                                                <div class="circle"></div>
                                              </div><div class="gap-patch">
                                                <div class="circle"></div>
                                              </div><div class="circle-clipper right">
                                                <div class="circle"></div>
                                              </div>
                                            </div>
                                          </div>

                                    <h5>Please Wait....</h5>
                                </div>

                            </div>
                    </div>
                </div>
            </div>
        </div>
      </div>
    </div>
        <script
            src="https://code.jquery.com/jquery-3.6.0.min.js"
            integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
            crossorigin="anonymous">

        </script>
        <script>
                $(document).ready(function(){
                console.log("Page is ready...... ") ;
                $("#myform").on('submit',function(event){
                event.preventDefault();
                var f = $(this).serialize();
                console.log(f);
                $(".loader").show();
                $(".form").hide();

                    $.ajax({
                       url:"Register",
                       data:f,
                       type:'POST',
                       success:function(data,textStatus,jqXHR){
                           console.log(data);
                           console.log("Success......");
                           $(".loader").hide();
                           $(".form").show();
                           if(data.trim()==="Done"){
                               $("#msg").html("Succesfully Registered !!!");
                               $("#msg").addClass("green-text");
                           }else{
                               $("#msg").html("Something went wrong !!!");
                               $("#msg").addClass("red-text");
                           }

                       },
                       error:function(jqXHR,textStatus,errorThrown){
                           console.log(data);
                           console.log("error");
                           $(".loader").hide();
                           $(".form").show();
                           $("#msg").html("Something went wrong !!!");
                           $("#msg").addClass("red-text");
                       }
                   });
                });
                });

        </script>
    </body>
</html>```

```

答:
The problem is in the HTML.

You need to move the loader outside this div to make it work.

```

Otherwise, when you call $(".form").hide();, everything inside this div will be hidden, including the loader.

Body:
loader is not working when I am clicking submit button  on Register page. I hava added Thread.sleep(3000; in Register.java page

`
$(document).ready(function(){
console.log("Page is ready...... ") ;
$("#myform").on('submit',function(event){
event.preventDefault();
var f = $(this).serialize();
console.log(f);
$(".loader").show();
$(".form").hide();

                $.ajax({
                   url:"Register",
                   data:f,
                   type:'POST',
                   success:function(data,textStatus,jqXHR){
                       console.log(data);
                       console.log("Success......");
                       $(".loader").hide();
                       $(".form").show();
                       if(data.trim()==="Done"){
                           $("#msg").html("Succesfully Registered !!!");
                           $("#msg").addClass("green-text");
                       }else{
                           $("#msg").html("Something went wrong !!!");
                           $("#msg").addClass("red-text");
                       }

                   },
                   error:function(jqXHR,textStatus,errorThrown){
                       console.log(data);
                       console.log("error");
                       $(".loader").hide();
                       $(".form").show();
                       $("#msg").html("Something went wrong !!!");
                       $("#msg").addClass("red-text");
                   }
               });
            });
            });`

package com.user;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;

public class Register extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            /*out.println("<!DOCTYPE html>");
            out.println("");
            out.println("");
            out.println("<title>Servlet Register</title>");
            out.println("");
            out.println("");*/
            //Getting all the details from incoming from request
            String name=request.getParameter("user_name");
            String email=request.getParameter("user_email");
            String password=request.getParameter("user_password");
            //out.println(name);
            //out.println(email);
            //out.println(password);
            //connection
             try{
                 Thread.sleep(3000);
                 Class.forName("com.mysql.cj.jdbc.Driver");
                 Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/youtube1","root","Vandana");

                 //query
                 String q="insert into user(name,email,password) value(?, ?, ?)";
                 PreparedStatement pstmpt= con.prepareStatement(q);
                 pstmpt.setString(1, name);
                 pstmpt.setString(2, password);
                 pstmpt.setString(3, email);

                 pstmpt.executeUpdate();

                 out.println("Done");
             }

             catch (Exception e){
                e.printStackTrace() ;
                out.println("Error");
             }

            //......
            //out.println("");
            //out.println("");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

    Document   : signup
    Created on : 01-Feb-2022, 2:13:08 PM
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

Register Here !!

                                 <h5 id="msg" class="center-align"

                                <form action="Register" method="post" id="myform">
                                    <input type="text" name="user_name" placeholder="Enter user_name"\>
                                    <input type="password" name="user_password" placeholder="Enter password"\>
                                    <input type="email" name="user_email" placeholder="Enter your email"\>

                                    <button type="submit" name="btn" style="background-color:#b3e5fc;">Submit</button>

                                </form>

Please Wait....

```

Body:
The problem is in the HTML.

You need to move the loader outside this div to make it work.

<div class="form center-align">

Otherwise, when you call $(".form").hide();, everything inside this div will be hidden, including the loader.


问:
How to reset or restart the ARCore session?
I need to reset/restart the ARCore session. In ARKit, I just have to create a new configuration and execute the RunWithConfigAndOptions method, but I can't find any information on how to do this in ARCore. The following is the code I use in Unity for ARKit:

```<code>ARKitWorldTrackingSessionConfiguration config = new ARKitWorldTrackingSessionConfiguration();
config.planeDetection = UnityARPlaneDetection.Horizontal;
config.alignment = UnityARAlignment.UnityARAlignmentGravity;
config.enableLightEstimation = true;

UnityARSessionNativeInterface.GetARSessionNativeInterface().RunWithConfigAndOptions(config,
                                                                                UnityARSessionRunOption.ARSessionRunOptionRemoveExistingAnchors |
                                                                                UnityARSessionRunOption.ARSessionRunOptionResetTracking);
</code>```

I'm working in Unity, but I guess any information will be useful.

Thanks

答:
In my case, I inherited a Unity3D ARCore project a bit weirdly setup.

The easiest solution in my case, in order to correctly reset the session (otherwise it would not restart tracking on scene load) was to first find the ARCore Device gameobject and uncheck the script enabled in the Unity3D editor.

Once that was done, I just needed to find the ARCoreSession in the Awake() function (but you may need it to do that in Start(), depending on how your project is setup if you have other pre-conditions) and then simply enable the script

```<code>GoogleARCore.ARCoreSession g = GameObject.Find("ARCore Device").GetComponent<GoogleARCore.ARCoreSession>();
g.enabled = true;
</code>```

Body:
I need to reset/restart the ARCore session. In ARKit, I just have to create a new configuration and execute the RunWithConfigAndOptions method, but I can't find any information on how to do this in ARCore. The following is the code I use in Unity for ARKit:

ARKitWorldTrackingSessionConfiguration config = new ARKitWorldTrackingSessionConfiguration();
config.planeDetection = UnityARPlaneDetection.Horizontal;
config.alignment = UnityARAlignment.UnityARAlignmentGravity;
config.enableLightEstimation = true;

UnityARSessionNativeInterface.GetARSessionNativeInterface().RunWithConfigAndOptions(config,
                                                                                UnityARSessionRunOption.ARSessionRunOptionRemoveExistingAnchors |
                                                                                UnityARSessionRunOption.ARSessionRunOptionResetTracking);

I'm working in Unity, but I guess any information will be useful.

Thanks

Body:
In my case, I inherited a Unity3D ARCore project a bit weirdly setup.

The easiest solution in my case, in order to correctly reset the session (otherwise it would not restart tracking on scene load) was to first find the ARCore Device gameobject and uncheck the script enabled in the Unity3D editor.

Once that was done, I just needed to find the ARCoreSession in the Awake() function (but you may need it to do that in Start(), depending on how your project is setup if you have other pre-conditions) and then simply enable the script

GoogleARCore.ARCoreSession g = GameObject.Find("ARCore Device").GetComponent<GoogleARCore.ARCoreSession>();
g.enabled = true;


问:
Escaping quotes in Javascript variable from Classic ASP
How can I escape quotes using a Classic ASP variable in javascript/jQuery? The ASP variable is taken from a DB. I'm using:

```<code>var goala = "<%=(goal_a)%>";
</code>```

But obviously that appears as

```<code>var goala = "<p>testing "quotation" marks</p>";
</code>```

when the page loads, which breaks the function with unexpected identifier.

edit: I'm using using jQuery not "how can I achieve this using jQuery" sorry wasn't clear.

Any ideas? Thanks

答:
It has been a while I dealt with this stuff.
You have to encode your data to use it inside an attribute.
Try this.</p>
```<code><%=server.HTMLEncode(goal_a)%>
</code>```

Body:
How can I escape quotes using a Classic ASP variable in javascript/jQuery? The ASP variable is taken from a DB. I'm using:

var goala = "<%=(goal_a)%>";

But obviously that appears as

var goala = "
testing "quotation" marks
";

when the page loads, which breaks the function with unexpected identifier.

edit: I'm using using jQuery not "how can I achieve this using jQuery" sorry wasn't clear.

Any ideas? Thanks

Body:
It has been a while I dealt with this stuff.
You have to encode your data to use it inside an attribute.
Try this.

<%=server.HTMLEncode(goal_a)%>


问:
How to return value from Action()?
In regards to the answer for this question Passing DataContext into Action(), how do I return a value from action(db)?

```<code>SimpleUsing.DoUsing(db => {
// do whatever with db
});
</code>```

Should be more like:

```<code>MyType myType = SimpleUsing.DoUsing<MyType>(db => {
// do whatever with db.  query buit using db returns MyType.
});
</code>```

答:
In addition to ssls answer: For a software we call a lot of "micro methods" to query this and that from the local machine. Sometimes exceptions appear (file / folder not existing, etc). In order to not repeat our self over and over with try/catch blocks, we used ssls approach with return values:

```<code>private T ExecuteAndCatch<T>(Func<T> action, T defaultReturn)
{
    try
    {
        return action();
    }
    catch (Exception ex)
    {
        Log.e("Exception during ExecuteAndCatch", ex);
        return defaultReturn;
    }
}
</code>```

Example of mentioned micro-methods:

```<code>private Boolean CheckKasperskyInstalled() => System.IO.File.Exists(Environment.ExpandEnvironmentVariables(@"%pf_x86%\Kaspersky Lab\Kaspersky Endpoint Security for Windows\avp.exe"));
private Boolean CheckKasperskyRunning() => System.Diagnostics.Process.GetProcessesByName("avp").Length > 0;
</code>```

And when using, we no longer have to care if these Methods might throw an exception for whatever reason:

```<code>cci = new ComputerComplianceInfo();
cci.KasperskyInstalled = ExecuteAndCatch(() => CheckKasperskyInstalled(), false);
cci.KasperskyRunning = ExecuteAndCatch(() => CheckKasperskyRunning(), false);
</code>```

Title: How to return value from Action()?

Body:
In regards to the answer for this question Passing DataContext into Action(), how do I return a value from action(db)?

SimpleUsing.DoUsing(db => {
// do whatever with db
});

Should be more like:

MyType myType = SimpleUsing.DoUsing<MyType>(db => {
// do whatever with db.  query buit using db returns MyType.
});

Body:
In addition to ssls answer: For a software we call a lot of "micro methods" to query this and that from the local machine. Sometimes exceptions appear (file / folder not existing, etc). In order to not repeat our self over and over with try/catch blocks, we used ssls approach with return values:

private T ExecuteAndCatch<T>(Func<T> action, T defaultReturn)
{
    try
    {
        return action();
    }
    catch (Exception ex)
    {
        Log.e("Exception during ExecuteAndCatch", ex);
        return defaultReturn;
    }
}

Example of mentioned micro-methods:

private Boolean CheckKasperskyInstalled() => System.IO.File.Exists(Environment.ExpandEnvironmentVariables(@"%pf_x86%\Kaspersky Lab\Kaspersky Endpoint Security for Windows\avp.exe"));
private Boolean CheckKasperskyRunning() => System.Diagnostics.Process.GetProcessesByName("avp").Length > 0;

And when using, we no longer have to care if these Methods might throw an exception for whatever reason:

cci = new ComputerComplianceInfo();
cci.KasperskyInstalled = ExecuteAndCatch(() => CheckKasperskyInstalled(), false);
cci.KasperskyRunning = ExecuteAndCatch(() => CheckKasperskyRunning(), false);


问:
How to make the program ask the user for input until they give a valid response?
could you please help me to make this program to get a correct number? The program should check the input type, it should be int. Also, the program should check that the value is from 1 to 10. If these conditions are true, the value should be assigned to correctNumber. So far I came up to this piece of code but I have difficulties in making it work properly.</p>
```<code>System.out.println("Enter a number from 1 to 10:");
    Scanner scanner = new Scanner(System.in);
    while (!scanner.hasNextInt() || !isCorrectNumber(scanner.nextInt())) {
                System.out.println("Incorrect input!");
                scanner.next();
            }
            int correctNumber = scanner.nextInt();

        }
    private static boolean isCorrectNumber(int n) {
        return size >= 1 && size <= 10;
    }
</code>```

答:
You are asking for input 2 times in your while condition
Use a variable to save the input and then work with that

```<code>public static void main(String[] args) throws IOException {

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

    String x = input.readLine();
    while (!isInt(x)) {
        x = input.readLine();
    }
    System.out.println(x);
}
</code>```

I ask for input, i get a String, now i have to check if this string can be a number. For that i've created a boolean function isInt(String)
Takes the String and returns if it can be a number.

```<code>public static boolean isInt(String str) {//function that checks if String can be parsed into an integer
    try {
        Integer.parseInt(str);
        return true;
    }catch (NumberFormatException e) {
        return false;
    }
}
</code>```

I hope i've been helpfull

Body:
could you please help me to make this program to get a correct number? The program should check the input type, it should be int. Also, the program should check that the value is from 1 to 10. If these conditions are true, the value should be assigned to correctNumber. So far I came up to this piece of code but I have difficulties in making it work properly.

System.out.println("Enter a number from 1 to 10:");
    Scanner scanner = new Scanner(System.in);
    while (!scanner.hasNextInt() || !isCorrectNumber(scanner.nextInt())) {
                System.out.println("Incorrect input!");
                scanner.next();
            }
            int correctNumber = scanner.nextInt();

        }
    private static boolean isCorrectNumber(int n) {
        return size >= 1 && size <= 10;
    }

Body:
You are asking for input 2 times in your while condition
Use a variable to save the input and then work with that

public static void main(String[] args) throws IOException {

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

    String x = input.readLine();
    while (!isInt(x)) {
        x = input.readLine();
    }
    System.out.println(x);
}

I ask for input, i get a String, now i have to check if this string can be a number. For that i've created a boolean function isInt(String)
Takes the String and returns if it can be a number.

public static boolean isInt(String str) {//function that checks if String can be parsed into an integer
    try {
        Integer.parseInt(str);
        return true;
    }catch (NumberFormatException e) {
        return false;
    }
}

I hope i've been helpfull


问:
I need to fetch the records that are between these DATE and DATE_TIME Column
I have a AUDIT Table in Oracle with DATE_AND_TIME as DATE and DATE_AND_TIME_24HOUR_FORMAT as Varchar2. I need to fetch records that are between two Date and DATE_AND_TIME_24HOUR_FORMAT. for example

```<code>Record  Date_AND_TIME   DATE_AND_TIME_24HOUR_FORMAT
1   02-Feb-2022 13:35:24
2   02-Feb-2022 13:35:56
3   07-Feb-2022 13:35:32
4   07-Feb-2022 13:35:23
5   07-Feb-2022 13:35:02
6   07-Feb-2022 13:36:02
</code>```

I need the Query which will fetch me records 3,4,5 if I execute it for 03-FEB-2022 13:35:00 to 07-FEB-2022 13:35:00 and record 6 if I execute the query for 07-FEB-2022 13:36:00 to 12 07-FEB-2022 13:37:00.

答:
Do not store your time values in a VARCHAR2 column. In Oracle, a DATE data type ALWAYS has the components year, month, day, hour, minute and second so you can store the time in the DATE column.

CREATE TABLE table_name (
  Record        NUMBER PRIMARY KEY,
  Date_AND_TIME DATE
);
```
<p>Then:</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO table_name (record, date_and_time)
SELECT 1, TO_DATE('02-Feb-2022 13:35:24', 'DD-MON-YYYY HH24:MI:SS') FROM DUAL UNION ALL
SELECT 2, TO_DATE('02-Feb-2022 13:35:56', 'DD-MON-YYYY HH24:MI:SS') FROM DUAL UNION ALL
SELECT 3, TO_DATE('07-Feb-2022 13:35:32', 'DD-MON-YYYY HH24:MI:SS') FROM DUAL UNION ALL
SELECT 4, TO_DATE('07-Feb-2022 13:35:23', 'DD-MON-YYYY HH24:MI:SS') FROM DUAL UNION ALL
SELECT 5, TO_DATE('07-Feb-2022 13:35:02', 'DD-MON-YYYY HH24:MI:SS') FROM DUAL UNION ALL
SELECT 6, TO_DATE('07-Feb-2022 13:36:02', 'DD-MON-YYYY HH24:MI:SS') FROM DUAL;
</code>```

Then your query is simply:

SELECT *
FROM   table_name
WHERE  date_and_time BETWEEN TO_DATE('03-FEB-2022 13:35:00', 'DD-MON-YYYY HH24:MI:SS')
                     AND     TO_DATE('07-FEB-2022 13:36:00', 'DD-MON-YYYY HH24:MI:SS')
```
<p>or</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM   table_name
WHERE  date_and_time BETWEEN TO_DATE('07-FEB-2022 13:36:00', 'DD-MON-YYYY HH24:MI:SS')
                     AND     TO_DATE('07-FEB-2022 13:37:00', 'DD-MON-YYYY HH24:MI:SS')
</code>```

db<>fiddle here

Body:
I have a AUDIT Table in Oracle with DATE_AND_TIME as DATE and DATE_AND_TIME_24HOUR_FORMAT as Varchar2. I need to fetch records that are between two Date and DATE_AND_TIME_24HOUR_FORMAT. for example

Record  Date_AND_TIME   DATE_AND_TIME_24HOUR_FORMAT
1   02-Feb-2022 13:35:24
2   02-Feb-2022 13:35:56
3   07-Feb-2022 13:35:32
4   07-Feb-2022 13:35:23
5   07-Feb-2022 13:35:02
6   07-Feb-2022 13:36:02

I need the Query which will fetch me records 3,4,5 if I execute it for 03-FEB-2022 13:35:00 to 07-FEB-2022 13:35:00 and record 6 if I execute the query for 07-FEB-2022 13:36:00 to 12 07-FEB-2022 13:37:00.

Body:
Do not store your time values in a VARCHAR2 column. In Oracle, a DATE data type ALWAYS has the components year, month, day, hour, minute and second so you can store the time in the DATE column.

CREATE TABLE table_name (
  Record        NUMBER PRIMARY KEY,
  Date_AND_TIME DATE
);

Then:

INSERT INTO table_name (record, date_and_time)
SELECT 1, TO_DATE('02-Feb-2022 13:35:24', 'DD-MON-YYYY HH24:MI:SS') FROM DUAL UNION ALL
SELECT 2, TO_DATE('02-Feb-2022 13:35:56', 'DD-MON-YYYY HH24:MI:SS') FROM DUAL UNION ALL
SELECT 3, TO_DATE('07-Feb-2022 13:35:32', 'DD-MON-YYYY HH24:MI:SS') FROM DUAL UNION ALL
SELECT 4, TO_DATE('07-Feb-2022 13:35:23', 'DD-MON-YYYY HH24:MI:SS') FROM DUAL UNION ALL
SELECT 5, TO_DATE('07-Feb-2022 13:35:02', 'DD-MON-YYYY HH24:MI:SS') FROM DUAL UNION ALL
SELECT 6, TO_DATE('07-Feb-2022 13:36:02', 'DD-MON-YYYY HH24:MI:SS') FROM DUAL;

Then your query is simply:

SELECT *
FROM   table_name
WHERE  date_and_time BETWEEN TO_DATE('03-FEB-2022 13:35:00', 'DD-MON-YYYY HH24:MI:SS')
                     AND     TO_DATE('07-FEB-2022 13:36:00', 'DD-MON-YYYY HH24:MI:SS')

or

SELECT *
FROM   table_name
WHERE  date_and_time BETWEEN TO_DATE('07-FEB-2022 13:36:00', 'DD-MON-YYYY HH24:MI:SS')
                     AND     TO_DATE('07-FEB-2022 13:37:00', 'DD-MON-YYYY HH24:MI:SS')

db<>fiddle here


问:
React-Native: cannot update a component while rendering a different component
I've got this simple component Login:

```<code>function Login() {
  const [isFormValidState, setIsFormValidState] = React.useState(false);
  const [credentialState, setCredentialState] = React.useState();

  function getFormErrors(errors: any, dirty: boolean) {
    setIsFormValidState(!Object.keys(errors).length && dirty);
  }

  function getFormValues(values: any) {
    setCredentialState(values);
  }

  function doAction() {
    //credentialState rest call...
  }

  return (
    <View>
      <Text>Login</Text>
      <UserCredentialForm getFormValues={getFormValues} getFormErrors={getFormErrors}/>
      <Button title='Entra' disabled={!isFormValidState} onPress={doAction}/>
    </View>
  );
}
</code>```

Which calls UserCredentialForm:

```<code>export default function UserCredentialForm({ getFormValues, getFormErrors }) {
[...]
  return (
    <Formik innerRef={formRef} validationSchema={formSchema} initialValues={state.form} onSubmit={() => { }}>
      {({ handleChange, values, touched, errors, dirty }) => {
        getFormValues(values);
        getFormErrors(errors, dirty);
        return <React.Fragment>
          // <TextInput/>....
        </React.Fragment>
      }}
    </Formik>
  );

[...]
}
</code>```

While navigating in my app I've got this error:

react native cannot update a component Login while rendering a
different component Formik.

Then it points me to the error in the setCredentialState inside getFormValues handler in Login component.
I've resolved this using a ref instead of a state, but the problem itself is unsolved to me.

What if I need to update my parent component view after a child event?

答:
I think you got an unlimited loop of rendering,

you setState by getFormValues and the Login component re-render make UserCredentialForm re-render too, so it call getFormValues again and again

You can call getFormValues(values) in a useEffect hook after values of formik update

Body:
I've got this simple component Login:

function Login() {
  const [isFormValidState, setIsFormValidState] = React.useState(false);
  const [credentialState, setCredentialState] = React.useState();

  function getFormErrors(errors: any, dirty: boolean) {
    setIsFormValidState(!Object.keys(errors).length && dirty);
  }

  function getFormValues(values: any) {
    setCredentialState(values);
  }

  function doAction() {
    //credentialState rest call...
  }

  return (
    <View>
      <Text>Login</Text>
      <UserCredentialForm getFormValues={getFormValues} getFormErrors={getFormErrors}/>
      <Button title='Entra' disabled={!isFormValidState} onPress={doAction}/>
    </View>
  );
}

Which calls UserCredentialForm:

export default function UserCredentialForm({ getFormValues, getFormErrors }) {
[...]
  return (
    <Formik innerRef={formRef} validationSchema={formSchema} initialValues={state.form} onSubmit={() => { }}>
      {({ handleChange, values, touched, errors, dirty }) => {
        getFormValues(values);
        getFormErrors(errors, dirty);
        return <React.Fragment>
          // <TextInput/>....
        </React.Fragment>
      }}
    </Formik>
  );

[...]
}

While navigating in my app I've got this error:

react native cannot update a component Login while rendering a
different component Formik.

Then it points me to the error in the setCredentialState inside getFormValues handler in Login component.
I've resolved this using a ref instead of a state, but the problem itself is unsolved to me.

What if I need to update my parent component view after a child event?


问:
Define AWS credentials in nodejs deployment on EC2
I need guidance regarding using AWS-SDK credentials in production nodejs app.

What is the possible way of doing this? I researched about it that always use shared credentials files for aws credentials using that link. "https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/loading-node-credentials-shared.html"

So I'm confused about the way. Do I need to create that file in that Linux path specified in that link in VM of EC2?

I made a new IAM role for S3 and allocate it to a specific EC2 instance but through code how can I be able to access S3 services. I deployed my app and it's still giving me access denied error on accessing S3 service.

Do I still need to include credentials file as discussed in like given above? And Do I still need to initialize S3?

```<code>const s3 = new aws.S3({
  accessKeyId,
  secretKey,
  bucketRegion,
});
</code>```

Please guide me that how can I deploy nodejs app without affecting AWS services.

答:
Following the AWS Well Architected Framework the best solution would be to assign a role with your required permissions to the EC2 instance that you are going to use.

You should strive from adding credentials to the application directly as they are not needed in most of the cases.

Please take a look at IAM roles for Amazon EC2 as how does AWS guides to achieving that.

Body:
I need guidance regarding using AWS-SDK credentials in production nodejs app.

What is the possible way of doing this? I researched about it that always use shared credentials files for aws credentials using that link. "https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/loading-node-credentials-shared.html"

So I'm confused about the way. Do I need to create that file in that Linux path specified in that link in VM of EC2?

I made a new IAM role for S3 and allocate it to a specific EC2 instance but through code how can I be able to access S3 services. I deployed my app and it's still giving me access denied error on accessing S3 service.

Do I still need to include credentials file as discussed in like given above? And Do I still need to initialize S3?

const s3 = new aws.S3({
  accessKeyId,
  secretKey,
  bucketRegion,
});

Please guide me that how can I deploy nodejs app without affecting AWS services.


问:
Visual Studio Code to use node version specified by NVM
Is it possible for VS Code to use node version specified by NVM?

I have 6.9.2 installed locally. Even after switching to another version, from the OS X terminal (not the VS Code terminal), restarting VS Code, VS Code still shows using 6.9.2.

OS X terminal

```<code>MacBook-Pro-3:~ mac$ node -v
v7.8.0
</code>```

VS Code Terminal

```<code>MacBook-Pro-3:QB-Invoice-API mac$ node -v
v6.9.2
</code>```

答:
According to the docs of nvm, you need to add this code snippet to your ~/.bashrc, ~/.profile, or ~/.zshrc file, so open the file and paste this in, restart vscode and enjoy nvm

```<code>export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion
</code>```

source: https://github.com/nvm-sh/nvm#manual-install

Body:
Is it possible for VS Code to use node version specified by NVM?

I have 6.9.2 installed locally. Even after switching to another version, from the OS X terminal (not the VS Code terminal), restarting VS Code, VS Code still shows using 6.9.2.

OS X terminal

MacBook-Pro-3:~ mac$ node -v
v7.8.0

VS Code Terminal

MacBook-Pro-3:QB-Invoice-API mac$ node -v
v6.9.2

Body:
According to the docs of nvm, you need to add this code snippet to your ~/.bashrc, ~/.profile, or ~/.zshrc file, so open the file and paste this in, restart vscode and enjoy nvm

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

source: https://github.com/nvm-sh/nvm#manual-install


问:
Asynchronously communication between clients and services
I've been reading for some tome ago about "asynchronous communication between microservices" and its benefits.

Something doesn't fit on my mind:

What about if client only is able to make synchronous communicacion to my service?

Or what about, if service has to be able to dispath both synchro and asynchro communication?

I mean, I can design a "barista system" like this:

Dispatchning an event from "counter service" and send a "coffee is ready" to client, when "counter service" receive an "coffee is ready event" from "barista service".

Some counterparts here:

How "counter service" sends feedback to client? Request connection has been release and then server is not able to point to client.

What about if client are not able to treat with asynchromously communiations?

I mean, what about if client is only able to handle synchronous communication on a "asynchronously inter-service communication"?

Which feedback techniques are available here? I mean, are there more modern techniques besides of "polling request status"?

答:
If a client is only able to communicate synchronously (i.e. no interaction besides client makes request and then client gets response is possible), then you essentially have two options:

You can respond to the initial request with some unique identifier that the client can use to request a [more] final response.  In the coffee bar example, this would be like placing an order over the phone, being told an order number, coming into the shop at some later point, and asking "is order XYZ ready?".  This is fairly lightweight, at least as long as the client doesn't just spam you with request updates (as in rapid polling).

Alternatively, you can present a synchronous API even if the internals are asynchronous: you just need a component that holds the interaction open until the response is final.  The analogy here would be if an order is placed over the phone, the order taker is required to stay on the line with the customer until the customer comes in to pick up the coffee.  If the connection breaks, the coffee is lost.