问:
How to remove intersecting String[] arrays from a nested ArrayList of String arrays?
Lets say i have an
ArrayList<ArrayList<String[]>> variable named ListToProcess where in each arrayList i have the following ArrayLists of String[]:

```<code>    String[] arr1 = {"1","2","3"};
    String[] arr2 = {"7","5","3"};
    String[] arr3 = {"8","2","6"};
    String[] arr4 = {"0","4","9"};
</code>```

ArrayList<String[]> arrString1 contains arr1 and arr2 and ArrayList<String[]> arrString1 constains arr3 and arr4
I want to process ListToProcess in such a way that removes arr2 & arr3 since intersect with arr1(or keep arr2and remove arr1 and arr3...) from it.
I try through flattening ListToProcess to a List<String[]> and remove intersecting elements through the below method removeIntersectingArrays

```<code>    List<String[]> flatList =
            partitionsOfClustersIds.stream()
                    .flatMap(ListToProcess::stream)
                    .collect(Collectors.toList());
    ArrayList<String[]> flattenedArrayElements=  new ArrayList<String[]>(flatList);
    flattenedArrayElements= removeIntersectingArrays(flattenedArrayElements);
</code>```

The removeIntersectingArrays method is the following :

```<code>Public static ArrayList<String[]> removeIntersectingArrays(ArrayList<String[]> totalArrays) {
        List<Integer> idx = new ArrayList<Integer>();
        for (int i = 0; i < totalArrays.size(); i++)
            for (int j = i + 1; j < totalArrays.size(); j++) {
                String[] tmpArr = totalArrays.get(j);
                if (Arrays.stream(totalArrays.get(i)).distinct().filter(x -> Arrays.stream(tmpArr).anyMatch(y -> y.equals(x))).toArray().length != 0) {

                    idx.add(j);
                }
            }
        Collections.reverse(idx);
        for (int k : idx)
            totalArrays.remove(k); // this line raises an indexOutOfBound exception
        return totalArrays;
    }
</code>```

But i get and indexOutOfBound error, any idea how to fix this ?

答:
I figured out that removing duplicates from the list of indexes of elements to remove solved it: so doing:

```<code>        ...
        // remove duplicates
        List<Integer> idxWithoutDuplicates = new ArrayList<>(
                new LinkedHashSet<>(idx));
        Collections.reverse(idxWithoutDuplicates); ...
</code>```

Solved my issue.

UPDATE : or other solution is : to check whether the index is already added to idx array above through for example this liner :

```<code>...
if (!Arrays.asList(idx).contains(j))
    idx.add(j);...
</code>```

Body:
Lets say i have an
ArrayList<ArrayList<String[]>> variable named ListToProcess where in each arrayList i have the following ArrayLists of String[]:

    String[] arr1 = {"1","2","3"};
    String[] arr2 = {"7","5","3"};
    String[] arr3 = {"8","2","6"};
    String[] arr4 = {"0","4","9"};

ArrayList<String[]> arrString1 contains arr1 and arr2 and ArrayList<String[]> arrString1 constains arr3 and arr4
I want to process ListToProcess in such a way that removes arr2 & arr3 since intersect with arr1(or keep arr2and remove arr1 and arr3...) from it.
I try through flattening ListToProcess to a List<String[]> and remove intersecting elements through the below method removeIntersectingArrays

    List<String[]> flatList =
            partitionsOfClustersIds.stream()
                    .flatMap(ListToProcess::stream)
                    .collect(Collectors.toList());
    ArrayList<String[]> flattenedArrayElements=  new ArrayList<String[]>(flatList);
    flattenedArrayElements= removeIntersectingArrays(flattenedArrayElements);

The removeIntersectingArrays method is the following :

Public static ArrayList<String[]> removeIntersectingArrays(ArrayList<String[]> totalArrays) {
        List<Integer> idx = new ArrayList<Integer>();
        for (int i = 0; i < totalArrays.size(); i++)
            for (int j = i + 1; j < totalArrays.size(); j++) {
                String[] tmpArr = totalArrays.get(j);
                if (Arrays.stream(totalArrays.get(i)).distinct().filter(x -> Arrays.stream(tmpArr).anyMatch(y -> y.equals(x))).toArray().length != 0) {

                    idx.add(j);
                }
            }
        Collections.reverse(idx);
        for (int k : idx)
            totalArrays.remove(k); // this line raises an indexOutOfBound exception
        return totalArrays;
    }

But i get and indexOutOfBound error, any idea how to fix this ?

Body:
I figured out that removing duplicates from the list of indexes of elements to remove solved it: so doing:

        ...
        // remove duplicates
        List<Integer> idxWithoutDuplicates = new ArrayList<>(
                new LinkedHashSet<>(idx));
        Collections.reverse(idxWithoutDuplicates); ...

Solved my issue.

UPDATE : or other solution is : to check whether the index is already added to idx array above through for example this liner :

...
if (!Arrays.asList(idx).contains(j))
    idx.add(j);...


来源: stackexchange

问:
How can I open read-only webpage on Flutter App
Can you show me the right way to solve my problem?

I want to run a webpage in the application and disable the screen response to user actions. (read only)

I run the page using the code:

```<code>String _url = 'https://google.com
await launch(
             _url,
             enableJavaScript: true,
             forceWebView: true,
             forceSafariVC: true,
)
</code>```

But I can't cope with making this page insensitive to user actions (buttons, zooming, etc.). I've tried:

Enable "launch" in ignoring or absorbing. Did not work.

I tried to run a URL as a background and then put an inactive transparent button on it. I failed to.

I have no idea how to bite it.

答: use webview_flutter instead it gives you more control over the web screen</p>

ContentLicense: CC BY-SA 4.0

Body:
Can you show me the right way to solve my problem?

I want to run a webpage in the application and disable the screen response to user actions. (read only)

I run the page using the code:

String _url = 'https://google.com
await launch(
             _url,
             enableJavaScript: true,
             forceWebView: true,
             forceSafariVC: true,
)

But I can't cope with making this page insensitive to user actions (buttons, zooming, etc.). I've tried:

Enable "launch" in ignoring or absorbing. Did not work.

I tried to run a URL as a background and then put an inactive transparent button on it. I failed to.

I have no idea how to bite it.


问:
ARKit and AVCamera simultaneously
As there is no autofocus in ARKit, I wanted to load ARKit in a view that is half the screen and second half will have AVFoundation -> AVCamera.
Is it possible to load AVCamera and ARKit simultaneously in same app?
Thanks.</p>

答:
I managed to use AVFoundation with ARKit by calling                     self.sceneView.session.run(self.sceneView.session.configuration!) right after taking the photo.

Use self.captureSession?.stopRunning() right after taking photo to make the session resume faster.

```<code>self.takePhoto()
self.sceneView.session.run(self.sceneView.session.configuration!)

 func startCamera() {
    captureSession = AVCaptureSession()
    captureSession.sessionPreset = AVCaptureSession.Preset.photo
    cameraOutput = AVCapturePhotoOutput()

    if let device = AVCaptureDevice.default(for: .video),
       let input = try? AVCaptureDeviceInput(device: device) {
        if (captureSession.canAddInput(input)) {
            captureSession.addInput(input)
            if (captureSession.canAddOutput(cameraOutput)) {
                captureSession.addOutput(cameraOutput)
                captureSession.startRunning()
            }
        } else {
            print("issue here : captureSesssion.canAddInput")
        }
    } else {
        print("some problem here")
    }
}

func takePhoto() {
    startCamera()
    let settings = AVCapturePhotoSettings()
    cameraOutput.capturePhoto(with: settings, delegate: self)
    self.captureSession?.stopRunning()
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: ARKit and AVCamera simultaneously

Body:
I managed to use AVFoundation with ARKit by calling                     self.sceneView.session.run(self.sceneView.session.configuration!) right after taking the photo.

Use self.captureSession?.stopRunning() right after taking photo to make the session resume faster.

self.takePhoto()
self.sceneView.session.run(self.sceneView.session.configuration!)

 func startCamera() {
    captureSession = AVCaptureSession()
    captureSession.sessionPreset = AVCaptureSession.Preset.photo
    cameraOutput = AVCapturePhotoOutput()

    if let device = AVCaptureDevice.default(for: .video),
       let input = try? AVCaptureDeviceInput(device: device) {
        if (captureSession.canAddInput(input)) {
            captureSession.addInput(input)
            if (captureSession.canAddOutput(cameraOutput)) {
                captureSession.addOutput(cameraOutput)
                captureSession.startRunning()
            }
        } else {
            print("issue here : captureSesssion.canAddInput")
        }
    } else {
        print("some problem here")
    }
}

func takePhoto() {
    startCamera()
    let settings = AVCapturePhotoSettings()
    cameraOutput.capturePhoto(with: settings, delegate: self)
    self.captureSession?.stopRunning()
}


问:
ACF Relationship Query in the Functions.php to pull into Query ID in Elementor Posts Widget
I'm trying to create 'featured posts' in specific category pages. I've set up a relationship ACF and this bit of PHP works fine and produces an array of post IDs.

```<code>$term = get_queried_object();
$things = get_field("catfeatured", $term);
</code>```

I'm trying to turn this into a query I can stick in the functions.php and then pull into my elementor posts widget using the query ID. I've been messing around for 2 days now but I seem to be no closer. This is the latest of a long line of things that didn't work:

```<code>add_action( 'elementor/query/Cat_Featured', function( $query ) {
    global $post;
    $term = get_queried_object();
    $ids = get_field("catfeatured", $term);
    $query->set( 'post__in', $ids );
});
</code>```

Someone please put me out of my misery.

答:
In category page:

```<code>$term = get_queried_object();
my_elementor_shortcode( $term );
</code>```

Then in functions.php

```<code>    my_elementor_shortcode( $term ) {
$things = get_field("catfeatured", $term); foreach ($things as $value) { echo "$value <br>"; } add_shortcode( 'my_elementor_php_output', 'my_elementor_shortcode');
</code>```

Then you can use the shortcode [my_elementor_php_output] in the elementor using shortcode widget

Body:
I'm trying to create 'featured posts' in specific category pages. I've set up a relationship ACF and this bit of PHP works fine and produces an array of post IDs.

$term = get_queried_object();
$things = get_field("catfeatured", $term);

I'm trying to turn this into a query I can stick in the functions.php and then pull into my elementor posts widget using the query ID. I've been messing around for 2 days now but I seem to be no closer. This is the latest of a long line of things that didn't work:

add_action( 'elementor/query/Cat_Featured', function( $query ) {
    global $post;
    $term = get_queried_object();
    $ids = get_field("catfeatured", $term);
    $query->set( 'post__in', $ids );
});

Someone please put me out of my misery.

Body:
In category page:

$term = get_queried_object();
my_elementor_shortcode( $term );

Then in functions.php

    my_elementor_shortcode( $term ) {
$things = get_field("catfeatured", $term); foreach ($things as $value) { echo "$value <br>"; } add_shortcode( 'my_elementor_php_output', 'my_elementor_shortcode');

Then you can use the shortcode [my_elementor_php_output] in the elementor using shortcode widget


问:
How to do infinite scrolling in flutter?
I want to scroll infinitely as much my product has. I have total 412 pages. When I scroll to the end I want to show more item of next pages. that means infinite scrolling. how to do this? i have implemented the ScrollController.

this is my Api:
https://www.moharaj.com.bd/api/new/collection/products?page=1

this is my model class:

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

import 'dart:convert';

NewCollectionProductModel newCollectionProductModelFromJson(String str) =>
    NewCollectionProductModel.fromJson(json.decode(str));

String newCollectionProductModelToJson(NewCollectionProductModel data) =>
    json.encode(data.toJson());

class NewCollectionProductModel {
  NewCollectionProductModel({
    required this.currentPage,
    required this.data,
    required this.firstPageUrl,
    required this.from,
    required this.lastPage,
    required this.lastPageUrl,
    required this.nextPageUrl,
    required this.path,
    required this.perPage,
    required this.prevPageUrl,
    required this.to,
    required this.total,
  });

  final int currentPage;
  final List<Datum> data;
  final String firstPageUrl;
  final int from;
  final int lastPage;
  final String lastPageUrl;
  final String nextPageUrl;
  final String path;
  final int perPage;
  final dynamic prevPageUrl;
  final int to;
  final int total;

  factory NewCollectionProductModel.fromJson(Map<String, dynamic> json) =>
      NewCollectionProductModel(
        currentPage: json["current_page"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
        firstPageUrl: json["first_page_url"],
        from: json["from"],
        lastPage: json["last_page"],
        lastPageUrl: json["last_page_url"],
        nextPageUrl: json["next_page_url"],
        path: json["path"],
        perPage: json["per_page"],
        prevPageUrl: json["prev_page_url"],
        to: json["to"],
        total: json["total"],
      );

  Map<String, dynamic> toJson() => {
        "current_page": currentPage,
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
        "first_page_url": firstPageUrl,
        "from": from,
        "last_page": lastPage,
        "last_page_url": lastPageUrl,
        "next_page_url": nextPageUrl,
        "path": path,
        "per_page": perPage,
        "prev_page_url": prevPageUrl,
        "to": to,
        "total": total,
      };
}

class Datum {
  Datum({
    required this.id,
    required this.name,
    required this.price,
    required this.salePrice,
    required this.slug,
    required this.discount,
    required this.thumnail,
    required this.productImage,
  });

  final int id;
  final String name;
  final String price;
  final String salePrice;
  final String slug;
  final int discount;
  final String thumnail;
  final List<ProductImage> productImage;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        id: json["id"],
        name: json["name"],
        price: json["price"],
        salePrice: json["sale_price"],
        slug: json["slug"],
        discount: json["discount"],
        thumnail: json["thumnail"],
        productImage: List<ProductImage>.from(
            json["product_image"].map((x) => ProductImage.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "price": price,
        "sale_price": salePrice,
        "slug": slug,
        "discount": discount,
        "thumnail": thumnail,
        "product_image":
            List<dynamic>.from(productImage.map((x) => x.toJson())),
      };
}

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

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

  factory ProductImage.fromJson(Map<String, dynamic> json) => ProductImage(
        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>```

this is my Service class Code:

```<code>import 'dart:convert';
import 'package:infinite_pagination/NewArrival.dart';
import 'package:infinite_pagination/NewCollectionProductModel.dart';

import 'package:http/http.dart' as http;

/**
 * This is a Service Class.
 * This Service Class is used for New COllection Product.
 *
 */

class NewCollectionProductService {
  static var product;
  static Future<NewCollectionProductModel>
      getNewCollectionProductService() async {
    try {
      final response = await http.get(Uri.parse(
          "https://www.moharaj.com.bd/api/new/collection/products?page=$pageNumber"));
      //print(response);
      if (response.statusCode == 200 || response.statusCode == 201) {
        final decode = jsonDecode(response.body);
        product = NewCollectionProductModel.fromJson(decode);
        return product;
      } else {
        return product;
      }
    } catch (error) {
      throw Exception();
    }
  }
}
</code>```

this is product Class:

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

var size = 180.0;
var iconSize = 10.0;

Widget Products(String ImgLocation, name, price, discountPrice, discountPercent,
    reviews, BuildContext context) {
  return Container(
    height: 300,
    child: Card(
      child: Padding(
          padding: EdgeInsets.all(5),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Expanded(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: Image.network(
                    '$ImgLocation',
                    fit: BoxFit.cover,
                    loadingBuilder: (context, child, loadingProgress) {
                      return loadingProgress == null
                          ? child
                          : Center(
                              child: LinearProgressIndicator(
                              value: loadingProgress.expectedTotalBytes != null
                                  ? loadingProgress.cumulativeBytesLoaded /
                                      loadingProgress.expectedTotalBytes!
                                  : null,
                            ));
                      // : LinearProgressIndicator();
                    },
                    width: MediaQuery.of(context).size.width,
                    height: size,
                  ),
                ),
              ),
              Text(
                '$name',
                textAlign: TextAlign.start,
              ),
              Text(
                '৳ $price',
                style: TextStyle(
                    fontSize: 15,
                    color: Colors.red,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.left,
              ),
              Text.rich(
                TextSpan(
                  children: <TextSpan>[
                    // ignore: unnecessary_new
                    TextSpan(
                      text: '৳ $discountPercent',
                      style: const TextStyle(
                        color: Colors.grey,
                        decoration: TextDecoration.lineThrough,
                      ),
                    ),
                    TextSpan(
                      text: ' -$discountPrice%',
                    ),
                  ],
                ),
              ),
              Row(
                children: [
                  Icon(
                    Icons.star,
                    color: Color(0xFFFfebf50),
                    size: iconSize,
                  ),
                  Icon(
                    Icons.star,
                    color: Color(0xFFFfebf50),
                    size: iconSize,
                  ),
                  Icon(
                    Icons.star,
                    color: Color(0xFFFfebf50),
                    size: iconSize,
                  ),
                  Icon(
                    Icons.star,
                    color: Color(0xFFFfebf50),
                    size: iconSize,
                  ),
                  Icon(
                    Icons.star,
                    color: Color(0xFFFfee9c3),
                    size: iconSize,
                  ),
                  SizedBox(
                    width: 5,
                  ),
                  Text(
                    '($reviews)',
                    style: TextStyle(fontSize: iconSize),
                  )
                ],
              )
            ],
          )),
    ),
  );
}
</code>```

this is my home page:

```<code>import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:infinite_pagination/NewArrivalController.dart';
import 'package:infinite_pagination/NewCollectionProductModel.dart';
import 'package:infinite_pagination/NewCollectionProductService.dart';
import 'package:infinite_pagination/Products.dart';

//------------------------------------------------------------
//        this widget is for Upcoming categories
//------------------------------------------------------------

class NewArrival extends StatefulWidget {
  @override
  State<NewArrival> createState() => _NewArrivalState();
}

var pageNumber = 1;

class _NewArrivalState extends State<NewArrival> {
  NewArrivalController newArrivalController = Get.put(NewArrivalController());
  late Future<NewCollectionProductModel> getData;

  ScrollController scrollController = ScrollController();

  @override
  void initState() {
    getData = NewCollectionProductService.getNewCollectionProductService();
    // TODO: implement initState
    super.initState();
    scrollController.addListener(() {
      print(scrollController.position.pixels);
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        pageNumber++;

        print(pageNumber);
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Padding(
                    padding: EdgeInsets.only(left: 10),
                    child: Text('New Arrival',
                        style: TextStyle(
                          fontSize: 17,
                          fontWeight: FontWeight.bold,
                        )),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: MaterialButton(
                        color: Colors.red,
                        child: Text("View All"),
                        onPressed: () {}),
                  )
                ],
              ),
              Container(
                  // height: 200,
                  child: collectionOfData())
            ],
          ),
        ),
      ),
    );
  }

  collectionOfData() {
    return FutureBuilder<NewCollectionProductModel>(
        future: getData,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
                controller: scrollController,
                physics: NeverScrollableScrollPhysics(),
                // scrollDirection: Axis.horizontal,
                shrinkWrap: true,
                itemCount: snapshot.data!.data.length,
                // gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                //     crossAxisCount: 2),
                itemBuilder: (context, int index) {
                  var product = snapshot.data!.data[index];
                  //slug = product.slug;
                  String image = product.productImage[0].prefixUrl.toString() +
                      product.productImage[0].productImage.toString();
                  return GestureDetector(
                    onTap: () {},
                    child: Container(
                      height: 300,
                      width: 200,
                      child: Products(
                        image,
                        product.name,
                        product.price,
                        product.discount,
                        product.salePrice,
                        product.id,
                        context,
                      ),
                    ),
                  );
                });
          } else {
            return Center(child: CircularProgressIndicator());
          }
        });
  }
}
</code>```

答:
you can manage in 2 ways.

without package: manage scrolling point & total page, current page & per page items.

using pagination_view and other packages.

you can also check the below links.

raywenderlich-pagination

mobikul-pageination

stack-overfllow-query

Simple Example without packages:

Declare the below code initially.

```<code>ScrollController _scrollController = new ScrollController();
  var pageNumber = 1;// update in API CALL
  total_page = 0; // update in API CALL
  current_page = 0; // update in API CALL
  List<ModelClass> arrList = [];
</code>```

Add below code init method

```<code>_scrollController.addListener(() async {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        if (currentPage != total) { // on bottom scroll API Call until last page
          currentPage += 1;
          apiCall(page: currentPage);
        }
      }
    });
</code>```

If No data is found & add Pull to refresh widget.

```<code>Widget noDataFound() {
    return RefreshIndicator(
      onRefresh: apiCall(),
      child: Center(
        child: Text('No Data Found!'),
      ),
    );
  }
</code>```

in Build Widget

```<code>arrList.isNotEmpty ? ListView.separated(
                          padding: const EdgeInsets.all(16.0),
                          separatorBuilder: (c, index) {
                            return SizedBox(
                              height: 20.0,
                            );
                          },
                          physics: AlwaysScrollableScrollPhysics(),
                          controller: _scrollController,
                          itemCount: arrList.size + 1,
                          itemBuilder: (_, index) {
                            if (index == arrList.length) { // Always one widget 'Loading...' added end of list it will Hide/Show based on condtion.
                              return Visibility(
                                visible:
                                current_page != totalPage ? false:true,
                                child: Center(
                                  child: Text('Loading...',),
                              );
                            } else {
                              return ... listViewItemWidget;
                            }
                          }) : noDataFound()
</code>```

API Call Function

```<code>apiCall(int page = 0){

// update all pagenation variables After API get & map data sucessfully
 currentPage , Total page , list value

   // Add one condition to store data
   if (page == 0) { // If Pull to refresh.
    arrList.clear();
    arrList = [mapData list from API]; // New data load.
   } else {
      arrList.add([mapData list from API]); // Append new data in old list
   }

}
</code>```

Body:
I want to scroll infinitely as much my product has. I have total 412 pages. When I scroll to the end I want to show more item of next pages. that means infinite scrolling. how to do this? i have implemented the ScrollController.

this is my Api:
https://www.moharaj.com.bd/api/new/collection/products?page=1

this is my model class:

// To parse this JSON data, do
//
//     final newCollectionProductModel = newCollectionProductModelFromJson(jsonString);

import 'dart:convert';

NewCollectionProductModel newCollectionProductModelFromJson(String str) =>
    NewCollectionProductModel.fromJson(json.decode(str));

String newCollectionProductModelToJson(NewCollectionProductModel data) =>
    json.encode(data.toJson());

class NewCollectionProductModel {
  NewCollectionProductModel({
    required this.currentPage,
    required this.data,
    required this.firstPageUrl,
    required this.from,
    required this.lastPage,
    required this.lastPageUrl,
    required this.nextPageUrl,
    required this.path,
    required this.perPage,
    required this.prevPageUrl,
    required this.to,
    required this.total,
  });

  final int currentPage;
  final List<Datum> data;
  final String firstPageUrl;
  final int from;
  final int lastPage;
  final String lastPageUrl;
  final String nextPageUrl;
  final String path;
  final int perPage;
  final dynamic prevPageUrl;
  final int to;
  final int total;

  factory NewCollectionProductModel.fromJson(Map<String, dynamic> json) =>
      NewCollectionProductModel(
        currentPage: json["current_page"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
        firstPageUrl: json["first_page_url"],
        from: json["from"],
        lastPage: json["last_page"],
        lastPageUrl: json["last_page_url"],
        nextPageUrl: json["next_page_url"],
        path: json["path"],
        perPage: json["per_page"],
        prevPageUrl: json["prev_page_url"],
        to: json["to"],
        total: json["total"],
      );

  Map<String, dynamic> toJson() => {
        "current_page": currentPage,
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
        "first_page_url": firstPageUrl,
        "from": from,
        "last_page": lastPage,
        "last_page_url": lastPageUrl,
        "next_page_url": nextPageUrl,
        "path": path,
        "per_page": perPage,
        "prev_page_url": prevPageUrl,
        "to": to,
        "total": total,
      };
}

class Datum {
  Datum({
    required this.id,
    required this.name,
    required this.price,
    required this.salePrice,
    required this.slug,
    required this.discount,
    required this.thumnail,
    required this.productImage,
  });

  final int id;
  final String name;
  final String price;
  final String salePrice;
  final String slug;
  final int discount;
  final String thumnail;
  final List<ProductImage> productImage;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        id: json["id"],
        name: json["name"],
        price: json["price"],
        salePrice: json["sale_price"],
        slug: json["slug"],
        discount: json["discount"],
        thumnail: json["thumnail"],
        productImage: List<ProductImage>.from(
            json["product_image"].map((x) => ProductImage.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "price": price,
        "sale_price": salePrice,
        "slug": slug,
        "discount": discount,
        "thumnail": thumnail,
        "product_image":
            List<dynamic>.from(productImage.map((x) => x.toJson())),
      };
}

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

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

  factory ProductImage.fromJson(Map<String, dynamic> json) => ProductImage(
        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(),
      };
}

this is my Service class Code:

import 'dart:convert';
import 'package:infinite_pagination/NewArrival.dart';
import 'package:infinite_pagination/NewCollectionProductModel.dart';

import 'package:http/http.dart' as http;

/**
 * This is a Service Class.
 * This Service Class is used for New COllection Product.
 *
 */

class NewCollectionProductService {
  static var product;
  static Future<NewCollectionProductModel>
      getNewCollectionProductService() async {
    try {
      final response = await http.get(Uri.parse(
          "https://www.moharaj.com.bd/api/new/collection/products?page=$pageNumber"));
      //print(response);
      if (response.statusCode == 200 || response.statusCode == 201) {
        final decode = jsonDecode(response.body);
        product = NewCollectionProductModel.fromJson(decode);
        return product;
      } else {
        return product;
      }
    } catch (error) {
      throw Exception();
    }
  }
}

this is product Class:

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';

var size = 180.0;
var iconSize = 10.0;

Widget Products(String ImgLocation, name, price, discountPrice, discountPercent,
    reviews, BuildContext context) {
  return Container(
    height: 300,
    child: Card(
      child: Padding(
          padding: EdgeInsets.all(5),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Expanded(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: Image.network(
                    '$ImgLocation',
                    fit: BoxFit.cover,
                    loadingBuilder: (context, child, loadingProgress) {
                      return loadingProgress == null
                          ? child
                          : Center(
                              child: LinearProgressIndicator(
                              value: loadingProgress.expectedTotalBytes != null
                                  ? loadingProgress.cumulativeBytesLoaded /
                                      loadingProgress.expectedTotalBytes!
                                  : null,
                            ));
                      // : LinearProgressIndicator();
                    },
                    width: MediaQuery.of(context).size.width,
                    height: size,
                  ),
                ),
              ),
              Text(
                '$name',
                textAlign: TextAlign.start,
              ),
              Text(
                '৳ $price',
                style: TextStyle(
                    fontSize: 15,
                    color: Colors.red,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.left,
              ),
              Text.rich(
                TextSpan(
                  children: <TextSpan>[
                    // ignore: unnecessary_new
                    TextSpan(
                      text: '৳ $discountPercent',
                      style: const TextStyle(
                        color: Colors.grey,
                        decoration: TextDecoration.lineThrough,
                      ),
                    ),
                    TextSpan(
                      text: ' -$discountPrice%',
                    ),
                  ],
                ),
              ),
              Row(
                children: [
                  Icon(
                    Icons.star,
                    color: Color(0xFFFfebf50),
                    size: iconSize,
                  ),
                  Icon(
                    Icons.star,
                    color: Color(0xFFFfebf50),
                    size: iconSize,
                  ),
                  Icon(
                    Icons.star,
                    color: Color(0xFFFfebf50),
                    size: iconSize,
                  ),
                  Icon(
                    Icons.star,
                    color: Color(0xFFFfebf50),
                    size: iconSize,
                  ),
                  Icon(
                    Icons.star,
                    color: Color(0xFFFfee9c3),
                    size: iconSize,
                  ),
                  SizedBox(
                    width: 5,
                  ),
                  Text(
                    '($reviews)',
                    style: TextStyle(fontSize: iconSize),
                  )
                ],
              )
            ],
          )),
    ),
  );
}

this is my home page:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:infinite_pagination/NewArrivalController.dart';
import 'package:infinite_pagination/NewCollectionProductModel.dart';
import 'package:infinite_pagination/NewCollectionProductService.dart';
import 'package:infinite_pagination/Products.dart';

//------------------------------------------------------------
//        this widget is for Upcoming categories
//------------------------------------------------------------

class NewArrival extends StatefulWidget {
  @override
  State<NewArrival> createState() => _NewArrivalState();
}

var pageNumber = 1;

class _NewArrivalState extends State<NewArrival> {
  NewArrivalController newArrivalController = Get.put(NewArrivalController());
  late Future<NewCollectionProductModel> getData;

  ScrollController scrollController = ScrollController();

  @override
  void initState() {
    getData = NewCollectionProductService.getNewCollectionProductService();
    // TODO: implement initState
    super.initState();
    scrollController.addListener(() {
      print(scrollController.position.pixels);
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        pageNumber++;

        print(pageNumber);
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Padding(
                    padding: EdgeInsets.only(left: 10),
                    child: Text('New Arrival',
                        style: TextStyle(
                          fontSize: 17,
                          fontWeight: FontWeight.bold,
                        )),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: MaterialButton(
                        color: Colors.red,
                        child: Text("View All"),
                        onPressed: () {}),
                  )
                ],
              ),
              Container(
                  // height: 200,
                  child: collectionOfData())
            ],
          ),
        ),
      ),
    );
  }

  collectionOfData() {
    return FutureBuilder<NewCollectionProductModel>(
        future: getData,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
                controller: scrollController,
                physics: NeverScrollableScrollPhysics(),
                // scrollDirection: Axis.horizontal,
                shrinkWrap: true,
                itemCount: snapshot.data!.data.length,
                // gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                //     crossAxisCount: 2),
                itemBuilder: (context, int index) {
                  var product = snapshot.data!.data[index];
                  //slug = product.slug;
                  String image = product.productImage[0].prefixUrl.toString() +
                      product.productImage[0].productImage.toString();
                  return GestureDetector(
                    onTap: () {},
                    child: Container(
                      height: 300,
                      width: 200,
                      child: Products(
                        image,
                        product.name,
                        product.price,
                        product.discount,
                        product.salePrice,
                        product.id,
                        context,
                      ),
                    ),
                  );
                });
          } else {
            return Center(child: CircularProgressIndicator());
          }
        });
  }
}

Body:
you can manage in 2 ways.

without package: manage scrolling point & total page, current page & per page items.

using pagination_view and other packages.

you can also check the below links.

raywenderlich-pagination

mobikul-pageination

stack-overfllow-query

Simple Example without packages:

Declare the below code initially.

ScrollController _scrollController = new ScrollController();
  var pageNumber = 1;// update in API CALL
  total_page = 0; // update in API CALL
  current_page = 0; // update in API CALL
  List<ModelClass> arrList = [];

Add below code init method

_scrollController.addListener(() async {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        if (currentPage != total) { // on bottom scroll API Call until last page
          currentPage += 1;
          apiCall(page: currentPage);
        }
      }
    });

If No data is found & add Pull to refresh widget.

Widget noDataFound() {
    return RefreshIndicator(
      onRefresh: apiCall(),
      child: Center(
        child: Text('No Data Found!'),
      ),
    );
  }

in Build Widget

arrList.isNotEmpty ? ListView.separated(
                          padding: const EdgeInsets.all(16.0),
                          separatorBuilder: (c, index) {
                            return SizedBox(
                              height: 20.0,
                            );
                          },
                          physics: AlwaysScrollableScrollPhysics(),
                          controller: _scrollController,
                          itemCount: arrList.size + 1,
                          itemBuilder: (_, index) {
                            if (index == arrList.length) { // Always one widget 'Loading...' added end of list it will Hide/Show based on condtion.
                              return Visibility(
                                visible:
                                current_page != totalPage ? false:true,
                                child: Center(
                                  child: Text('Loading...',),
                              );
                            } else {
                              return ... listViewItemWidget;
                            }
                          }) : noDataFound()

API Call Function

apiCall(int page = 0){

// update all pagenation variables After API get & map data sucessfully
 currentPage , Total page , list value

   // Add one condition to store data
   if (page == 0) { // If Pull to refresh.
    arrList.clear();
    arrList = [mapData list from API]; // New data load.
   } else {
      arrList.add([mapData list from API]); // Append new data in old list
   }

}


问:
Can't get discord.py installed on a seperate venv in linux VM
I'm unable to get discord.py installed on a separate venv on my linux VM. I'll run through exactly what's happening. Running python 3.7. I have a discord boy located on /home/username/mybot/discboy.py. I created a new venv inside of the script directory - python3 -m venv /home/username/mybot/venv. Confirmed that a new "venv" directory is in the /mybot/ directory. I activated the venv by source /home/username/mybot/venv/bin/activate . Confirmed as my PATH changed to (venv) /home/... . I then installed discord.py python3 -m pip install -U discord.py . I confirmed that it installed via pip3 list. I then started the bot up. Here is the trace code error `

```<code>0|mybot  |     import discord
0|mybot  | ModuleNotFoundError: No module named 'discord'
0|mybot  | Traceback (most recent call last):
0|mybot  |   File "/home/username/mybot/discbot.py", line 3, in <module>
0|mybot  |     import discord
0|mybot  | ModuleNotFoundError: No module named 'discord'
0|mybot  | Traceback (most recent call last):
0|mybot  |   File "/home/username/mybot/discbot.py", line 3, in <module>
0|mybot  |     import discord
0|mybot  | ModuleNotFoundError: No module named 'discord'
0|mybot  | Traceback (most recent call last):
0|mybot  |   File "/home/username/mybot/discbot.py", line 3, in <module>
0|mybot  |     import discord
0|mybot  | ModuleNotFoundError: No module named 'discord'
</code>```

To note: installing discord.py outside of the environment WORKS. It appears my script isn't running inside of the environment as I did confirm discord.py is installed to it. Is there something that I'm missing here?

Is it possible that I'm missing another package that discord.py depends on? Here's what's installed on the venv:

```<code>Package           Version
----------------- -----------
aiohttp           3.7.4.post0
async-timeout     3.0.1
attrs             21.4.0
chardet           4.0.0
discord.py        1.7.3
idna              3.3
multidict         6.0.2
pip               18.1
pkg-resources     0.0.0
python-dotenv     0.19.2
setuptools        40.8.0
typing-extensions 4.0.1
yarl              1.7.2
</code>```

答:
This sometimes happens to me. In the same directory as your bot, type this in your terminal:

```<code>pip install --target="." discord
</code>```

This will install the discord library in your directory, allowing your program to directly access it

Body:
I'm unable to get discord.py installed on a separate venv on my linux VM. I'll run through exactly what's happening. Running python 3.7. I have a discord boy located on /home/username/mybot/discboy.py. I created a new venv inside of the script directory - python3 -m venv /home/username/mybot/venv. Confirmed that a new "venv" directory is in the /mybot/ directory. I activated the venv by source /home/username/mybot/venv/bin/activate . Confirmed as my PATH changed to (venv) /home/... . I then installed discord.py python3 -m pip install -U discord.py . I confirmed that it installed via pip3 list. I then started the bot up. Here is the trace code error `

0|mybot  |     import discord
0|mybot  | ModuleNotFoundError: No module named 'discord'
0|mybot  | Traceback (most recent call last):
0|mybot  |   File "/home/username/mybot/discbot.py", line 3, in <module>
0|mybot  |     import discord
0|mybot  | ModuleNotFoundError: No module named 'discord'
0|mybot  | Traceback (most recent call last):
0|mybot  |   File "/home/username/mybot/discbot.py", line 3, in <module>
0|mybot  |     import discord
0|mybot  | ModuleNotFoundError: No module named 'discord'
0|mybot  | Traceback (most recent call last):
0|mybot  |   File "/home/username/mybot/discbot.py", line 3, in <module>
0|mybot  |     import discord
0|mybot  | ModuleNotFoundError: No module named 'discord'

To note: installing discord.py outside of the environment WORKS. It appears my script isn't running inside of the environment as I did confirm discord.py is installed to it. Is there something that I'm missing here?

Is it possible that I'm missing another package that discord.py depends on? Here's what's installed on the venv:

Package           Version
----------------- -----------
aiohttp           3.7.4.post0
async-timeout     3.0.1
attrs             21.4.0
chardet           4.0.0
discord.py        1.7.3
idna              3.3
multidict         6.0.2
pip               18.1
pkg-resources     0.0.0
python-dotenv     0.19.2
setuptools        40.8.0
typing-extensions 4.0.1
yarl              1.7.2

Body:
This sometimes happens to me. In the same directory as your bot, type this in your terminal:

pip install --target="." discord

This will install the discord library in your directory, allowing your program to directly access it


问:
Remove spaces before getting the result in laravel elequent
i want to compare the search result in laravel controller.

When user input the name and search. In my controller it will remove the input spaces and compare data retrieved from database.

Users submitted is John Doe

```<code>preg_match_all('/\@([^\s\.]+)/', $request->name, $matches);
</code>```

Remove spaces become JohnDoe. Then get data with

```<code>$user = User::where('name', $name)->first();
</code>```

And i want remove the name column spaces before comparing the result. For example the data get from database column is John Doe. How to remove the spaces and comparing them.
$user = User::where('John Doe', $matches)->first();

答:
I did use whereRaw

User::whereRaw("REPLACE('name', ' ', '') = ? ",  $request->name)->first();

and also if you want to use OR you can use: orWhereRaw

orWhereRaw or whereRaw used to write SQL functions.

Body:
i want to compare the search result in laravel controller.

When user input the name and search. In my controller it will remove the input spaces and compare data retrieved from database.

Users submitted is John Doe

preg_match_all('/\@([^\s\.]+)/', $request->name, $matches);

Remove spaces become JohnDoe. Then get data with

$user = User::where('name', $name)->first();

And i want remove the name column spaces before comparing the result. For example the data get from database column is John Doe. How to remove the spaces and comparing them.
$user = User::where('John Doe', $matches)->first();


问:
Uno App exception launch missing windows.color
I just migrated my app to use Uno 4.0 and am having a few issues.  When I go to build and run the project- I am getting this error:

System.MissingFieldException
Message=Field not found: Windows.UI.Color Windows.UI.Colors.Black Due to: Could not find field in class

I do use the colors in my MaterialColorPaletteOverride.xaml.  I currently have Uno.Material at 1.0.507.  I plan to migrate that- but would like to resolve this issue first.  This code did work before the migration- so I think somehow the colors are referenced differently now.

I am using the following packages:

Uno.Core 4.0.1

Uno.Material 1.0.0.-dev.507

Uno.UI 4.0.7

Microsoft.UI.Xaml 2.7.0

Here is my snippet from my MaterialColorPaletteOverride.xaml:

    <ResourceDictionary
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:local="using:NeatApp.Shared">
           <ResourceDictionary.ThemeDictionaries>

           <ResourceDictionary x:Key="Light">
               <SolidColorBrush x:Key="MaterialOnBackgroundBrush" Color="Black"/>
           </ResourceDictionary>

           <ResourceDictionary x:Key="Dark">
               <SolidColorBrush x:Key="MaterialOnBackgroundBrush" Color="White"/>
           </ResourceDictionary>
       </ResourceDictionary.ThemeDictionaries>
    </ResourceDictionary>
```

答: The problem is actually that you are using an incompatible version of Uno.Material. 1.0.0.-dev.507 is compatible with Uno.UI 3.x, but not with 4.x, due to the fact that there were many breaking changes (including changes in Windows.UI.Colors). You will also need to upgrade Uno.Material to a 4.x compatible version to avoid this error.


问:
How to make --version custom command in linux
So, I just started to introduce myself with custom commands in Linux and created one but now I want it to be executed globally like this,
say my command is owncmd
#!/bin/bash
echo "Heya custom commands"

this works perfectly fine when I execute
$-owncmd
but I wanted to write the version or help page like :
$- owncmd --version OR owncmd --help

答:
You should make a CLI (Command Line Interface).
To do this, you should parse the command line arguments, like --help and --version. You can access them with $1, $2, ...

Here is an example on your code :

#!/bin/bash

cli_help() {
    # --help: Shows help message
    echo "
owncmd - Custom command

Usage:
    owncmd [options]

Options:
    --help / -h: Show this message and exit.
    --version / -V: Show version number and exit.
"
    exit
}

cli_version() {
    # --version: Show version
    echo "owncmd v1.0"
    exit
}

# Argument
case $1 in
    "--help"|"-h")
        cli_help
        ;;
    "--version"|"-V")
        cli_version
        ;;
esac
# Main program
echo "Heya custom commands"
```

The program look at the first argument $1.

If it is --help or -h: Show an help message (function cli_help) and exit

If it is --version or -V: Show version number (function cli_version) and exit

ℹ Note: We use -V instead of -v because -v means "verbose mode", not "version".

If there is no --help or --version, the program shows Heya custom commands.

Body:
You should make a CLI (Command Line Interface).
To do this, you should parse the command line arguments, like --help and --version. You can access them with $1, $2, ...

Here is an example on your code :

#!/bin/bash

cli_help() {
    # --help: Shows help message
    echo "
owncmd - Custom command

Usage:
    owncmd [options]

Options:
    --help / -h: Show this message and exit.
    --version / -V: Show version number and exit.
"
    exit
}

cli_version() {
    # --version: Show version
    echo "owncmd v1.0"
    exit
}

# Argument
case $1 in
    "--help"|"-h")
        cli_help
        ;;
    "--version"|"-V")
        cli_version
        ;;
esac
# Main program
echo "Heya custom commands"

The program look at the first argument $1.

If it is --help or -h: Show an help message (function cli_help) and exit

If it is --version or -V: Show version number (function cli_version) and exit

ℹ Note: We use -V instead of -v because -v means "verbose mode", not "version".

If there is no --help or --version, the program shows Heya custom commands.


问:
column ambiguously defined in oracle apex?
I have use this code as an interactive report sql query & toad and receive the same error, the idea is simply to join two tables :

```<code>select request.* from ( select distinct
  a.REQUEST_ID,
 (select full_name from  apps.per_all_people_f ppf where sysdate between effective_start_date
 and effective_end_date and a.EMPLOYEE_NUMBER in (ppf.national_identifier,ppf.employee_number)
 and current_employee_flag = 'Y' )   EMPLOYEE_NUMBER,
 a.DEPARTMENT,
 a.LOCATION,
 a.PROBLEM_TYPE,
 a.PROBLEM_PRIORITY,
 a.PROBLEM_SUMMARY,
 a.PROBLEM_DATE ,
 a.CREATED_BY ,
 a.CREATION_DATE,
 a.LAST_UPDATE_DATE,
 a.LAST_UPDATE_LOGIN,
 a.LAST_UPDATED_BY,
 a.STATUS,
 a.CLOSED_DATE,
 a.ASSIGNED_TO,
 a.EXTENSION,
 'Assign' as Assign,
 (select user_name from apps.fnd_user where user_id=a.created_by) Assigned_by       ,
 c.REQUEST_ID,
 c.FILENAME,
 c.MIME_TYPE,
 c.BLOB_CONTENT
from IT_REQUESTS  a, IT_REQUESTS_ATTACH c
where 1=1
and a.request_source = 'IT'
and a.status                 = 'CLOSED'--'NEW'
and a.request_id = c.request_id
order by a.PROBLEM_DATE desc) request
</code>```

error received:
ORA-20999: Failed to parse SQL query! ORA-06550: line 10, column 4: ORA-00918: column ambiguously defined

答:
To illustrate what you did, I'll use Scott's sample schema.

This is a simple join between two tables; both of them contain DEPTNO column (as indicated) - no problem so far:

```<code>SQL> select e.deptno,   --> here
  2         e.ename,
  3         e.job,
  4         d.deptno,   --> and here
  5         d.dname
  6  from emp e join dept d on e.deptno = d.deptno
  7  where d.deptno = 10;

    DEPTNO ENAME      JOB           DEPTNO DNAME
---------- ---------- --------- ---------- --------------
        10 CLARK      MANAGER           10 ACCOUNTING
        10 KING       PRESIDENT         10 ACCOUNTING
        10 MILLER     CLERK             10 ACCOUNTING
</code>```

This is your situation: you used such a query as a subquery (named it request). This won't work any more because - which DEPTNO is which?

```<code>SQL> select request.*
  2  from (select e.deptno,   --> here
  3               e.ename,
  4               e.job,
  5               d.deptno,   --> and here
  6               d.dname
  7        from emp e join dept d on e.deptno = d.deptno
  8        where d.deptno = 10
  9       ) request;
select request.*
               *
ERROR at line 1:
ORA-00918: column ambiguously defined

SQL>
</code>```

What to do? As Mat commented, one option is to use only one of those columns, they have the same value anyway. Another one is to use column aliases:

```<code>SQL> select request.*
  2  from (select e.deptno as emp_deptno,    --> here
  3               e.ename,
  4               e.job,
  5               d.deptno as dept_deptno,   --> and here
  6               d.dname
  7        from emp e join dept d on e.deptno = d.deptno
  8        where d.deptno = 10
  9       ) request;

EMP_DEPTNO ENAME      JOB       DEPT_DEPTNO DNAME
---------- ---------- --------- ----------- --------------
        10 CLARK      MANAGER            10 ACCOUNTING
        10 KING       PRESIDENT          10 ACCOUNTING
        10 MILLER     CLERK              10 ACCOUNTING

SQL>
</code>```

Generally speaking, it is a bad habit to use asterisk while working with columns. Always name all of them; yes, it requires some more typing, but makes things much more clear. Therefore, avoid select request.* and specify select emp_deptno, ename, job, dept_deptno, dname from request instead.

Body:
I have use this code as an interactive report sql query & toad and receive the same error, the idea is simply to join two tables :

select request.* from ( select distinct
  a.REQUEST_ID,
 (select full_name from  apps.per_all_people_f ppf where sysdate between effective_start_date
 and effective_end_date and a.EMPLOYEE_NUMBER in (ppf.national_identifier,ppf.employee_number)
 and current_employee_flag = 'Y' )   EMPLOYEE_NUMBER,
 a.DEPARTMENT,
 a.LOCATION,
 a.PROBLEM_TYPE,
 a.PROBLEM_PRIORITY,
 a.PROBLEM_SUMMARY,
 a.PROBLEM_DATE ,
 a.CREATED_BY ,
 a.CREATION_DATE,
 a.LAST_UPDATE_DATE,
 a.LAST_UPDATE_LOGIN,
 a.LAST_UPDATED_BY,
 a.STATUS,
 a.CLOSED_DATE,
 a.ASSIGNED_TO,
 a.EXTENSION,
 'Assign' as Assign,
 (select user_name from apps.fnd_user where user_id=a.created_by) Assigned_by       ,
 c.REQUEST_ID,
 c.FILENAME,
 c.MIME_TYPE,
 c.BLOB_CONTENT
from IT_REQUESTS  a, IT_REQUESTS_ATTACH c
where 1=1
and a.request_source = 'IT'
and a.status                 = 'CLOSED'--'NEW'
and a.request_id = c.request_id
order by a.PROBLEM_DATE desc) request

error received:
ORA-20999: Failed to parse SQL query! ORA-06550: line 10, column 4: ORA-00918: column ambiguously defined

Body:
To illustrate what you did, I'll use Scott's sample schema.

This is a simple join between two tables; both of them contain DEPTNO column (as indicated) - no problem so far:

SQL> select e.deptno,   --> here
  2         e.ename,
  3         e.job,
  4         d.deptno,   --> and here
  5         d.dname
  6  from emp e join dept d on e.deptno = d.deptno
  7  where d.deptno = 10;

    DEPTNO ENAME      JOB           DEPTNO DNAME
---------- ---------- --------- ---------- --------------
        10 CLARK      MANAGER           10 ACCOUNTING
        10 KING       PRESIDENT         10 ACCOUNTING
        10 MILLER     CLERK             10 ACCOUNTING

This is your situation: you used such a query as a subquery (named it request). This won't work any more because - which DEPTNO is which?

SQL> select request.*
  2  from (select e.deptno,   --> here
  3               e.ename,
  4               e.job,
  5               d.deptno,   --> and here
  6               d.dname
  7        from emp e join dept d on e.deptno = d.deptno
  8        where d.deptno = 10
  9       ) request;
select request.*
               *
ERROR at line 1:
ORA-00918: column ambiguously defined

SQL>

What to do? As Mat commented, one option is to use only one of those columns, they have the same value anyway. Another one is to use column aliases:

SQL> select request.*
  2  from (select e.deptno as emp_deptno,    --> here
  3               e.ename,
  4               e.job,
  5               d.deptno as dept_deptno,   --> and here
  6               d.dname
  7        from emp e join dept d on e.deptno = d.deptno
  8        where d.deptno = 10
  9       ) request;

EMP_DEPTNO ENAME      JOB       DEPT_DEPTNO DNAME
---------- ---------- --------- ----------- --------------
        10 CLARK      MANAGER            10 ACCOUNTING
        10 KING       PRESIDENT          10 ACCOUNTING
        10 MILLER     CLERK              10 ACCOUNTING

SQL>

Generally speaking, it is a bad habit to use asterisk while working with columns. Always name all of them; yes, it requires some more typing, but makes things much more clear. Therefore, avoid select request.* and specify select emp_deptno, ename, job, dept_deptno, dname from request instead.


答:
Remove one of the duplicate Request_id columns (since you already have the join condition a.request_id = c.request_id then they must always be the same value). You can also remove the unnecessary 1=1 filter and the SELECT wrapping the main query:

SELECT DISTINCT
       a.REQUEST_ID,
       ( SELECT full_name
         FROM   apps.per_all_people_f ppf
         WHERE  sysdate BETWEEN effective_start_date
                        AND     effective_end_date
         AND    a.EMPLOYEE_NUMBER in (ppf.national_identifier,ppf.employee_number)
         AND    current_employee_flag = 'Y'
       ) AS  EMPLOYEE_NUMBER,
       a.DEPARTMENT,
       a.LOCATION,
       a.PROBLEM_TYPE,
       a.PROBLEM_PRIORITY,
       a.PROBLEM_SUMMARY,
       a.PROBLEM_DATE ,
       a.CREATED_BY ,
       a.CREATION_DATE,
       a.LAST_UPDATE_DATE,
       a.LAST_UPDATE_LOGIN,
       a.LAST_UPDATED_BY,
       a.STATUS,
       a.CLOSED_DATE,
       a.ASSIGNED_TO,
       a.EXTENSION,
       'Assign' as Assign,
       ( SELECT user_name
         FROM   apps.fnd_user
         WHERE  user_id=a.created_by
       ) AS Assigned_by,
       c.FILENAME,
       c.MIME_TYPE,
       c.BLOB_CONTENT
FROM   IT_REQUESTS a
       INNER JOIN IT_REQUESTS_ATTACH c
       ON (a.request_id = c.request_id)
WHERE  a.request_source = 'IT'
AND    a.status         = 'CLOSED'--'NEW'
ORDER BY a.PROBLEM_DATE desc
```

Title: column ambiguously defined in oracle apex?


问:
How to modify Internet Explorer temporary internet settings with registry?
I have been looking through registries for hours and can't seem to find the one that controls the Internet Explorer Temporary Internet File settings. I want to change from Automatic to something else.

答:
```<code>HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings
</code>```

DWORD called SyncMode5

0 = Never

2 = Every time you start internet explorer

3 = Every visit to the page.

4 = Automatically

Found it here - first result if you Google "temporary internet files check for newer registry".

Tried it out and it is certainly true for IE8/XP SP3

Body:
HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings

DWORD called SyncMode5

0 = Never

2 = Every time you start internet explorer

3 = Every visit to the page.

4 = Automatically

Found it here - first result if you Google "temporary internet files check for newer registry".

Tried it out and it is certainly true for IE8/XP SP3


问:
How to export fast large tables from SQL Server to csv?
I am trying to export large (10 million rows) table to a semicolon separated .csv file. I am currently using build in tool (Import/Export Wizard) in Microsoft SQL Server Management Studio v17 and the export takes approximately 5 hours.

Is there a simple way to speed up this process?

I am limited by my company to use only R/python solution, beside of course SQL Server itself.

答:
What is the size in memory of your table? I have a ~2Giga table turned into a csv in a couple of minutes.
Check your data source connection,  I use OLEDB.</p>


问:
Python/NumPy first occurrence of subarray
In Python or NumPy, what is the best way to find out the first occurrence of a subarray?

For example, I have

```<code>a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4]
</code>```

What is the fastest way (run-time-wise) to find out where b occurs in a? I understand for strings this is extremely easy, but what about for a list or numpy ndarray?

Thanks a lot!

[EDITED] I prefer the numpy solution, since from my experience numpy vectorization is much faster than Python list comprehension. Meanwhile, the big array is huge, so I don't want to convert it into a string; that will be (too) long.

答:
The following code should work:

```<code>[x for x in xrange(len(a)) if a[x:x+len(b)] == b]
</code>```

Returns the index at which the pattern starts.

Body:
In Python or NumPy, what is the best way to find out the first occurrence of a subarray?

For example, I have

a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4]

What is the fastest way (run-time-wise) to find out where b occurs in a? I understand for strings this is extremely easy, but what about for a list or numpy ndarray?

Thanks a lot!

[EDITED] I prefer the numpy solution, since from my experience numpy vectorization is much faster than Python list comprehension. Meanwhile, the big array is huge, so I don't want to convert it into a string; that will be (too) long.

Body:
The following code should work:

[x for x in xrange(len(a)) if a[x:x+len(b)] == b]

Returns the index at which the pattern starts.


答: You could check the input $1 to see whether it is -v or --version in which case you print the version and stop without executing the actual code. Idem for -h or --help.</p>

Title: How to make --version custom command in linux

Body:
So, I just started to introduce myself with custom commands in Linux and created one but now I want it to be executed globally like this,
say my command is owncmd
#!/bin/bash
echo "Heya custom commands"

this works perfectly fine when I execute
$-owncmd
but I wanted to write the version or help page like :
$- owncmd --version OR owncmd --help


问:
I can't display the text after the icon
I can't display text after the icon. I tried to use float but isn't working.

Can u help me to solve it please? I can't find the solve on google, i tried this before asking

CSS File:

```<code>*{
    margin: 0;
    padding: 0;
}

header{
    height: 70px;
    background-color: darkgrey;
    width: 100%;
}

i{
    margin-top: 15px;
    margin-left: 15px;
    padding: 0px 3px 0px 3px;
    border-radius: 10px;
    border-style: solid;
    border-spacing: 10px;
}

i:hover{
    background-color: grey;
}
</code>```

HTML File:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Titlu</title>

    <script src="https://kit.fontawesome.com/768cd38b76.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="./styles.css">
</head>
<body>
    <header>
        <i class="fas fa-bars fa-2x"></i>
        <h1>Titlu</h1>
    </header>
</body>
</html>
</code>```

答:
```<code>display: flex;
align-items: center;
</code>```

Just add that to the class and it should solve your problem. You can also remove margin-top in the "i" class to make you design neater.

Title: I can't display the text after the icon

Body:
I can't display text after the icon. I tried to use float but isn't working.

Can u help me to solve it please? I can't find the solve on google, i tried this before asking

CSS File:

*{
    margin: 0;
    padding: 0;
}

header{
    height: 70px;
    background-color: darkgrey;
    width: 100%;
}

i{
    margin-top: 15px;
    margin-left: 15px;
    padding: 0px 3px 0px 3px;
    border-radius: 10px;
    border-style: solid;
    border-spacing: 10px;
}

i:hover{
    background-color: grey;
}

HTML File:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Titlu</title>

    <link rel="stylesheet" href="./styles.css">

Titlu

Body:
display: flex;
align-items: center;

Just add that to the class and it should solve your problem. You can also remove margin-top in the "i" class to make you design neater.


问:
smtp connect failed in smtp mail
i have a issue sending mail using smtp mail class when i use my send email code using smtp in my local system at that time is working prefect but when i try that code in live server i got every time smtp connect failed error

i use this code for send mail using smtp mailer class

```<code>require 'mail/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'myemail@gmail.com';
$mail->Password = 'mypassword';
$mail->SMTPSecure = 'tls';
$mail->From = 'myemail@gmail.com';
$mail->FromName = 'Mailer';
$mail->addAddress('myemail@gmail.com', 'Joe User');
$mail->addAddress('myemail@gmail.com');
$mail->addReplyTo('myemail@gmail.com', 'Information');
$mail->addCC('myemail@gmail.com');
$mail->addBCC('myemail@gmail.com');
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';}
</code>```

that is my code it working in local but not working in live server

i did all setting in my php.ini file like smtp and user password
but still not working so please give me proper solution or code that working in live server

this is error

2016-07-07 17:23:09   SMTP ERROR: Failed to connect to server: Network is unreachable (101) 2016-07-07 17:23:09   SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

答:
Use real email for sender and receiver 'Make sure of the password'

change

$mail->SMTPSecure = 'tls';

to

$mail->SMTPSecure = 'ssl';

```<code>   //tls for localhost and ssl for host server 'onligne'
</code>```

add port

$mail->Port = 465 ; // or 587

may work for you :)

Title: smtp connect failed in smtp mail

Body:
i have a issue sending mail using smtp mail class when i use my send email code using smtp in my local system at that time is working prefect but when i try that code in live server i got every time smtp connect failed error

i use this code for send mail using smtp mailer class

require 'mail/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'myemail@gmail.com';
$mail->Password = 'mypassword';
$mail->SMTPSecure = 'tls';
$mail->From = 'myemail@gmail.com';
$mail->FromName = 'Mailer';
$mail->addAddress('myemail@gmail.com', 'Joe User');
$mail->addAddress('myemail@gmail.com');
$mail->addReplyTo('myemail@gmail.com', 'Information');
$mail->addCC('myemail@gmail.com');
$mail->addBCC('myemail@gmail.com');
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body in bold!';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';}

that is my code it working in local but not working in live server

i did all setting in my php.ini file like smtp and user password
but still not working so please give me proper solution or code that working in live server

this is error

2016-07-07 17:23:09   SMTP ERROR: Failed to connect to server: Network is unreachable (101) 2016-07-07 17:23:09   SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Body:
Use real email for sender and receiver 'Make sure of the password'

change

$mail->SMTPSecure = 'tls';

to

$mail->SMTPSecure = 'ssl';

   //tls for localhost and ssl for host server 'onligne'

add port

$mail->Port = 465 ; // or 587

may work for you :)


问:
DB2 Community edition on higher core count server
If I run DB2 community edition on a higher core count server will IBM want to charge me for more cores or will the software simply use only 4 cores and 16gb of memory?</p>

答:
Check out this website or this site.

It says that the limit is hard enforced. So you should not have a problem - it will stay limited to that resources.


问:
How to get list of supported argument in V (command line)
I have installed v using the official doc on my Ubuntu 20.04 LTS.

The installation was successful as I can check the version:

```<code>$ v version
V 0.2.4 310969a
</code>```

When I tried to see the supported args using help arg, it is resulting in an error.

```<code>$ v help
`v help`: unknown help topic provided. Use `v help` for usage information.
Known help topics:
</code>```

I tried v help, v --help, v -help, v --h, v -h but all resulted in an error.

Thanks.

答:
The more safe way to install v compiler it uses the following command

git clone https://github.com/vlang/v.git
cd v
make
make install
```
<p>This will use the C compiler to build v and also <code>symlink</code> it without that you know nothing.</p>
```sudo ./v symlink
```

After that you can use both v --help and v help

Body:
I have installed v using the official doc on my Ubuntu 20.04 LTS.

The installation was successful as I can check the version:

$ v version
V 0.2.4 310969a

When I tried to see the supported args using help arg, it is resulting in an error.

$ v help
`v help`: unknown help topic provided. Use `v help` for usage information.
Known help topics:

I tried v help, v --help, v -help, v --h, v -h but all resulted in an error.

Thanks.

Body:
The more safe way to install v compiler it uses the following command

git clone https://github.com/vlang/v.git
cd v
make
make install

This will use the C compiler to build v and also symlink it without that you know nothing.

sudo ./v symlink

After that you can use both v --help and v help


问:
Typescript returns string on operation number.tofixed & parseFloat doesn't return double as datatype always
```<code>const number = 100
</code>```

number.toFixed(2) -> "100.00"

```<code>parseFloat(number.toFixed(2))  -> 100
</code>```

I am not getting expected result as 100.00 as double type
if input is 100.36 getting expected result

Framework - loopback4

答:
Is that solution what you are looking for?

const number = 100.3611
let newNumber = parseFloat(number).toFixed(2)

console.log(newNumber)```

Body:
const number = 100

number.toFixed(2) -> "100.00"

parseFloat(number.toFixed(2))  -> 100

I am not getting expected result as 100.00 as double type
if input is 100.36 getting expected result

Framework - loopback4


问:
Create unique combinations regardless of subset size
I am doing a project that requires getting unique combinations in Python regardless of the subset size.

Lets say I have a list of sizes [1,2,2,3,4,5] and a size bound of 8. I want combinations that have all the elements and no repeat such that the sum of each combination should be less than or equal to 8. Another restriction is that the subtraction of the sum and the bound should be minimum.

For example in this case the answer should be [5,3] [4,2,2] [3,1] this way the total waste out of 8 will be 4 which is (3+1)-8=4.

答:
You probably need something like itertools.combinations, that will give you all the possible combinations of elements in sublists of given lenght without duplicate elements.

If you want to know more about function combinations, i would suggest to read also this.

Something like this should work:

```<code>for i in range(8//min(myList)):
    for j in itertools.permutations(myList, i):
        if sum(j) == 8:
            print(j)
</code>```

This way you are getting all the combinations of myList, and printing those ones of which element's sum is 8.

A function like this may be useful:

```<code>def permutationsWithSum(myList: list[int], n: int):
    for i in range(n//min(myList)):
        for j in itertools.permutations(myList, i):
            if sum(j) == n:
                yield j
</code>```

Body:
You probably need something like itertools.combinations, that will give you all the possible combinations of elements in sublists of given lenght without duplicate elements.

If you want to know more about function combinations, i would suggest to read also this.

Something like this should work:

for i in range(8//min(myList)):
    for j in itertools.permutations(myList, i):
        if sum(j) == 8:
            print(j)

This way you are getting all the combinations of myList, and printing those ones of which element's sum is 8.

A function like this may be useful:

def permutationsWithSum(myList: list[int], n: int):
    for i in range(n//min(myList)):
        for j in itertools.permutations(myList, i):
            if sum(j) == n:
                yield j


问:
Partial view is not loading in pagecontainer class on click of Basic Info button in asp.net MVC
Here is my code for design this UI
UI here

```<code><div>
    <div class="py-2 h4">
        Profile Setting Page
    </div>
    <div class="row">
        <div class="col-sm-2 bg-light py-2">
            <div class="p-1" >
                <a href="/Profile/BasicInfo" class="btn btn-dark w-100" id="basicinfo">Basic Info</a>
            </div>
        </div>
        <div class="col-sm-10 bg-light">
            <div class="pagecontainer">
                <div class="d-flex justify-content-center align-items-center m-4">
                    <h1 class="display-3">Welcome to Settings</h1>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

in the above code, use the 'pagecontainer' class for loading the partial UI. After clicking on 'Basic Info' button, partial view page loading but doesn't insert in pagecontainer class , it is refreshed and shows on same page like this,Image here
My JavaScript code is as,

```<code>//basic info
    $("#basicinfo").click(function (e) {
        e.preventDefault();
        var href = $(this).attr("href");
        $.get(href, function (data, status) {
            $('.pagecontainer').html(data);
        });
    });
</code>```

答:
Please remove href from tag a:

```<code><div class="p-1" >
  <a  class="btn btn-dark w-100" id="basicinfo">Basic Info</a>
</div>
</code>```

and in the javascript:

```<code>$("#basicinfo").click(function (e) {
    e.preventDefault();
    $.get("/Profile/BasicInfo", function (data, status) {
        $('.pagecontainer').html(data);
    });
});

</code>```

Body:
Here is my code for design this UI
UI here

        Profile Setting Page

                Basic Info

Welcome to Settings

in the above code, use the 'pagecontainer' class for loading the partial UI. After clicking on 'Basic Info' button, partial view page loading but doesn't insert in pagecontainer class , it is refreshed and shows on same page like this,Image here
My JavaScript code is as,

//basic info
    $("#basicinfo").click(function (e) {
        e.preventDefault();
        var href = $(this).attr("href");
        $.get(href, function (data, status) {
            $('.pagecontainer').html(data);
        });
    });

Body:
Please remove href from tag a:

<div class="p-1" >
  <a  class="btn btn-dark w-100" id="basicinfo">Basic Info</a>
</div>

and in the javascript:

$("#basicinfo").click(function (e) {
    e.preventDefault();
    $.get("/Profile/BasicInfo", function (data, status) {
        $('.pagecontainer').html(data);
    });
});


问:
PHP, MySQL: question on how to "sync" two databases
Note: my question is in the last paragraph.

I have multiple sources of files that get inserted into a database (call it process/database A). These files contain the same type of information but in different formats (i.e. different column headers, orders, number of columns, etc.), but when process A puts them into a unified table, and it is nice and neat. I need this data from multiple sources also inserted into another database (process/database B), but I'm not sure what is the best way of doing this. DB B is part of a software we use. It is not open-source, but DB connection can be made.

We already have process A up and running for a while. Process B is something new to improve physical workflow at the warehouse. I think since the data is already unified in process A, it seems to me that I should pull this unified data and insert it into B. This will save me the repetitive work of remapping everything for process B.

My question is, if I want to "sync" these two databases, what would be the optimal approach? It's not exactly "syncing," I suppose, because the two tables (only need to reference one table on each DB) have different columns. I see these approaches..

Check the entire DB's and pull from DB A to insert to DB B for new data. However, DB B has over 50K rows. DB A is much smaller and growing slowly.

Have the user input a date from which to look for new data rows to insert from A to B.

Check the latest date (data rows are dated) in DB B, and insert accordingly.

Do you guys have any inputs? I'm not too familiar with MySQL processing speed, so I'm not sure if approach 1 is a good option. I'm also not sure what some conventions (if any) are for these types of tasks. I imagine it isn't a too-uncommon thing to do. But (1) seems to be a more complete way of doing things. Any comments or alternative options are appreciated. I'd like to keep things in PHP as it will be a feature on a web application. TIA!

答:
Use mysql clustering
Check it : http://en.wikipedia.org/wiki/MySQL_Cluster</p>


问:
Javascript split function for getting name from a whole link?
I have several link like this:

```<code>https://www.globenewswire.com/news-release/2022/02/05/2379566/673/en/ROSEN-GLOBAL-INVESTOR-COUNSEL-Encourages-Reata-Pharmaceuticals-Inc-Investors-With-Losses-Over-100K-to-Secure-Counsel-Before-Important-February-18-Deadline-in-Securities-Class-Actio.html
</code>```

Or, it can be:

```<code>https://finance.yahoo.com/m/597b7dc4-eecf-3b45-83ac-fa87ba542bbf/bitcoin-is-back-over-%2441%2C000.html

https://www.dailyfx.com/forex/fundamental/forecast/weekly/title/2022/02/06/Mexican-Peso-Outlook-US-Inflation-Data-Banxico-Decision-will-Be-Key-for-USDMXN.html
</code>```

Anything. But I need the domain name. How can I get that.

Here from this two links, I need:

Finace Yahoo

Globe News Wire

Daily Fx

How can I find that using JavaScript.

答:
A solution using regex</p>
```<code>const extractNameWithoutTLD = (url) => {
  const regex = /^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n]+)/g;
  const match = regex.exec(url);
  return match[1].replace(/\.[^.]+$/, '');
}
console.log(
  extractNameWithoutTLD(
    'https://finance.yahoo.com/m/597b7dc4-eecf-3b45-83ac-fa87ba542bbf/bitcoin-is-back-over-%2441%2C000.html'
  )
);
</code>```

Body:
I have several link like this:

https://www.globenewswire.com/news-release/2022/02/05/2379566/673/en/ROSEN-GLOBAL-INVESTOR-COUNSEL-Encourages-Reata-Pharmaceuticals-Inc-Investors-With-Losses-Over-100K-to-Secure-Counsel-Before-Important-February-18-Deadline-in-Securities-Class-Actio.html

Or, it can be:

https://finance.yahoo.com/m/597b7dc4-eecf-3b45-83ac-fa87ba542bbf/bitcoin-is-back-over-%2441%2C000.html

https://www.dailyfx.com/forex/fundamental/forecast/weekly/title/2022/02/06/Mexican-Peso-Outlook-US-Inflation-Data-Banxico-Decision-will-Be-Key-for-USDMXN.html

Anything. But I need the domain name. How can I get that.

Here from this two links, I need:

Finace Yahoo

Globe News Wire

Daily Fx

How can I find that using JavaScript.

Body:
A solution using regex

const extractNameWithoutTLD = (url) => {
  const regex = /^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n]+)/g;
  const match = regex.exec(url);
  return match[1].replace(/\.[^.]+$/, '');
}
console.log(
  extractNameWithoutTLD(
    'https://finance.yahoo.com/m/597b7dc4-eecf-3b45-83ac-fa87ba542bbf/bitcoin-is-back-over-%2441%2C000.html'
  )
);


问:
Insert prepare statement mutiple checkbox with multiple queries in php
I know this question may have been asked before but I cannot find the solution for my issue. I want to implement prepare statements (procedural) to multiple checkbox I do understand how it works and has worked with it before. But in this situation, I am not sure how to implement it. Can someone please provide me with a clue?</p>
```<code><?php
if(isset($_POST) && count($_POST) > 0){
    if (isset($_POST['checkbox1'])) {
        $sql1="UPDATE switch SET status = 1 WHERE id = 1";
    } else {
        $sql1="UPDATE switch SET status = 0 WHERE id = 1";
    }
    $result=$conn->query($sql1);

    if (isset($_POST['checkbox2'])) {
        $sql2="UPDATE switch SET status = 1 WHERE id = 2";
    } else {
        $sql2="UPDATE switch SET status = 0 WHERE id = 2";
    }
    $result=$conn->query($sql2);

    if (isset($_POST['checkbox3'])) {
        $sql3="UPDATE switch SET status = 1 WHERE id = 3";
    } else {
        $sql3="UPDATE switch SET status = 0 WHERE id = 3";
    }
    $result=$conn->query($sql3);

    if (isset($_POST['checkbox4'])) {
        $sql4="UPDATE switch SET status = 1 WHERE id = 4";
    } else {
        $sql4="UPDATE switch SET status = 0 WHERE id = 4";
    }
    $result=$conn->query($sql4);
}

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form id="form" action="" method="POST" >

        <label>
            Checkbox 1
            <input type="checkbox" name="checkbox1" value="1" onchange="document.getElementById('form').submit();"
                <?php if(isset($_POST['checkbox1'])) { echo 'checked="checked"'; } ?>>
        </label>

        <label>
            Checkbox 2
            <input type="checkbox" name="checkbox2" value="1" onchange="document.getElementById('form').submit();"
                <?php if(isset($_POST['checkbox2'])) { echo 'checked="checked"'; } ?>>
        </label>

        <label>
            Checkbox 3
            <input type="checkbox" name="checkbox3" value="1" onchange="document.getElementById('form').submit();"
                <?php if(isset($_POST['checkbox3'])) { echo 'checked="checked"'; } ?>>
        </label>

        <label>
            Checkbox 4
            <input type="checkbox" name="checkbox4" value="1" onchange="document.getElementById('form').submit();"
                <?php if(isset($_POST['checkbox4'])) { echo 'checked="checked"'; } ?>>
        </label>

    </form>
</body>
</html>

</code>```

答:
Starting from the form construction, you should not make name attributes with appended numbers when the data is more meaningfully established in an array structure.  By using arrays, multiple techniques can be implemented you make your code less bloated, hardcoded, and repetitious.  Perhaps for easier reading, rename your name attributes boxes instead of checkbox which is identical to the type attribute.

Use a loop to construct your fields.

```<code>$maxBoxes = 4;  // assign this near the top of your php file so that multiple sections of your file can use it.

$fieldTemplate = <<<HTML
<label>
    Checkbox %1$d
    <input type="checkbox" name="boxes[%1$d]" value="1"%2$s>
</label>

HTML;

for ($x = 1; $x <= $maxBoxes; ++$x) {
    printf(
        $fieldTemplate,
        $x,  // %1$d
        isset($_POST['boxes'][$x]) ? " checked" : '' // %2$s
    );
}
</code>```

Move your onchange inline event to the  of your HTML document or better yet, into an external .js file.  This keeps your HTML markup very clean, lean, and readable.

Now, when your submission hits your receiving code, you can enjoy a loop again. (untested snippet)

```<code>$sql = "UPDATE switch SET status = CASE id WHEN"
for ($x = 1; $x <= $maxBoxes; ++$x) {
    $sql .= sprintf(
        " %d THEN %d",
        $x, // %d
        (int)isset($_POST['boxes'][$x]) // %d
    );
}
$sql .= " END WHERE id BETWEEN $x AND $maxBoxes";
</code>```

Because you are 100% in control of the dynamic data being fed to the query and you the placeholders in sprintf() are strongly typed, using a prepared statement can be avoided -- not that there is anything wrong with using a prepared statement (I merely chose not use one).

Perhaps the only thing not mentioned is: How are you going to determine that a submission was made when a submission includes no checkboxes (in your code)?  You are submitting every time a checkbox is toggled.  So if on the first submission, a checkbox is ticked, then that checkbox is unticked, the second submission will not trigger an UPDATE to the database.  To prevent this, you may want send a hidden value from the form so that you have something to confirm a submission.  (The $_POST superglobal array is always declared; you cannot determine anything by checking if it isset().)

Body:
I know this question may have been asked before but I cannot find the solution for my issue. I want to implement prepare statements (procedural) to multiple checkbox I do understand how it works and has worked with it before. But in this situation, I am not sure how to implement it. Can someone please provide me with a clue?

<?php
if(isset($_POST) && count($_POST) > 0){
    if (isset($_POST['checkbox1'])) {
        $sql1="UPDATE switch SET status = 1 WHERE id = 1";
    } else {
        $sql1="UPDATE switch SET status = 0 WHERE id = 1";
    }
    $result=$conn->query($sql1);

    if (isset($_POST['checkbox2'])) {
        $sql2="UPDATE switch SET status = 1 WHERE id = 2";
    } else {
        $sql2="UPDATE switch SET status = 0 WHERE id = 2";
    }
    $result=$conn->query($sql2);

    if (isset($_POST['checkbox3'])) {
        $sql3="UPDATE switch SET status = 1 WHERE id = 3";
    } else {
        $sql3="UPDATE switch SET status = 0 WHERE id = 3";
    }
    $result=$conn->query($sql3);

    if (isset($_POST['checkbox4'])) {
        $sql4="UPDATE switch SET status = 1 WHERE id = 4";
    } else {
        $sql4="UPDATE switch SET status = 0 WHERE id = 4";
    }
    $result=$conn->query($sql4);
}

?>
<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <form id="form" action="" method="POST" >

            Checkbox 1
            <input type="checkbox" name="checkbox1" value="1" onchange="document.getElementById('form').submit();"
                <?php if(isset($_POST['checkbox1'])) { echo 'checked="checked"'; } ?>>

            Checkbox 2
            <input type="checkbox" name="checkbox2" value="1" onchange="document.getElementById('form').submit();"
                <?php if(isset($_POST['checkbox2'])) { echo 'checked="checked"'; } ?>>

            Checkbox 3
            <input type="checkbox" name="checkbox3" value="1" onchange="document.getElementById('form').submit();"
                <?php if(isset($_POST['checkbox3'])) { echo 'checked="checked"'; } ?>>

            Checkbox 4
            <input type="checkbox" name="checkbox4" value="1" onchange="document.getElementById('form').submit();"
                <?php if(isset($_POST['checkbox4'])) { echo 'checked="checked"'; } ?>>

    </form>

Body:
Starting from the form construction, you should not make name attributes with appended numbers when the data is more meaningfully established in an array structure.  By using arrays, multiple techniques can be implemented you make your code less bloated, hardcoded, and repetitious.  Perhaps for easier reading, rename your name attributes boxes instead of checkbox which is identical to the type attribute.

Use a loop to construct your fields.

$maxBoxes = 4;  // assign this near the top of your php file so that multiple sections of your file can use it.

$fieldTemplate = <<<HTML
<label>
    Checkbox %1$d
    <input type="checkbox" name="boxes[%1$d]" value="1"%2$s>
</label>

HTML;

for ($x = 1; $x <= $maxBoxes; ++$x) {
    printf(
        $fieldTemplate,
        $x,  // %1$d
        isset($_POST['boxes'][$x]) ? " checked" : '' // %2$s
    );
}

Move your onchange inline event to the <head> of your HTML document or better yet, into an external .js file.  This keeps your HTML markup very clean, lean, and readable.

Now, when your submission hits your receiving code, you can enjoy a loop again. (untested snippet)

$sql = "UPDATE switch SET status = CASE id WHEN"
for ($x = 1; $x <= $maxBoxes; ++$x) {
    $sql .= sprintf(
        " %d THEN %d",
        $x, // %d
        (int)isset($_POST['boxes'][$x]) // %d
    );
}
$sql .= " END WHERE id BETWEEN $x AND $maxBoxes";

Because you are 100% in control of the dynamic data being fed to the query and you the placeholders in sprintf() are strongly typed, using a prepared statement can be avoided -- not that there is anything wrong with using a prepared statement (I merely chose not use one).

Perhaps the only thing not mentioned is: How are you going to determine that a submission was made when a submission includes no checkboxes (in your code)?  You are submitting every time a checkbox is toggled.  So if on the first submission, a checkbox is ticked, then that checkbox is unticked, the second submission will not trigger an UPDATE to the database.  To prevent this, you may want send a hidden value from the form so that you have something to confirm a submission.  (The $_POST superglobal array is always declared; you cannot determine anything by checking if it isset().)