text:
Q: How to implement Search Function using Singly Linked List in Java? Hello fellow Programmers!
I would like to ask how to implement the Search Function in Singly Linked List using Java (Data Structures).
PROBLEM: The Search function of my program can only access the head and tail of the elements.
Question: How can I access all the elements?
Sample Code:
import java.util.*;
public class MyLinkedList<T> {
    private Node<T> head;
    private Node<T> tail;

public void add(T element){
    Node<T> nd = new Node<T>();
    nd.setValue(element);
     if(head == null){
        head = nd;
        tail = nd;
      }
     else {
        tail.setNextRef(nd);
        tail = nd;
      }}
 public void delete(){
    if(head == null){
        System.out.println("List is empty...");
    }
    else{
    Node<T> tmp = head;
    head = tmp.getNextRef();
    if(head == null){
        tail = null;
    }
    System.out.println("Deleted: "+tmp.getValue());
    System.out.println("First Employee Name Deleted!");
    }
}
public void search(){
    Node<T> tmp = head;
        if(head==null){
            System.out.println("List is empty...");
        }
        else{
        String b=""+tmp.getValue();
        Scanner input=new Scanner(System.in);
        System.out.print("Enter an employee name to search: ");
        String search = input.nextLine();
        if(b.equals(search)){
         System.out.println("Found! "+tmp.getValue());
        }
        else if (b!=search){
            System.out.println("Not Found!");
        }
        tmp = tmp.getNextRef();
    }   }
  public void show(){
    Node<T> tmp = head;
    if(head==null){
        System.out.println("List is empty...");
    }
    else{
        while(true){
        if(tmp == null){
            break;
        }

        System.out.println(tmp.getValue());
        tmp = tmp.getNextRef();
    }}
}
public static void main(String a[]){
    MyLinkedList<String> sl = new MyLinkedList<String>();
    Scanner input = new Scanner(System.in);
    sl.add("Garcia, Bianca Axel, 001");
    sl.add("Temprosa, Camille Ann, 002");
    sl.add("Villanueva, Von Justin, 003");
    sl.add("Rivera, Reygie, 004");
    sl.add("Dapapac, Ronnelle, 005");
    sl.add("Bati, Aubrey, 006");
    sl.add("Fiestada, Diana Rose, 007");
    sl.add("Dobalada, Jojo, 008");
    sl.add("Del Mundo, Maria Ethel, 009");
    sl.add("Alejandro, Rachelle, 010");
    System.out.print("Welcome To Singly Linked List Management for Employee Names!\n(Created by: Alex del Rosario || Source Code: Mr. John Carlo Son)\n");
    while(true){
    System.out.println("*------------------------*");
    System.out.println("*PLEASE SELECT A FUNCTION*");
    System.out.println("*1.)Add Employee Name    *");
    System.out.println("*2.)Delete Employee Name *");
    System.out.println("*3.)Show Employee List   *");
    System.out.println("*4.)Search an Employee   *");
    System.out.println("*5.)Exit the program     *");
    System.out.println("*------------------------*");
    System.out.print("Enter a number: ");
    int select = input.nextInt();
    if(select==1){
    System.out.println("**Enter an employee name with ID number**");
    System.out.println("Use this format:(Last Name),(First Name),(ID number)");
    System.out.println("(ex. del Rosario, Alex, 0001)");
    System.out.print("Input here: ");
    input.nextLine();
    String employee=input.nextLine();
    sl.add(employee);
    System.out.println("Employee: "+employee+" successfully added!");
    }
    else if(select==2){
    sl.delete();
    }
    else if(select==3){
    System.out.println("Employee List:");
    sl.show();
    }
    else if(select==4){
    sl.search();
    }
    else if(select==5){
    System.out.println("*** THANK YOU FOR USING THIS PROGRAM! :) ***");
    System.exit(0);
    }
    else{
        System.out.println("INVALID INPUT!");
    }

    }}
}

class Node <T> implements Comparable<T> {

    private T value;
    private Node<T> nextRef;

    public T getValue() {
        return value;
    }
    public void setValue(T value) {
        this.value = value;
    }
    public Node<T> getNextRef() {
        return nextRef;
    }
    public void setNextRef(Node<T> ref) {
        this.nextRef = ref;
    }
    @Override
    public int compareTo(T arg) {
        if(arg == this.value){
            return 0;
        } else {
            return 1;
        }
    }
}

A: More a tipp than an answer. Ask yourself what you want to do. Do you want to use the linked list provided by Java or write your own code for a linked list?
With the provided list iterating is easy.
private void search(String searchElement) {
     for (int i = 0; i < list.size(); i++) {
         String listElement = list.get(i);
         if (searchElement.equals(listElement)) {
             System.out.println("Found element " + searchElement + " at position " + i);
             return;
         }
     }
     System.out.println(searchElement + " does not appear in the list");
}

When writing your own list you have to be more careful how you use the list. For example your implementation of delete() will not work.
public void delete(){
    if(head == null){
        System.out.println(List is empty...);
    }
    else{
       NodeAlex tmp = head;
       head = tmp.getNextRef();
       if(head == null){ // you need to check if head == tail or head.getNextRef() == null
          tail = null; // here you have to set tmp.setNextRef(null);
                       // and additionally define tmp as tail.
      }
      System.out.println(Deleted +tmp.getValue());
      System.out.println(First Employee Name Deleted!);
    }
}

Edit: To access the list you have two possibilities. At first you have to create a new instance, i.e., (here for Strings, you might want to use other types/objects)
List<String> list = new LinkedList<String>();

Then you basically have two opportunities on how to access the list in the methods.
(a) Your method is in the same class where you initialized the list, however, list has to be a global field.
private List<String> list;

private static void main(String[] args) {
     list = new LinkedList<String>();
     (...)
}

private static void search(String searchElement) {
     // has access on list
}

(b) You simply pass your list to the method you need and if the method modifies the list you need to return the list again.
(main class, main method)
search(list, "Test");
list = delete(list, "Test");

(the class where the methods are located)
public void search(List<String> list, String searchElement) { ... }

public List<String> delete(List<String> list, String elementToDelete) {
      // delete element
      return list;
}


text:
Q: get the minimum number of execution for a generator to yield a specific item Imagine that we have a generator as simple as the following:
def gen_question():
    letters = ['a', 'b', 'c', 'e', 'f', 'g']
    count = 0
    while True:
        if count >= len(letters):
            count = 0
        obj = letters[count]
        yield obj
        count +=1

I would like to get the minimum number of times that the generator needs to be executed to yield a specif item. For instance we need to execute it at least 3 times to get the first 'c' item. So 3 is my index of interest in this case. How could I do this in a neat way?
PS : My real function is a keras generator yielding batches of training data and I would like to get the index of a specific batch (i.e. number of extraction to yield a specific batch).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular 2 rc 1 router - rewrites url After updating to rc 1 routing, my application doesn't work when url has query string parameters.
Here is how the routes are defined in the app component:
import {Component,  OnInit, OnDestroy } from '@angular/core';
import {ROUTER_PROVIDERS, Routes, Router, ROUTER_DIRECTIVES} from '@angular/router';
@Component({ selector: 'my-app',
    providers:[ROUTER_PROVIDERS],
    template:
    `
        <router-outlet></router-outlet>
    `
    , directives: [ROUTER_DIRECTIVES]
})
@Routes([
    {path:'/designer',              component: MainComponent},
    {path:'/designer/designs/:id',   component: SharedDesignComponent}
])
export class AppComponent implements OnInit, OnDestroy  {

constructor(private router: Router){}

ngOnInit() {
    console.log("appComponent: Initialized");
 }

ngOnDestroy() {  }
}

And here is the Main Component:
import {Component, OnInit, OnDestroy, Input, ChangeDetectorRef} from "@angular/core";
import {OnActivate, Router, RouteSegment} from "@angular/router";
@Component({
    selector: "my-main",
    templateUrl: "main.html"
})
export class MainComponent implements OnInit, OnDestroy, OnActivate {
    constructor(private router: Router){}
    routerOnActivate(curr: RouteSegment) : void {
        let id = curr.getParam("designId");
    }
    ngOnInit() {}
}

So the problem is when I have the url like this, http://localhost:49191/designer?designId=100, it calls the main component correctly and the routerOnActivate is called too. But inside it, I don't get id. And as soon as the ngOnInit is called, the url is changed to http://localhost:49191/designer without the query string parameter.
How do I retain the url? And not let it change by the router?

A: You need to access your MainComponent like this:
http://localhost:49191/designer;designId=100

Notice how I replaced ? with ;
And everything should work fine.
Basically the query string parameters are no longer separated by "?" and "&". They are separated by semicolons (;). This is called Matrix URL notation which is the way Angular 2 RC1 Router works based on.
Please see this answer for more info.


text:
Q: Parse exception in hive I have built a hive query which will join 2 tables and get the sum of the columns and based on that, have written a nested case statement that goes as below:
select purchasing_document, pdoc_litem, po_quantity, po_value,gr_quantity, gr_value, ir_quantity, ir_value,
case
when po_quantity != '0' then
case
when gr_quantity != '0' then
case
when ir_quantity = '0' then 'Invoice qty not posted'
when ir_quantity != '0' and gr_quantity > ir_quantity then 'Invoice qty is partially posted'
when gr_quantity < ir_quantity then 'Invoice qty exceeds GR qty '
else 'Invoice qty is completely posted' end
when gr_quantity = '0' then
case
when ir_quantity != '0' then 'Invoice qty exceeds GR qty where GR qty = 0'
else 'Both GR and Invoice qty not posted at all' end
else '' end
else 'PO qty not present' end as comment1
from
( select  a.purchasing_document, a.pdoc_litem ,
               sum(b.re_quantity)    ir_quantity,
               min(b.re_quantity)    min_ir_quantity,
               sum(b.re_value)       ir_value,
               sum(a.we_quantity)    gr_quantity,
               min(a.we_quantity)    min_gr_quantity,
               sum(a.we_value)       gr_value,
               min(a.Po_quantity) po_quantity,
               min(a.PO_value)    po_value
       from grir_data_we_only a join grir_data_re_only b ON (a.pdoc_litem = b.pdoc_litem)
       group by purchasing_document, pdoc_litem
       )s order by     purchasing_document, pdoc_litem limit 10;

But I am getting the below error:
FAILED: ParseException line 5:0 cannot recognize input near 'when' 'gr_quantity' '!=' in expression specification
Can you please help on this? Thanks!!


text:
Q: How to initiate the state after getting data from firestore automaticly i m a beginner in flutter and i m working on a history page in my app,
what i m trying to do is getting data from Firestore, then work on that data and stock it into a list so i can build my history items in the dashbord widget, the problem is that the items don't appear unless i refresh the state manually, and in my case i m using this filter icon, the fonction that gets me data is getVente() which im calling it in initState() , i want this fonction to execute in the moment that i load my page, so the items too, and not manually.
this is what's happening image gif
and this is the code
import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:chips_choice/chips_choice.dart';
import 'package:stocknsell/Components/DownSelect.dart';
import 'package:stocknsell/Components/DownSelect2.dart';
import 'package:date_range_picker/date_range_picker.dart' as DateRagePicker;
import 'package:stocknsell/Components/historyitem.dart';

final Color backgroundColor = Color(0xFF4A4A58);

class HistoriquePage extends StatefulWidget {
  static String id = "/history";
  @override
  _HistoriquePageState createState() => _HistoriquePageState();
}

class _HistoriquePageState extends State<HistoriquePage>
    with SingleTickerProviderStateMixin {
  bool isCollapsed = true;
  double screenWidth, screenHeight;
  final Duration duration = const Duration(milliseconds: 300);
  AnimationController _controller;
  Animation<double> _scaleAnimation;
  Animation<double> _menuScaleAnimation;
  Animation<Offset> _slideAnimation;
  Vente vente;
  List<Vente> list = List();
  List<Produit> produits = List();
  Produit produit = Produit();

  @override
  void initState() {
    getVente();
    _controller = AnimationController(vsync: this, duration: duration);
    _scaleAnimation = Tween<double>(begin: 1, end: 0.8).animate(_controller);
    _menuScaleAnimation =
        Tween<double>(begin: 0.5, end: 1).animate(_controller);
    _slideAnimation = Tween<Offset>(begin: Offset(-1, 0), end: Offset(0, 0))
        .animate(_controller);
    super.initState();
  }

  void getVente() async {
    bool trouve = false;
    await for (var snapshots
        in FirebaseFirestore.instance.collection('vente').snapshots()) {
      for (var ventes in snapshots.docs) {
        if ((ventes['client_id'] != null) && (ventes['date'] != null)) {
          if (list.isNotEmpty) {
            for (var sells in list) {
              if ((sells.clientid == ventes['client_id']) &&
                  (sells.date == ventes['date'])) {
                trouve = true;
                produit = Produit();
                produit.baseprice = ventes['baseprice'];
                produit.couttotale = ventes['couttotale'];
                produit.nbarticle = ventes['nb_product'];
                produit.prixpromo = ventes['prixpromo'];
                produit.nom = ventes['marque'];
                sells.produits.add(produit);
                sells.montant += produit.couttotale;
              }
            }
            if (!trouve) {
              vente = Vente(
                clientid: ventes['client_id'],
                clientnom: ventes['client_name'],
                date: ventes['date'],
                data: ventes,
                montant: ventes['couttotale'],
              );
              produit = Produit();
              produit.baseprice = ventes['baseprice'];
              produit.couttotale = ventes['couttotale'];
              produit.nbarticle = ventes['nb_product'];
              produit.prixpromo = ventes['prixpromo'];
              produit.nom = ventes['marque'];
              vente.produits = List<Produit>();
              vente.produits.add(produit);
              list.add(vente);
            }
            trouve = false;
          } else {
            vente = Vente(
              clientid: ventes['client_id'],
              clientnom: ventes['client_name'],
              date: ventes['date'],
              data: ventes,
              montant: ventes['couttotale'],
            );
            vente.produits = List<Produit>();
            produit = Produit();
            produit.baseprice = ventes['baseprice'];
            produit.couttotale = ventes['couttotale'];
            produit.nbarticle = ventes['nb_product'];
            produit.prixpromo = ventes['prixpromo'];
            produit.nom = ventes['marque'];
            vente.produits.add(produit);
            list.add(vente);
          }
        }
      }
    }
    setState(() {});
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    screenHeight = size.height;
    screenWidth = size.width;
    return Scaffold(
      backgroundColor: backgroundColor,
      body: Stack(
        children: <Widget>[
          menu(context),
          dashboard(context),
        ],
      ),
    );
  }

  int tag = 0;
  List<String> options = [
    'Date',
    'Client',
    'Montant',
  ];
  final elements1 = [
    "Alger",
    "Harach",
    "Beo",
    "Said Hamdine",
    "Ain Naadja",
    "Kouba",
    "Garidi",
  ];

  _openPopup(context) {
    DateTime mindate, maxdate;
    Alert(
        context: context,
        title: "Filtres",
        style: AlertStyle(
            backgroundColor: Colors.grey[200],
            titleStyle: TextStyle(
                fontFamily: 'Mom cake',
                fontWeight: FontWeight.bold,
                fontSize: 34)),
        content: SizedBox(
          width: screenWidth,
          height: screenHeight * 0.6,
          child: Padding(
            padding: const EdgeInsets.only(left: 8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text("Trier par :",
                    style: TextStyle(
                        fontFamily: 'Mom cake',
                        fontWeight: FontWeight.bold,
                        fontSize: 34)),
                Row(
                  children: [
                    Expanded(
                      child: ChipsChoice<int>.single(
                        value: tag,
                        onChanged: (val) => setState(() => tag = val),
                        choiceItems: C2Choice.listFrom<int, String>(
                          source: options,
                          value: (i, v) => i,
                          label: (i, v) => v,
                        ),
                        choiceStyle: C2ChoiceStyle(
                          color: Colors.black,
                          borderRadius:
                              const BorderRadius.all(Radius.circular(10)),
                        ),
                      ),
                    ),
                  ],
                ),
                Text("Secteur :"),
                MyStatefulWidget(),
                Text("Client : "),
                MyStatefulWidget2(),
                Text("Montant de vente"),
                Row(
                  children: [
                    SizedBox(
                      width: 110.0,
                      child: TextFormField(
                        decoration: InputDecoration(
                          labelText: 'MIN',
                          border: OutlineInputBorder(),
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 8,
                      child: Divider(
                        thickness: 2.0,
                      ),
                    ),
                    SizedBox(
                      width: 110.0,
                      child: TextFormField(
                        decoration: InputDecoration(
                          labelText: 'MAX',
                          border: OutlineInputBorder(),
                        ),
                      ),
                    ),
                  ],
                ),
                Text("Date de vente"),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    SizedBox(
                      width: 150.0,
                      height: 70,
                      child: IconButton(
                        icon: Icon(
                          Icons.date_range_rounded,
                        ),
                        onPressed: () async {
                          final List<DateTime> picked =
                              await DateRagePicker.showDatePicker(
                                  context: context,
                                  initialFirstDate: new DateTime.now(),
                                  initialLastDate: new DateTime.now()
                                      .add(new Duration(days: 7)),
                                  firstDate: new DateTime(2015),
                                  lastDate: new DateTime(2030));
                          if (picked != null && picked.length == 2) {
                            mindate = picked[1];
                            maxdate = picked[2];
                          }
                        },
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
        buttons: [
          DialogButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              "Filtrer",
              style: TextStyle(color: Colors.white, fontSize: 17),
            ),
          ),
          DialogButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              "Réinitialiser",
              style: TextStyle(color: Colors.white, fontSize: 17),
            ),
          )
        ]).show();
  }

  Widget menu(context) {
    return ... some widget ...
  }

  Widget dashboard(context) {
    return AnimatedPositioned(
      duration: duration,
      top: 0,
      bottom: 0,
      left: isCollapsed ? 0 : 0.6 * screenWidth,
      right: isCollapsed ? 0 : -0.2 * screenWidth,
      child: ScaleTransition(
        scale: _scaleAnimation,
        child: Material(
          animationDuration: duration,
          borderRadius: BorderRadius.all(Radius.circular(40)),
          elevation: 8,
          color: backgroundColor,
          child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            physics: ClampingScrollPhysics(),
            child: Container(
              padding: const EdgeInsets.only(left: 16, right: 16, top: 37),
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        InkWell(
                          child: Icon(Icons.menu, color: Colors.white),
                          onTap: () {
                            setState(() {
                              if (isCollapsed) {
                                _controller.forward();
                              } else
                                _controller.reverse();

                              isCollapsed = !isCollapsed;
                            });
                          },
                        ),
                        Text("Historique",
                            style:
                                TextStyle(fontSize: 24, color: Colors.white)),
                        IconButton(
                            icon: CircleAvatar(
                              radius: 15.0,
                              backgroundImage:
                                  AssetImage('assets/images/search.png'),
                            ),
                            onPressed: () {
                              _openPopup(context);
                              setState(() {});
                            })
                      ],
                    ),
                    ListView.builder(
                      scrollDirection: Axis.vertical,
                      shrinkWrap: true,
                      itemCount: list.length,
                      itemBuilder: (context, index) {
                        return HistoryItem(
                          client_id: list[index].clientid,
                          date: list[index].date,
                          clientnom: list[index].clientnom,
                          screenWidth: MediaQuery.of(context).size.width,
                          documentSnapshot: list[index].data,
                          montant: list[index].montant,
                          produits: list[index].produits,
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class Vente {
  DocumentSnapshot data;
  String clientid;
  String clientnom;
  String date;
  double montant;
  List<Produit> produits;
  Vente(
      {@required this.clientid,
      this.date,
      this.data,
      this.clientnom,
      this.produits,
      this.montant});
}

class Produit {
  String nom;
  int baseprice;
  double prixpromo;
  double couttotale;
  int nbarticle;
  Produit(
      {this.baseprice,
      this.nbarticle,
      this.nom,
      this.couttotale,
      this.prixpromo});
}

A: You can use FutureBuilder widget. Wrap your ListView.builder with FutureBuilder.
FutureBuilder<List<Vente>(
  future: getVente(),
  builder: (context, stream){
    if(stream.hasData){
       return ListView.builder();
    } else {
       return CircularProgressIndicator() ;
    }
  }

)

Update your getVente() method
Future<List<Vente>> getVente() async {
  bool trouve = false;
  await for (QuerySnapshot snapshots
      in FirebaseFirestore.instance.collection('vente').snapshots()) {
    for (var ventes in snapshots.docs) {
      if ((ventes['client_id'] != null) && (ventes['date'] != null)) {
        if (list.isNotEmpty) {
          for (var sells in list) {
            if ((sells.clientid == ventes['client_id']) &&
                (sells.date == ventes['date'])) {
              trouve = true;
              produit = Produit();
              produit.baseprice = ventes['baseprice'];
              produit.couttotale = ventes['couttotale'];
              produit.nbarticle = ventes['nb_product'];
              produit.prixpromo = ventes['prixpromo'];
              produit.nom = ventes['marque'];
              sells.produits.add(produit);
              sells.montant += produit.couttotale;
            }
          }
          if (!trouve) {
            vente = Vente(
              clientid: ventes['client_id'],
              clientnom: ventes['client_name'],
              date: ventes['date'],
              data: ventes,
              montant: ventes['couttotale'],
            );
            produit = Produit();
            produit.baseprice = ventes['baseprice'];
            produit.couttotale = ventes['couttotale'];
            produit.nbarticle = ventes['nb_product'];
            produit.prixpromo = ventes['prixpromo'];
            produit.nom = ventes['marque'];
            vente.produits = List<Produit>();
            vente.produits.add(produit);
            list.add(vente);
          }
          trouve = false;
        } else {
          vente = Vente(
            clientid: ventes['client_id'],
            clientnom: ventes['client_name'],
            date: ventes['date'],
            data: ventes,
            montant: ventes['couttotale'],
          );
          vente.produits = List<Produit>();
          produit = Produit();
          produit.baseprice = ventes['baseprice'];
          produit.couttotale = ventes['couttotale'];
          produit.nbarticle = ventes['nb_product'];
          produit.prixpromo = ventes['prixpromo'];
          produit.nom = ventes['marque'];
          vente.produits.add(produit);
          list.add(vente);
        }
      }
    }
  }
  return list; // Add this here
}

Explanation
FutureBuilder<T> will wait for a future to be completed.
In this case, FutureBuilder<void> expected nothing, so as your method getVente() which returns void. It will wait until the code is completed, and notify the builder. In this case, you don't need to call getVente() method in initState, since FutureBuilder will do it for you.
You can also you FutureBuilder<List<Vente>> which is better, but you will need to change your code quite a bit. It expects a list of Vente objects, which you can use in your builder method.
future.connectionState == ConnectionState.waiting will check if the future is still in connection, and not yet completed. In this case, the builder will show a CircularProgressIndicator(),
When the future is completed, it will then return the ListView.builder method.
You can find out more information about FutureBuilder if you want.
You can also use StreamBuilder if you want the widget to be updated when the value changes.
StreamBuilder<List<Vente>(
  stream: getVente(),
  builder: (context, future){
    if(future.hasData){
       return ListView.builder();
    } else {
       return CircularProgressIndicator() ;
    }
  }

)

Update your getVente() method
Stream<List<Vente>> getVente() async* {
  bool trouve = false;
  await for (QuerySnapshot snapshots
      in FirebaseFirestore.instance.collection('vente').snapshots()) {
    for (var ventes in snapshots.docs) {
      if ((ventes['client_id'] != null) && (ventes['date'] != null)) {
        if (list.isNotEmpty) {
          for (var sells in list) {
            if ((sells.clientid == ventes['client_id']) &&
                (sells.date == ventes['date'])) {
              trouve = true;
              produit = Produit();
              produit.baseprice = ventes['baseprice'];
              produit.couttotale = ventes['couttotale'];
              produit.nbarticle = ventes['nb_product'];
              produit.prixpromo = ventes['prixpromo'];
              produit.nom = ventes['marque'];
              sells.produits.add(produit);
              sells.montant += produit.couttotale;
            }
          }
          if (!trouve) {
            vente = Vente(
              clientid: ventes['client_id'],
              clientnom: ventes['client_name'],
              date: ventes['date'],
              data: ventes,
              montant: ventes['couttotale'],
            );
            produit = Produit();
            produit.baseprice = ventes['baseprice'];
            produit.couttotale = ventes['couttotale'];
            produit.nbarticle = ventes['nb_product'];
            produit.prixpromo = ventes['prixpromo'];
            produit.nom = ventes['marque'];
            vente.produits = List<Produit>();
            vente.produits.add(produit);
            list.add(vente);
          }
          trouve = false;
        } else {
          vente = Vente(
            clientid: ventes['client_id'],
            clientnom: ventes['client_name'],
            date: ventes['date'],
            data: ventes,
            montant: ventes['couttotale'],
          );
          vente.produits = List<Produit>();
          produit = Produit();
          produit.baseprice = ventes['baseprice'];
          produit.couttotale = ventes['couttotale'];
          produit.nbarticle = ventes['nb_product'];
          produit.prixpromo = ventes['prixpromo'];
          produit.nom = ventes['marque'];
          vente.produits.add(produit);
          list.add(vente);
        }
      }
    }
  }
  yield list; // Add this here
}


text:
Q: Codeigniter: how to get cart value for paypal payment <?php echo form_open('member/update_cart'); ?>

Your Shopping Cart

        <input type="button" value="Continue Shopping" onclick="window.location='<?php echo base_url(); ?>member/book'" />

        <?php if ($cart = $this->cart->contents()): ?>

            Item No
            Book Name
            Price
            Quantity
            Sub-Total
            Remove

        <?php
        echo form_open('cart/update_cart');
        $grand_total = 0; $i = 1;

        foreach ($cart as $item):
            echo form_hidden('cart['. $item['id'] .'][id]', $item['id']);
            echo form_hidden('cart['. $item['id'] .'][rowid]', $item['rowid']);
            echo form_hidden('cart['. $item['id'] .'][name]', $item['name']);
            echo form_hidden('cart['. $item['id'] .'][price]', $item['price']);
            echo form_hidden('cart['. $item['id'] .'][qty]', $item['qty']);
        ?>

                <?php echo $i++; ?>

                <?php echo $item['name']; ?>

                $ <?php echo number_format($item['price'],2); ?>

                <?php echo form_input('cart['. $item['id'] .'][qty]', $item['qty'], 'maxlength="3" size="1" style="text-align: right"'); ?>

            <?php $grand_total = $grand_total + $item['subtotal']; ?>

                $ <?php echo number_format($item['subtotal'],2) ?>

                <a href="<?php echo base_url(); ?>cart/remove/<?php echo $item['rowid'] ?>" style="color:#000000;">Remove

            <?php endforeach; ?>

            Grand Total: $<?php echo number_format($grand_total,2); ?>
            <input type="button" value="Clear Cart" onclick="clear_cart()">
                    <input type="submit" value="Update Cart">
                    <?php echo form_close(); ?>

                    <input type="button" value="Checkout" onclick="window.location='<?php echo base_url(); ?>payment/checking'">

        <?php endif; ?>

This is the paypal controller code:

public function __construct(){
    parent::__construct();
    $this->load->library('session');
    $this->load->library('cart');
    $this->load->helper('url');
    $this->load->helper('form');
    if (! $this->session->userdata('is_logged_in')){
        redirect('main/restricted');
    } else {
    $privilege = $this->session->userdata('privilege');
    if ($privilege == 'admin'){
        redirect('main/restricted');
    }
    }
    $this->load->helper("string");
}

public function do_purchase(){
    $config['business']             = 'phptesting2015-facilitator@gmail.com';
    $config['cpp_header_image']     = ''; //Image header url [750 pixels wide by 90 pixels high]
    $config['return']               = 'https://snt.website/ignite_project/payment/notify_purchase';
    $config['cancel_return']        = 'https://snt.website/ignite_project/payment/cancel_purchase';
    $config['notify_url']           = 'process_payment.php'; //IPN Post
    $config['production']           = FALSE; //Its false by default and will use sandbox
    //$config['discount_rate_cart']     = 20; //This means 20% discount
    $config["invoice"]              = random_string('numeric', 8); //The invoice id

    $this->load->library('paypal',$config);

    #$this->paypal->add(<name>,<price>,<quantity>[Default 1],[Optional]);

    //$this->paypal->add('T-shirt',2.99,6); //First item
    //$this->paypal->add('Pants',40);     //Second item
    //$this->paypal->add('Blowse',10,10,'B-199-26'); //Third item with code

    $this->paypal->pay(); //Proccess the payment
}

public function notify_purchase(){
    $received_data = print_r($this->input->post(), TRUE);

    echo "
".$received_data."
";
}

public function cancel_purchase(){
    echo "Cancel Purchase";

}

}

I am wondering how would i be able to get the data from the cart, so that i would be able to add the value in paypal so that the user will be able to proceed with the paypal? Please help!

A: Uses the CI Cart Library Method for this
$this->cart->total()

You get the total amount (price) with this and if you want to make discount over this u need to make a method exclusive for this.
[EDIT]
When you get the total amount parse it for the Paypal Library and with Curl (according with the Paypal Docs) you can parse the value with a Curl Method
curl -v -X 'POST' 'https://api.sandbox.paypal.com/v1/invoicing/invoices' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <Access-Token>' \
-d '{
  "merchant_info": {
    "email": "dennis@sample.com",
    "first_name": "Dennis",
    "last_name": "Doctor",
    "business_name": "Medical Professionals, LLC",
    "phone": {
      "country_code": "001",
      "national_number": "5032141716"
    },
    "address": {
      "line1": "1234 Main St.",
      "city": "Portland",
      "state": "OR",
      "postal_code": "97217",
      "country_code": "US"
    }
  },
  "billing_info": [
  {
    "email": "example@example.com"
  }
  ],
  "items": [
  {
    "name": "Sutures",
    "quantity": 100,
    "unit_price": {
    "currency": "USD",
    "value": 5
    }
  }
  ],
  "note": "Medical Invoice 16 Jul, 2013 PST",
  "payment_term" :{
      "term_type": "NET_45"
  },
  "shipping_info": {
    "first_name": "Sally",
    "last_name": "Patient",
    "business_name": "Not applicable",
    "address": {
    "line1": "1234 Broad St.",
    "city": "Portland",
    "state": "OR",
    "postal_code": "97216",
    "country_code": "US"
    }
  }
}'

(Source: CodeIgniter Documentation and PayPal API Documentation)

A: Judging by the code in your controller, you can use your paypal (library I presume), in the do_purchase() function to add products by looping through the cart contents:
foreach ($this->cart->contents() as $item) {
    $this->paypal->add($item['name'], $item['price'], $item['qty']);
}

$total = $this->cart->total();

You can find out more about CodeIgniter's shoppping cart class in the docs.
On a totally unrelated note, you can use base_url() as a function rather than append strings to it. For example <?=base_url('cart/remove/' . $item['rowid']);?> is a lot more readable compared to <?php echo base_url(); ?>cart/remove/<?php echo $item['rowid'] ?>


text:
Q: How to access docker container behind traefik in home network I run a docker host in my homelab using ubuntu. The host is reachable via docker.mydomain.com. This is managed by my pfsense firewall.
I use the following docker-compose file:
version: "3.7"

services:
  traefik:
    image: "traefik:v2.9"
    container_name: "traefik"
    hostname: "traefik"
    ports:
      - "80:80"
      - "8008:8080"
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro"
      - "./traefik.yml:/traefik.yml:ro"

  apache:
    image: httpd:latest
    container_name: apache
    hostname: apache
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.apache.entrypoints=web"
      - "traefik.http.routers.apache.rule=Host(`apache.docker.mydomain.com`)"

Additionally i use the following traefik.yml file
log:
  level: INFO

api:
  insecure: true
  dashboard: true

entryPoints:
  web:
    address: ":80"

providers:
  docker:
    endpoint: "unix:///var/run/docker.sock"
    exposedByDefault: false

I can reach the traefik web ui but not the apache default site using apache.docker.mydomain.com. I'm not sure if pfsense is the problem or traefik. What am i missing here?
UPDATE:
I see the apache service in the traefik ui:

A: It seems to be an issue with the dns forwarding on the pfsense firewall. I added a wildcard rule to address=/.docker.mydomain.com/192.168.1.10 and now the apache is reachable via apache.docker.mydomain.com


text:
Q: Step in proof of Dirichlet Series Convergence I am reading this proof, and am wondering about the justification of the step labeled "telescoping the series on the right."
$$\sum_{n=m}^{N-1} |(n+1)^{-s}-n^{-s}| \le |N^{-s}-m^{-s}|$$
where $\operatorname{Re}(s)>0$.
Why are you allowed to do this when there are absolute value signs?

A: Good point, which I think the author of ProofWiki proof has missed. When $\operatorname{Re} s>0$, we have
$$\begin{split}
\left|\frac{1}{(n+1)^{s}}-\frac{1}{n^s}\right| & =\left|\int_{n}^{n+1}\frac{s}{x^{s+1}}\,dx\right| \\ & \leq |s| \int_{n}^{n+1}\frac{dx}{x^{\operatorname{Re} s +1}} \\ &=\frac{|s|}{\operatorname{Re} s }\left(\frac{1}{n^{\operatorname{Re} s }}-\frac{1}{(n+1)^{\operatorname{Re} s }}\right)
\end{split}$$
Which leads to telescoping, but with the extra constant factor in front.
As seen in Uniform convergence of Dirichlet series, answer by Josué Tonelli-Cueto.


text:
Q: Setup wxWidgets on Code::Blocks I want to setup wxWidgets 3.2.1 in Code::Blocks 20.03, but with no success.
Here are the steps I took so far:

*

*Installed GCC 12.2.0 MinGW-W64

*Installed Code::Blocks 20.03 mingw setup

*Installed wxWidgets 3.2.1 using the Windows Installer

*Created a wxWidgets project in Code::Blocks: File > New > Project > wxWidgets Project

*Selected wxWidgets 3.1.x (since there is no entry for wxWidgets 3.2.x)

*Selected project and author information, "Preferred GUI Builder" and "Application Type"

*In the wxWidgets' location I enterd C:\wxWidgets-3.2.1 (where it's currently installed)

*Checked both Create "Debug" configuration and Create "Release" configuration

*Checked all the checkboxes in "wxWidgets Library Settings":

*

*Use wxWidgets DLL

*wxWidgets is built as a monolithic library

*Enable unicode
When I proceed, I get the following two warnings:

A matching Debug configuration cannot be found in the wxWidgets directory you specified.
This means that Debug targets of your project will not be built.
Are you sure you want to continue with these settings?

A matching Release configuration cannot be found in the wxWidgets directory you specified.
This means that Release targets of your project will not be built.
Are you sure you want to continue with these settings?

If I continue and try to compile my project, I get 3 of the following error:

C:\wxWidgets-3.2.1\include\wx\platform.h 159 fatal error: wx/setup.h: No such file or directory

I headed to C:\wxWidgets-3.2.1\include\wx and found that setup.h is missing: it's actually located in C:\wxWidgets-3.2.1\include\wx\msw (one folder deeper).
Any ideas on how to correctly setup wxWidgets to work with Code::Blocks?

A: Actually, using the Windows Installer only installed the source code. I had to build it myself:
cd /D C:\wxWidgets-3.2.1\build\msw

And then
mingw32-make -f makefile.gcc BUILD=release SHARED=1 MONOLITHIC=1 UNICODE=1 CXXFLAGS=-fno-keep-inline-dllexport 2>log.txt

After that, I followed the same steps above starting from step 4. The project is created without problems.
Next, since there's no entry for wxWidgets 3.2.x in Code::BLocks 20.03 (step 5 above), I had to change libwxmsw31u.a to libwxmsw32u.a under:

*

*Project > Build options > Debug > Linker settings

*Project > Build options > Release > Linker settings
Compiled and run the project, and it did work.
Setting up wxWidgets with Code::Blocks in Windows was of great help.


text:
Q: How to repeat variables in Visual Studio Snippet I would like to type the property name once for this snippet and have it fill in all three place holders. When I currently try this with Visual Studio, it only fills in the first variable. Is there a way to fill all three in by typing the name once?

                    @Html.LabelFor(model => model.$PropertyName$, htmlAttributes: new { @class = "" })

                    @Html.EditorFor(model => model.$PropertyName$, new { htmlAttributes = new { @class = "" } })
                    @Html.ValidationMessageFor(model => model.$PropertyName$, "", new { @class = "" })

And that property is defined above like
  <Declarations>
  <Literal>
    <ID>PropertyName</ID>
    <ToolTip>Name of the model property</ToolTip>
    <Default>Property</Default>
  </Literal>
</Declarations>

Is there a way to fill all three in by typing the name once?


text:
Q: Why isn't my solution to K&R exercise 2-3 working? I'm trying to solve exercise 2-3 in the book The C Programming Language, but my solution isn't working and I can't find out what I did wrong. The exercise says to write a function that takes a string containing a hexadecimal number and returns that number as an int.
Here is my code:
#include <stdio.h>
#include <ctype.h>
#include <math.h>

int htoi(char *s);

int main() {
    char s[5];
    scanf("%s", s);
    printf("%d", htoi(s));
}

int htoi(char *s) {
    int length, num = 0, i;
    char c = 'A';
    for (length = 0; c >= '0' && c <= '9' || c >= 'A' && c <= 'F'; length++)
        c = toupper(s[length]);
    for (i = 0; i <= length; i++) {
        c = toupper(s[i]);
        if (c >= '0' && c <= '9')
            num += (c - '0') * pow(16, length - i);
        else if (c >= 'A' && c <= 'F')
            num += (c - 'A' + 10) * pow(16, length - i);
    }
    return num;
}

Why isn't it working?

A: You need to change pow(16, length - i) to pow(16, length - i - 2).
"Why 2?" you may ask.
Well, you need to learn how to debug programs. First of, your length does not seem to be properly calculated. Print that value and you'll see that it is actually one more than expected. Usually, C-programmers do not count the '\0' terminator when talking about the length of a string, and the standard function strlen does not either.
So you should remove 1 from length after it is calculated. And then it will make sense. For instance, 4=4*10⁰ and 40=4*10¹. The digit on position n should be raised to the power n-1. After that you use pow(16, length - i - 1). Notice it's 1 instead of 2 when we have correct length.
Other comments on your code
Unless you have a specific reason to do so, I would not write a custom function to calculate the length. Instead, use strlen and check for correctness later. In this program it seems that you can assume that the string always will be correct. So I would have written it like this:
int htoi(char * s) {
    int length = strlen(s), num = 0, i;

    for (i = 0; i < length; i++) {
        int factor = pow(16, length - i - 1), digit;
        int c = toupper(s[i]);
        if (c >= '0' && c <= '9')
            digit = c - '0';
        else if (c >= 'A' && c <= 'F')
            digit = c - 'A' + 10;
        num += digit * factor;
    }
    return num;
}

I also refactored it a little bit.

A: There are multiple problems in your code:

*

*The buffer for input is too small and you do not pass its size to scanf(). If the user types more than 4 characters before the newline, you will have undefined behavior. It is much safer to use fgets() or at least specify the maximum number of characters to store with scanf("%4s", s).

*You should test the return value of scanf() to prevent undefined behavior on invalid input, such as when redirecting from an empty file.

*The first loop in htoi attempts to count the number of characters that are digits or letters between A and F, but it incorrect as it includes the first mismatched character in the computed length. Furthermore is has undefined behavior on platforms where char is signed by default if the user typed exotic characters such as é.

*relying on floating point arithmetic for this calculation is both wasteful and potentially incorrect. There is a much simpler method whereby you multiply the current value of num by 16 and add the value of the current hexadecimal digit. In your approach the factor should be pow(16, length - i -);iflength` had been computed correctly.

Here is a corrected version:
#include <ctype.h>
#include <stdio.h>

int htoi(const char *s);

int main() {
    char s[100];
    if (fgets(s, sizeof s, stdin))
        printf("%d\n", htoi(s));
    return 0;
}

int htoi(const char *s) {
    unsigned int num = 0;
    int i;
    for (i = 0; isxdigit((unsigned char)s[i]); i++) {
        if (c >= '0' && c <= '9')
            num = num * 16 + c - '0';
        else
            num = num * 16 + 10 + toupper(c) - 'A';
    }
    return num;
}


text:
Q: Extract datetime strings with datefinder matches = list(datefinder.find_dates(str(laslogsystime[0])))
if len(matches) > 0:
    date = matches[0]
    # print(date)

logging = re.findall(r'(.*?)', date)[0]
print(logging)

TypeError: expected string or bytes-like object

A: You must be trying to extract the strings that datefinder identifies as datetime strings.
You need no re.findall, you need to tell find_dates to return tuples containing both datetime and source strings by passing source=True argument:
import datefinder
from datetime import datetime

laslogsystime = "August 1990 some text May 21 2015"
matches = [src for time, src in datefinder.find_dates(laslogsystime, source=True)]
print(matches) # => ['August 1990', 'May 21 2015']


text:
Q: how to choose level shifters for serial / UART I have so far been using some MAX3323EEPE chips for shifting between 3.3V and 5V logics on serial / UART communications. This is quite some stuff to solder on a PCB, and the chip is a bit expansive. I only do quite vanilla communications, such as up to 57600, absolute max 115200 baud rate.
Would this kind of shield:
https://www.adafruit.com/product/757
do the trick?
And this kind?
https://www.adafruit.com/product/395

Edits

*

*Edit 1: typical use: I am thinking about having a project built around a 3.3V micro-controller, but I will need to be able to talk to some 5V logics stuff too. I will have a 5V step-up converter on the design, so getting 5V is not an issue. Typically, I will need to talk to a RockBLOCK 9603, which seems to be rather 5V than 3.3V ( https://www.rock7.com/products-rockblock-9603 though not completely clear to me if it would be ok to power with 5V and talk through 3.3 logics level; but other things will definitely need 5V logics levels anyways, so good to put on board).

A: What are you connecting your UART/serial comms to?
The MAX3323 uses external capacitors to generate +5V and -5V, and uses those supplies to convert signals from the low-voltage side into signals which transition between +5V and -5V. It only requires one low-voltage supply to do this.
The shield devices you link to require an external supply ( +5V ) to be used, and will then convert your low-voltage signals into signals which transition between +5V and 0V
The shields will require an additional 5V power supply - and if the device you are connecting to is expecting -5V levels, they won't work.
Edit for use with RockBlock 9603:
The Serial interface on this device looks like you may be ok with 3.3V levels only - in which case no interface would be needed

from here - https://www.rock7.com/products-rockblock-9603

A: yes, for such slow signals either kind would work.
Or you could use resistors for voltage drop and a TTL compatible buffer for the upwards shift.
but "rock7" says

There are various FTDI USB cables, the precise model used with our products is the TTL-232R-3V3, and it's available to purchase from our shop or from various electronics outlets globally.

https://docs.rockblock.rock7.com/docs/connectors
This implies that the rock block wants 3.3V signals for the UART,
so you don't need any level converter, just use wires.


text:
Q: Is there a way on Elasticsearch ingest-pipelines to use convert processor on multiple fields based on field name suffix? We have an index with default pipeline who converts a field to boolean, like documented here https://www.elastic.co/guide/en/elasticsearch/reference/7.10/convert-processor.html
We're using Elasticsearch v7.10.
Is there a way to create a pipeline to convert multiple fields based on field name suffix like '_b'?
Something like:
PUT _ingest/pipeline/string-to-bool
{
  "description": "converts fields ending in '_b' to boolean",
  "processors" : [
    {
      "convert" : {
        "field": "*_b",
        "type": "boolean"
      }
    }
  ]
}

A: Tldr;
As far as I know the convert processor does not allow fuzzy matching.
To workaround
As you proposed you could write a script doing the job.
PUT _ingest/pipeline/string-to-bool-script
{
  "processors" : [
    {
        "script": {
          "lang": "painless",
          "source": """
          for (key in ctx.keySet()) {
            if (key.endsWith("_b")) {
                ctx[key] = Boolean.parseBoolean(ctx[key]);
            }
          }
          """
        }
      }
  ]
}

POST /_ingest/pipeline/string-to-bool-script/_simulate
{
  "docs": [
    {
      "_index": "index",
      "_id": "id",
      "_source": {
        "plop_b": "true",
        "_b": "false"
      }
    }
  ]
}

Keep in mind this is very simplistic, and would only work for strings with value of true / false (not case sensitive).


text:
Q: Creating thousands of databases leads to out of memory issues I have a server running SQL server 2016, and I need to create around 6000 different databases.  I've created about 2000 so far, but the server will start throwing errors, all relating to the server being out of memory, such as:

Msg 701, Level 17, State 130, Line 8 There is insufficient system memory in resource pool 'internal' to run this query.

The code is written in c# using the Microsoft.SqlServer.Management.Smo library. In short, it's using SQLRestore to restore a backup of a "master" database to a new database with a different name.
After restarting the SQL Server service, I'm able to create 20 to 30 databases before encountering the same error.
How do I avoid this issue?
Some info about the server:

*

*Windows Server 2012 R2

*SQL Server 2016 13.0.4001.0 (x64)

*24 GB total ram, 16 GB allocated to SQL server

*This is a test server, the production server has considerably more RAM.  Each database is used to hold a different customer's data. This isn't a production server; it's a testing environment that we're using before going to production.

A: You are correct: having thousands of databases on your hardware won't work.
I understand that you're doing a proof-of-concept, but think about it differently.
If you're testing application logic or database maintenance, you don't need 6,000 databases on that server in order to do that level of testing. You should be able to get by with, say, 100.
If you're testing performance, you'll need to test on the kind of hardware that you'd be using in production. Even without end user queries, your simple regular background jobs of things like backups, stats updates, and checkdb will lead to dramatic performance issues.
If you're testing high availability with database mirroring or Always On Availability Groups, be aware that each additional database consumes resources even when it's not doing anything.


text:
Q: consolidate Array multiple sheets please advise how can i get to Dim sheets as at times there can be more than 300 sheets and not every sheet will have sheet name as (sheet4). i would have to consolidate the same array R10C1:R26C2
Sub Macro15()

Dim wb As Workbook
Dim ws As Worksheet
Dim ws2 As Worksheet
Dim arrRange()

Set wb = ThisWorkbook
Set ws = wb.ActiveSheet

arrRange = Array("Sheet4!R10C1:R26C2", "Sheet4 (2)!R10C1:R26C2", "Sheet4 (3)!R10C1:R26C2", _
"Sheet4 (4)!R10C1:R26C2", "Sheet4 (5)!R10C1:R26C2", "Sheet4 (6)!R10C1:R26C2", "Sheet4 (7)!R10C1:R26C2", _
"Sheet4 (8)!R10C1:R26C2", "Sheet4 (9)!R10C1:R26C2", "Sheet4 (10)!R10C1:R26C2", "Sheet4 (11)!R10C1:R26C2", _
"Sheet4 (12)!R10C1:R26C2", "Sheet4 (13)!R10C1:R26C2", "Sheet4 (14)!R10C1:R26C2")

Set ws2 = wb.Sheets.Add

With ws2
    .Range("A1").Consolidate arrRange, xlSum, True, True, False
End With

Application.ActiveWindow.SmallScroll Down:=-228
ws.Columns("A:A").ColumnWidth = 23.88
ws.Columns("A:A").ColumnWidth = 41.25
ws.Columns("A:A").ColumnWidth = 47.88
ws.Columns("B:B").ColumnWidth = 16.5

End Sub

A: Not tested : But you could try something like this to get the sheet names and and concatenate the range to it when the sheet name is copied into the array.
Dim sheets_Count As Integer
Dim sheets_Name() As String

sheets_Count = Sheets.Count

ReDim sheets_Name(sheets_Count)

For i = 1 To sheets_Count
    sheets_Name(i) = ActiveWorkbook.Sheets(i).Name
Next i

end sub

Hope it helps.


text:
Q: Facebook Graph API: how to add a caption to an image you upload? I am trying to post an image to an album on facebook and place a description with the image.
I can upload the image to an album, but i can't seem to add the description.
Here is the code I use:
// prepare the curl post fields
$batch = sprintf('[{"method":"POST", "relative_url":"%1$s/photos", "attached_files":"file1", "message":"caption"}]', $album_id);

$post_fields = array(
'batch' => $batch,
'access_token' => $access_token,
'file1' => '@' . $image_abs_path,
'caption' => 'image caption goes here"
);
$uri = 'https://graph.facebook.com';

$curl = curl_init( $uri );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl, CURLOPT_POST, TRUE );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $post_fields );

$raw_data = curl_exec( $curl );
curl_close( $curl );

$data = json_decode( $raw_data, $assoc = TRUE );

I also tried with a post-field called "name", but when I use this I get an empty array as a result. The image will not be added to the album when I use this post-field.

A: Try changing your $batch:

$batch = sprintf('[{"method":"POST", "relative_url":"%1$s/photos", "attached_files":"file1", "body" : "message=Your image caption"}]', $album_id);

Ref: Batch Upload
Hope it helps


text:
Q: Why page Load time 0 for most of the pages in GA? We are using google analytics in our application and getting strange results when tracking page load time. The data for most of the pages is 0 while few pages have the values. Now if we compare these pages with our qa sites , page load time has a value.
Nothing has changed on these pages when we move to production except that we have a different tracking code and the application is available publicly.
From screen shot below, you can see that we have data only for few days.

I am not sure what is happening here. Any pointers will be appreciated.
This is our code
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', "my-google-analytics-code", 'auto');
ga('send', 'pageview', {'page': (location.pathname+location.search+location.hash)});
</script>

A: Site speed is only tracked on 1% of visitors by default so it's likely nothing has been recorded yet for those pages, you can increase this by editing the ga('create' part of your code
ga('create', 'UA-XXXX-Y', {'siteSpeedSampleRate': 10})

https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#siteSpeedSampleRate


text:
Q: Regular expression for numbers in AngularJs I want to use regular expression in AngularJs that accept this three statement :
09344542525 -> 11 length integer that start with 09

02144532363 -> 11 length integer that start with 021

44532363 -> 8 length integer

Here is my HTML :

    <form novalidate name="cooperationForm" class="signinform">

            <input ng-model="restaurantInformation.tel" type="text" name="tel" id="tel" placeholder="phone number"
               ng-pattern="mobRegEx || prePhoneRegEx || phoneRegEx" class="form-control default-input singleline-input" required />

Wrong number format

    </form>

Angular:
app.controller('cooperationController', function ($scope) {
    $scope.mobRegEx = '/09[0-3][0-9]{8}/';
    $scope.prePhoneRegEx = '/021[0-9]{8}/';
    $scope.phoneRegEx = '[0-9]{8}';
    .
    .
    .
}

Actually , when my input is dirty and I test integer, error paragraph is always show error.
Any suggestion to modify regular expression?

A: All 3 combined:
/^(?:0(?:21|9[0-9]))?[0-9]{8}$/

Description

*

*^ matches the beginning of string

*(?:..)? is an optional group matching

*

*0(?:21|9[0-9]) literal 021 OR...

*09 and another digit

*[0-9]{8} 8 more digits

*$ matching the end of string as well.

Notice I added ^ and $ anchors to avoid matching a substring

A: You're trying to use multiple regular expressions in ng-pattern by separating them using pipes - that's not valid. As suggested in the answer here you should implement a custom directive (ng-phone-number?) or combine your multiple expressions into a single pattern.
Using a directive will probably be the most maintainable approach.

A:
var regExp = /(+09|021|44532363)\d{1,12}/g;
  var result = string.match(regExp);
  console.log(result)


text:
Q: Dropdownlist in Detailsview, not listing the items Hello Everyone
I have a detailsview, where there are 3 bound fields and a template field.
The template field has a DropDownList, which I have connected to an AccessDataSource.
But when I run, the dropdownlist has just the "System.Data.DataRowView" as it's items.
I wish to get the items from DB to be listed down in DropDownList
This is my code
asp:TemplateField HeaderText="State/Province" SortExpression="State/Province">
                            <EditItemTemplate>
                                <asp:DropDownList ID="ddlState" runat="server" DataSourceID="AccessDataSource1"
                                    onselectedindexchanged="DropDownList1_SelectedIndexChanged">
                                </asp:DropDownList>
                                <asp:AccessDataSource ID="AccessDataSource1" runat="server"
                                    DataFile="~/App_Data/db1.mdb"
                                    SelectCommand="SELECT [State/Province_name] FROM [State/Province_List ]">
                                </asp:AccessDataSource>
                            </EditItemTemplate>
                        </asp:TemplateField>

Should I add "DataBinding" or "DataBound" event for DropDownList?? to make it perfect?
Help me regarding this issue
Thanks,
Arjun

A: Define the filed to use in the drop down list
<asp:DropDownList ID="ddlState" runat="server"
   DataSourceID="AccessDataSource1"
   DataTextField="State/Province_name"
   DataValueField="State/Province_name"
   OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>

If you have problems with this non-standard column name, try to use an alias
SELECT [State/Province_name] AS StateProv FROM [State/Province_List ]

(Is the space in [State/Province_List ] OK?)
Then use this one
<asp:DropDownList ID="ddlState" runat="server"
   DataSourceID="AccessDataSource1"
   DataTextField="StateProv"
   DataValueField="StateProv"
   OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>


text:
Q: UITableView and a UITextField that is always visible I want to create an application which combines a chat feature. My question is this: how can I have a UITextField that is always visible in the same view as a UITableView?
The obvious solution would be to create my own UIView having a UITableView and a UITextField below it, however the UITableViewController doesn't seem to like me doing that as it expects the connected "view" outlet to be a UITableView, essentially destroying my plans.
Anyone with an idea?

A: I would suggest sticking a regular view in between your controller and your smaller "half-views". That has usually cleared things up for me, or at least exposed what the problem might be.

A: Don't use UITableViewController. After all, it's just a standard controller with a full-screen UITableView. You can roll your own easily.
Use a standard UIViewController and have it implement UITableViewDelegate and UITableViewDataSource protocols (you don't need to implement every method -- just the required ones). Then give it a UITableView as an iVar and set the delegate and dataSource to self. Size it so it only takes half the screen and your other views take the other part. You can lay out the whole thing in IB or create and position view+table manually.

A: If you don't need functionality that UITableViewController provided, than you can just use
UIViewController with <UITableViewDataSource, UITableViewDelegate> protocols.
So, your main viewController will accept any type of views.


text:
Q: Placing Osmdroid Mapview inside Dialog This doesn't seem to work. I ran into a similar issue in the google group from way back (sept. 2011) which describes it pretty well:
What steps will reproduce the problem?
1. Create own DialogPreference
2. override onCreateDialogView
3. return a MapView instance
What is the expected output? What do you see instead?
Expected: MapView inside Dialog.
Instead: Just OK/Cancel Buttons
But there was no answer.
Anyone has any idea?
Thanks


text:
Q: Size of a FILE ADDRESS in c++ How does one determine the sizeof a pos_type or offset_type such as is used in c++ stream i/o.  You can't just write sizeof(pos_type) or sizeof(basic_streambuf::pos_type) because it is defined somehow inside a template that ... well, it's pretty complex.
It would be nice to know this at compile time.
BTW, there is a type called "streamsize" that seems to fit the bill, but sizeof(streamsize) is not a valid preprocessor term.

A: You need to use sizeof on an instantiation of the template. sizeof(ifstream::pos_type)

A: basic_streambuf is a template class. It is not fully defined until you use it. Use sizeof for members of template specialization, e.g. for streambuf::pos_type.


text:
Q: Why can't I call a mutable method (and store the result) twice in a row? In the following example:
struct SimpleMemoryBank {
    vec: Vec<Box<i32>>,
}

impl SimpleMemoryBank {
    fn new() -> SimpleMemoryBank {
        SimpleMemoryBank{ vec: Vec::new() }
    }

    fn add(&mut self, value: i32) -> &mut i32 {
        self.vec.push(Box::new(value));
        let last = self.vec.len() - 1;
        &mut *self.vec[last]
    }
}

fn main() {
    let mut foo = SimpleMemoryBank::new();

    // Works okay
    foo.add(1);
    foo.add(2);

    // Doesn't work: "cannot borrow `foo` as mutable more than once at a time"
    let one = foo.add(1);
    let two = foo.add(2);
}

add() can be called multiple times in a row, as long as I don't store the result of the function call. But if I store the result of the function (let one = ...), I then get the error:
problem.rs:26:15: 26:18 error: cannot borrow `foo` as mutable more than once at a time
problem.rs:26     let two = foo.add(2);
                            ^~~
problem.rs:25:15: 25:18 note: previous borrow of `foo` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `foo` until the borrow ends
problem.rs:25     let one = foo.add(1);
                            ^~~
problem.rs:27:2: 27:2 note: previous borrow ends here
problem.rs:17 fn main() {
...
problem.rs:27 }
              ^
error: aborting due to previous error

Is this a manifestation of issue #6393: borrow scopes should not always be lexical?
How can I work around this? Essentially, I want to add a new Box to the vector, and then return a reference to it (so the caller can use it).

A: This is exactly the problem that Rust is designed to prevent you from causing. What would happen if you did:
let one = foo.add(1);
foo.vec.clear();
println!("{}", one);

Or what if foo.add worked by pushing the new value at the beginning of the vector? Bad things would happen! The main thing is that while you have a borrow out on a variable, you cannot mutate the variable any more. If you were able to mutate it, then you could potentially invalidate the memory underlying the borrow and then your program could do a number of things, the best case would be that it crashes.

Is this a manifestation of issue #6393: borrow scopes should not always be lexical?

Kind of, but not really. In this example, you never use one or two, so theoretically a non-lexical scope would allow it to compile. However, you then state

I want to add a new Box to the vector, and then return a reference to it (so the caller can use it)

Which means your real code wants to be
let one = foo.add(1);
let two = foo.add(2);
do_something(one);
do_something(two);

So the lifetimes of the variables would overlap.
In this case, if you just want a place to store variables that can't be deallocated individually, don't overlap with each other, and cannot be moved, try using a TypedArena:
extern crate arena;

use arena::TypedArena;

fn main() {
    let arena = TypedArena::new();
    let one = arena.alloc(1);
    let two = arena.alloc(2);

    *one = 3;
    println!("{}, {}", one, two);
}


text:
Q: Enable Tablet Mode on Windows 10 through Code? Ive read various way on how to detect if a Windows 10 device is in Tablet Mode, most notably the topic below;
How can I detect when Window 10 enters tablet mode in a Windows Forms application?
I would like to enable/disable Tablet Mode through code (.Net C#) but I cant find any resources to achieve this. Ive tried changing the registry key and sending a HWND_BROADCAST that a change has occurred but this doesn't initiate the change to tablet mode.
Ive also tried using Spy++ style applications but cant see the messages being sent.
Does a method exist to do this?

A: There is no real way to do this in C#. Of course you can change the registry key, but you will need a log off/on to change from or to tablet mode.
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\ImmersiveShell\TabletMode

Enable: 1 or disable 0
Since I had a problem that my WPF-App will not appear on startup with tablet mode on, I used a AutoHotKey script.
You can create a .exe as well.
Source: https://autohotkey.com/boards/viewtopic.php?t=15619
#NoEnv
SetBatchLines -1
ListLines Off
#NoTrayIcon

TABLETMODESTATE_DESKTOPMODE := 0x0
TABLETMODESTATE_TABLETMODE := 0x1

TabletModeController_GetMode(TabletModeController, ByRef mode) {
    return DllCall(NumGet(NumGet(TabletModeController+0),3*A_PtrSize), "Ptr", TabletModeController, "UInt*", mode)
}

TabletModeController_SetMode(TabletModeController, _TABLETMODESTATE, _TMCTRIGGER := 4) {
    return DllCall(NumGet(NumGet(TabletModeController+0),4*A_PtrSize), "Ptr", TabletModeController, "UInt", _TABLETMODESTATE, "UInt", _TMCTRIGGER)
}

ImmersiveShell := ComObjCreate("{C2F03A33-21F5-47FA-B4BB-156362A2F239}", "{00000000-0000-0000-C000-000000000046}")
TabletModeController := ComObjQuery(ImmersiveShell, "{4fda780a-acd2-41f7-b4f2-ebe674c9bf2a}", "{4fda780a-acd2-41f7-b4f2-ebe674c9bf2a}")

if (TabletModeController_GetMode(TabletModeController, mode) == 0)
    TabletModeController_SetMode(TabletModeController, mode == TABLETMODESTATE_DESKTOPMODE ? TABLETMODESTATE_TABLETMODE : TABLETMODESTATE_DESKTOPMODE)

ObjRelease(TabletModeController), TabletModeController := 0
ObjRelease(ImmersiveShell), ImmersiveShell := 0 ; Can be freed after TabletModeController is created, instead

A: Poke around in here - You will want to focus on the samples for user interaction mode.
NOTE: This is for UWP (Universal Windows Platform), aka Windows 10+, and you will need code for other versions of Windows if you are not targeting Win 10 only.


text:
Q: How to receive BigQuery SELECT instruction result faster? I use Google.Cloud.BigQuery.V2 (2.3.0) and this code to make queries:
GoogleCredential gc = GoogleCredential.FromFile(bq_json_path);
BigQueryClient bq_client = BigQueryClient.Create(bq_project_id, gc);
string query = "SELECT " + columns2select + " FROM " + project_dataset_table + ";";
BigQueryResults bqr = bq_client.ExecuteQuery(query, parameters: null);

IEnumerator<BigQueryRow> itr = bqr.GetEnumerator();

while(itr.MoveNext())
{
    //do something (even if I comment it and do nothing, it save only 2 seconds)
}

That way it process 100k rows for 26 seconds. That's ultimate slow.
I tried using bqr.ReadPage(100000);, but it also took ~26 seconds to retrieve the rows just by that call.
I doing the program to transfer data from BigQuery into ClickHouse for DataLens analysis purpose. And 100k rows insertion into cloud hosted ClickHouse (not on my local PC) takes just 1-2 seconds. That's weird imbalance. I think selecting rows should be way more faster.
P.S. 100k rows per 26 seconds is not a problem... The problem is that I need to transfer many tables with ~60 millions records and some tables can have even 1 billion of records.


text:
Q: программа, которая считывает три целых числа и выводит истину, если ровно одно число положительно Напишите программу, которая считывает три целых числа и выводит истину, если ровно одно число положительно (т.е.> 0).
В противном случае он должен напечатать false.
import java.util.Scanner;

  class Main {
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int a = scanner.nextInt();
    int b = scanner.nextInt();
    int c = scanner.nextInt();
    boolean res =(a>0)&&(b<=0)&&(c<=0)||(c>0)&&(a<=0)&&(b<=0)||(b>0)&&(a<=0)&&(b<=0);
    System.out.println(res);
}
}

Но если к примеру ввести числа: 0 2 0, то программа работать не будет. Подскажите, как исправить выражение,чтобы все работало нормально.

A: Вообще у вас ошибка вот тут
(b>0)&&(a<=0)&&(b<=0)

Вы b проверяете 2 раза, а с не проверяете совсем.
Чтобы не писать трехэтажные выражения, как вариант
import java.util.Scanner;

  class Main {
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int a = scanner.nextInt();
    int b = scanner.nextInt();
    int c = scanner.nextInt();
    int count = 0;
    if (a > 0) count++;
    if (b > 0) count++;
    if (c > 0) count++;
    boolean res = count == 1;
    System.out.println(res);
}
}


text:
Q: HA Proxy - Stopping/Queueing duplicate web request I am using HA Proxy for load balancing purpose. I have two servers (S1) and (S2) getting requests from devices via HA proxy.
Number of devices is more than 2000.
Those devices sending multiple requests (download an item) to HA proxy and HA proxy forwarding those requests to S1 & S2.
The problem is if a device1 (D1) send a request to download a item (image/movie) and response takes time because of downloading the item; meanwhile device2 (D2) boots up and send the same request to download and again this request lands to server (S1 or S2) via HA Proxy and download start happening, since download still in progress, a device3 (D3) boots up and send the same request to download. Like this all devices are start sending same request to download the same content loading my servers (S1 & S2) hugely.
What i need is some how, if we can stop the same download request to get  forwarded by HA Proxy to Servers (S1 or S2).
My intention to find a solution at HA Proxy level to stop sending the same requests again and again. If one request is still in progress then, all subsequent same request either queued or discared by HA Proxy.
Please help.

A: That is really an application design problem. You could split the download requests out to a different IP i.e. downloads.myapp.com and set maxconn=1 i.e. 1 request at a time?
Or you could balance on URL so the same download request goes to the same application server:
But it sounds like you just need in memory caching of content or more servers or faster I/O.


text:
Q: Passing page anchors to a new page without using URL I'm currently trying to pass a page anchor from one page, to another, to have the second page scroll smoothly to the correct div.
Currently the second part of the desired feature works, but I'm looking for a way to pass the anchor to the second page without it appearing in the URL.
So for example, instead of having
www.example.com/blog#features

The anchor tag #features, could be passed somehow to the blog page and scroll correctly without it appearing in the URL.
Is this possible with jQuery or some form of Ajax style request?

A: try to use localStorage for example http://devdocs.io/dom/window/localstorage
window.localStorage.setItem('id_of_element_to_scroll', '#example-div');

Then you could read from it and scroll into view.
$(document).ready(function () {
  var idToScroll = localStorage.getItem('id_of_element_to_scroll');
  $('html, body').animate({
    scrollTop: $(idToScroll).offset().top
  }, 200); // with animation
})


text:
Q: rotate ggplot2 maps to arbitrary angles Similar to ggplot2: How to rotate a graph in a specific angle?, but I don't want the image/square rotated, I'd like the data rotated within the frame.
For instance, if I start with this:
library(ggplot2)
usa <- maps::map('usa', plot=FALSE)

ggplot(as.data.frame(usa[c("x","y")]), aes(x,y)) +
  coord_quickmap() +
  geom_path()

I'd like to be able to generate this:

*

*Rotation needs to preserve aspect-ratio of the spatial data

*I need to support arbitrary rotation, not constrained by 90-degree jumps

*I'd like if the actual grid can be retained (to preserve the default behaviors within ggplot2), but if not I can generate them manually

*I'd like the enclosing rectangle of the generic plot to be unchanged, including (not shown here) titles and subtitles

*I'd like it if the coordinate system is unchanged, meaning that I can add other layers that will subsequently automatically appreciate the rotation. @qdread's answer gives the alternative to this, where a single function can calculate the rotation (though I don't know how to do this mathematically with spatial data)

*Please disregard:

*

*the grid problems in the top-left corner, my photoshopping was incomplete

*the x-axis labels, the numbers are wrong (y-axis is good-ish) (they can be removed, not required)

I wonder if this can be accomplished with CRS/projections, but I'm not smart enough on them to work with it formally/correctly.

A: edit2:
Using the oblique mercator projection to rotate a map:
#crs with 45degree shift using +gamma
# lat_0 and lonc approximate centroid of US
crs_string = +proj=omerc +lat_0=36.934 +lonc=-90.849 +alpha=0 +k_0=.7 +datum=WGS84 +units=m +no_defs +gamma=45"

# states data & libraries in code chunk below
ggplot(states) +
    geom_sf() +
    geom_sf(data = x, color = 'red') +
    coord_sf(crs = crs_string,
             xlim = c(-3172628,2201692),    #wide limits chosen for animation
             ylim = c(-1951676,2601638)) +  # set as needed
    theme_bw() +
    theme(axis.text = element_blank())

Animation of gamma from 0:360 in 10deg increments, alpha constant at 0. The artifacts are from gif compression, actual plots look like the one above labelled gamma 45.

earlier answer:
I think you can 'rotate' the plot (including graticules) by 'looking' at the earth from a different perspective by changing the projection to a Lambert azimuthal equal area and adjusting +lon_0=x in the projection string.
This should meet most of your goals, but I don't know how to get an exact rotation in degrees.
Below I've transformed the states_sf sf object manually before plotting.  It may be easier to transform the plot (and all the sf data being plotted) by working with crs 4326 for the data, and adding + coord_sf(crs  = "+proj=laea +x_0=0 +y_0=0 +lon_0=-140 +lat_0=40") to the end of the ggplot() + call.
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
library(urbnmapr)
library(tidyverse)

# get sf of the us, remove AK & HI,
#  transform to crs 4326 (lat & lon)
  states_sf <- get_urbn_map("states", sf = TRUE) %>%
    filter(!state_abbv %in% c('AK', 'HI')) %>%
    st_transform(4326)

  #centroid of us to 'look' at the US from directly above the center
  us_centroid <- st_union(states_sf) %>% st_centroid() %>% st_transform(4326)

  st_coordinates(us_centroid)
#>           X        Y
#> 1 -99.38208 39.39364

# Plots, changing the +lon_0=xxx of the projection
  p1 <- states_sf %>%
  st_transform("+proj=laea +x_0=0 +y_0=0 +lon_0=-99.382 +lat_0=39.394") %>%
  ggplot(aes()) +
  geom_sf(fill = "black", color = "#ffffff") +
    ggtitle('US from above its centroid 39.3N 99.4W')

  p2 <- states_sf %>%
    st_transform("+proj=laea +x_0=0 +y_0=0 +lon_0=-70 +lat_0=40") %>%
    ggplot(aes()) +
    geom_sf(fill = "black", color = "#ffffff") +
    ggtitle('US from 40N 70W')

  p3 <- states_sf %>%
    st_transform("+proj=laea +x_0=0 +y_0=0 +lon_0=-50 +lat_0=40") %>%
    ggplot(aes()) +
    geom_sf(fill = "black", color = "#ffffff") +
    ggtitle('US from 40N 50W')

  p4 <- states_sf %>%
    st_transform("+proj=laea +x_0=0 +y_0=0 +lon_0=-30 +lat_0=40") %>%
    ggplot(aes()) +
    geom_sf(fill = "black", color = "#ffffff") +
    ggtitle('US from 40N 30W')

  p5 <- states_sf %>%
    st_transform("+proj=laea +x_0=0 +y_0=0 +lon_0=-10 +lat_0=40") %>%
    ggplot(aes()) +
    geom_sf(fill = "black", color = "#ffffff") +
    ggtitle('US from 40N 10W')

  p6 <- states_sf %>%
    st_transform("+proj=laea +x_0=0 +y_0=0 +lon_0=-140 +lat_0=40") %>%
    ggplot(aes()) +
    geom_sf(fill = "black", color = "#ffffff") +
    ggtitle('US from 40N 140W')

 p1

 p3

 p5

 p6

Created on 2021-03-31 by the reprex package (v0.3.0)
edit:
It looks like you can get any angle with a combination of alpha and gamma when using the projection "+proj=omerc +lonc=-90 +lat_0=40 +gamma=0 +alpha=0".  I don't know exactly how they relate (something to do with azimuths), but this should help visualize it:
# Basic template for rotating, keeping US map centered.
#  adjust alpha and gamma by trial & error
crs <- "+proj=omerc +lonc=90 +lat_0=40 +gamma=90 +alpha=0"

 states_sf %>%
   ggplot() +
   geom_sf(fill = 'green') +
   coord_sf(crs = crs)

Animation of a broader range of alpha & gamma can be found here.

A: In order to preserve the shape of the map when we rotate, we first need to transform from lat-long to a conformal coordinate system where local angles are preserved. We will use a Lambert conformal conic projection, specifically ESRI:102004 for contiguous USA. We coerce the usa object to a sf object and apply the CRS transformation.
lambert_proj4 <- '+proj=lcc +lat_1=33 +lat_2=45 +lat_0=39 +lon_0=-96 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs'

library(sf)

usa_trans <- usa %>%
  st_as_sf %>%
  st_transform(crs = lambert_proj4)

The result looks like this:
ggplot(usa_trans) + geom_sf()

Next we modify the procedure in the sf documentation on affine transformations to rotate the geometry around its centroid.
The following function defines the transformation matrix.
rot = function(a) matrix(c(cos(a), sin(a), -sin(a), cos(a)), 2, 2)

Extract the geometry from the transformed object and then get the centroid. This will return ten points because there are 9 large islands included in addition to the mainland. (e.g. Long Island).
usa_geom <- st_geometry(usa_trans)
usa_centroid <- st_geometry(st_centroid(usa_trans))

Therefore we take usa_centroid[1,] which is the centroid of the mainland polygon, subtract it, apply the rotation of 45 degrees counterclockwise, and add back the centroid.
usa_rot_geom <- (usa_geom - usa_centroid[1,]) * rot(-45 * 2*pi/360) + usa_centroid[1,]

The result looks like this:
ggplot(usa_rot_geom) + geom_sf()

Finally if desired you can back-transform to lat-long again before plotting.
usa_rot_latlong <- usa_rot_geom %>%
  st_set_crs(lambert_proj4) %>%
  st_transform(4326) %>%
  st_as_sf

Result:
ggplot(usa_rot_latlong) + geom_sf()


text:
Q: how to group products dynamicaly and add same product separately into the cart page? I have some products which are selected on front end by the customer and want to make the group of that selected product and add to cart as a single view.
 How to add same product separately into the cart page?
example of cart view page which I want after adding the selected product to cart:
grouped productname 1
selected product1
selected product2
selected product3 selected product2 X 3 qty
selected product4 selected product2 x 3 qty
Total -25874
QTY- 1
grouped productname2
selected product6
selected product2
selected product8 selected product2 X 3 qty
selected product9 selected product2 x 3 qty
Total -85745
QTY- 1
 Give me some solution.


text:
Q: setting div height 100% giving strange result? I have got three child div (placed next to each otehr) in one parent dive. The first child div has some content in it and stretches as per its content length. The other two child div has no content in them, and I want them to have same height like the first child div.
After reading in articles on net, I set the height=100% of html, body, parent and second & third child div. Now when I check in browser, the height of html, body and child divs exceeding the height of first child div in normal view. And if I open the inspect element window, then height of html, body and child divs goes lesser than first child div. The margin of difference of height in both view is approx of 30%.
I'm using skeleton framework. Please help.
<------- code added below ------->
I added following lines in layout css:
html {
    height: 100%;
 }

body {
   height: 100%;
 }

.main { <!--class name applied to container or parent div -->
   height: 100%;
 }

.first-child, .second-child, .third-child { <!--class name given two three divs from left to right-->
   height: 100%;
 }

Apart this, I added respective class names to respective divs in html.

A: The inspect element panel decreases the size of the browser window. Since you are using a percentage of the window as the height, you are altering the 2nd and 3rd divs as well as the html, body, and parent; but not the first child div.


text:
Q: `data` is not available in the `created` method of vue.js I am trying to access component data from within my created() method, but it seems unavailable (undefined). How can I access the data then?
<script>
import MainLayout from './MainLayout.vue'
import axios from 'axios'

export default {
  components: { MainLayout },
  data: {
    loading: false,
    mytest: 123,
    table: {
      columns: [],
      data: [],
      total: 0,
    }
  },
  name: 'Entities',
  created: async function() {
    console.log(this.loading, this.table, this.mytest) // undefined, undefined, undefined

  },
}
</script>

A: Use the method mounted() instead.

A: vuejs official doc here when you are using .vue single compoent then data should be a function it should return the data, if you use vue in normal html inside script tag then you can use data as object

A: Still not sure why it worked, but turning data from an object into a function worked:
 data: function () {
    return {
      loading: false,
      mytest: 123,
      table: {
        columns: [],
        data: [],
        total: 0,
      }
    }
  },

A: I think it is precaution of Vue.js - data property must be function -
so if using data property as object not a function that returning every new object, vue show you error message

A: only when the component mounted could the data itself be accessed.
so if you want access data , you should wait util the component mounted, place the code into mounted lifecycle for example.


text:
Q: Logback log to multiple files with a common module I know that it is possible to log to multiple files based on a package. My question is slightly different. Given the following packaging:
 - foo.bar.moduleA
 - foo.bar.moduleB
 - foo.bar.commonModule

In this scenario, moduleA and moduleB have code that is called from the commonModule. The problem I have is that I get two log files that only contain logging from moduleA or only logging from moduleB. I know this is because of the package level logging I am using but I don't know how to expand it to say log everything from this package and any other packages that are called later on in this thread. Hopefully that makes sense. Thanks for any help.

A: I think you can do it using MDC, but you'll need to instrument your code, when your start your moduleA or moduleB thread so that it put something in the MDC:
MDC.put("module", "moduleA"); // or B

You can then put %X{module} to your pattern and filter thing using grep/whatever, or you can use SiftingAppender and MDCBasedDiscriminator. There is an example in this page.


text:
Q: Get a list of inventory hostnames host1: abc
host2: xyz

host1 and host2 are listed under test-hosts
[test-hosts]
abc
xyz

When i debug for inventory_hostnames, i see them like below
    > TASK [debug inventory_hostname]
    > *************************************************************************************************************************************************************************
ok: [abc] => {
    >     "inventory_hostname": "abc" }
ok: [xyz] => {
    >     "inventory_hostname": "xyz" }

Is there any way we can gather inventory_hostname's like a list by assigning it to a variable.
Expected result:
exp_result: [abc, xyz]

A: You can use groups['test-hosts'] to get those hosts as a list.
For example:
---
- hosts: all
  gather_facts: false
  tasks:
    - set_fact:
        host_list: "{{ groups['test-hosts'] }}"
    - debug:
        msg:  "{{host_list}}"

A: You can also use the variable inventory_hostnames if you want to select multiple groups or exclude groups with patterns.
In these examples, we're selecting all hosts except ones in the www group.
Saving the list of hosts as a variable for a task:

- debug:
    var: hostnames
  vars:
    hostnames: "{{ query('inventory_hostnames', 'all:!www') }}"

You can also use the lookup plugin to loop over the hosts that match the pattern. From the docs:
- name: show all the hosts matching the pattern, i.e. all but the group www
  debug:
    msg: "{{ item }}"
  with_inventory_hostnames:
    - all:!www


text:
Q: remapping and grouping repeated values from an array in php I am trying to remap an response from a query to the database and group like items in one array.  for example, from this example below.
Response:
[
    "Location"=> "City 1",
    "AptDate"=> "2020-09-16",
    "AptTime"=> "11:00",
    "AptLength"=> "45",
    "AptStatus"=> "1",
    "Operatory"=> "1 RECALL",
    "OperatoryNum"=> "2"
],
[
    "Location"=> "City 2",
    "AptDate"=> "2020-09-16",
    "AptTime"=> "09:00",
    "AptLength"=> "45",
    "AptStatus"=> "1",
    "Operatory"=> "1 RECALL",
    "OperatoryNum"=> "2"
],
[
    "Location"=> "City 1",
    "AptDate"=> "2020-09-16",
    "AptTime"=> "12:00",
    "AptLength"-> "45",
    "AptStatus"=>"1",
    "Operatory"=> "1 RECALL",
    "OperatoryNum"=> "2"
[,

looping through results:
           $remappedData=[];
                foreach ($result as $value)
                {
                    $remappedData[] = [
                        'location' => $value['Location'],

                        // And so on
                    ];

                }

}

This doesnt really give me what i need as I am trying to group the array based on Location and add the AppDate base on that location.  Something like this.
    {
        "Location": "City 1",
        "AptDate": ["2020-09-16","2020-09-16"],
        "AptTime": ["11:00","12:00"],
        "AptLength": ["45","45"],
        "AptStatus": ["1","1"],
        "Operatory": ["1 RECALL","1 RECALL"],
        "OperatoryNum": ["2","2"]
    },
    {
        "Location": "City 2",
        "AptDate": ["2020-09-16"],
        "AptTime": ["09:00"],
        "AptLength":[ "45"],
        "AptStatus": ["1"],
        "Operatory": ["1 RECALL"],
        "OperatoryNum": "2"
    },

A: So based on your scenario, you want grouping on Location and group all other attributes by keeping them in array.
foreach ($result as $value)
{
   $remappedData[$value['Location']]['location'] = $value['Location'];
   $remappedData[$value['Location']]['AptDate'][] = $value['AptDate']; // Notice we're creating an array here.
   $remappedData[$value['Location']]['AptTime'][] = $value['AptTime'];
   // so on all other attributes which needs to be grouped.
}

Note: Here we've created index as Location. If we don't want Location as key, we want as array(may be for frontend) use below code.
$temp = [];
$remappedData=[];
$intCurrentIndex = -1;

foreach ($result as $value)
{
    if(isset($temp[$value['Location']])){
         $oldIndex = $temp[$value['Location']];
         $remappedData[$oldIndex]['AptDate'][] = $value['AptDate'];
         $remappedData[$oldIndex]['AptTime'][] = $value['AptTime'];
    }
    else{
          $temp[$value['Location']] = ++$intCurrentIndex;
          $remappedData[$intCurrentIndex]['location'] = $value['Location'];
          $remappedData[$intCurrentIndex]['AptDate'][] = $value['AptDate'];
          $remappedData[$intCurrentIndex]['AptTime'][] = $value['AptTime'];
    }

}


text:
Q: XMLRPC Python server I'm working on a project that has a XML-RPC PHP client connecting to a python server. I got the PHP client to work but don't know how the python server takes input parameters. From the PHP client we send a message with a string and two integer and want the python server to use those values to perform calculations.
How does XML-RPC servers in python take in values sent from the client?
Thanks!

A: You can check xmlrpclib for python implementation of this standard.
Here a server side example from there:
from SimpleXMLRPCServer import SimpleXMLRPCServer

def is_even(n):
    return n%2 == 0

server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(is_even, "is_even")
server.serve_forever()


text:
Q: unit testing REST client -- mock the service I am trying to test REST client functionality when the response status indicates error. So I want to mock the rest service to return an error code (like 404) and test that the client is handling the error cases correctly. Is there a way to mock the service?

A: Try Mockito
It's a nice mocking framework for Java

A: Try to use Spring MVC Test Support.

A: mockito is a good choice for unit testing.
If you are interested in automated integration testing you might wanna try some webservice mocking tool, such as this one:
https://sourceforge.net/p/soaprest-mocker
You can set response code and/or response body on mock, execute your request against the mock and verify request(s) that reached the mock.


text:
Q: Enter Data Feature In PowerBI We have a table in PowerBI Model which was created as 'Enter Data' directly into PBIX file and published in Powerbi Service.
in case if there are any data updates that needs to be done in that table, is it possible to update it from app.powerbi.com or one needs to update the data in PBIX within Powerbi desktop and publish the report

A: For items created by the 'Enter Data' function they will have to be updated in PBI Desktop then uploaded. This may not apply to you if you know this already, but I've seen people delete the Entered Data table and redo it. You can go into the Query Editor and click on the 'source' gear icon and it allows you to update/add/delete data.

For static tables, that you would like to be able to update in the service, rather than the desktop, you do have the option of creating a Dataflow 'Blank Table'.

This works as an Entered Data table, but is only in the service. You can connect your desktop report to it, and load it that way, and will save you having to reload the report every time your static data changes


text:
Q: Connection with mySQL from JAVA in Linux I have a problem with the connection to mySQL from Java. I am using Linux with NetBeans, and I downloaded the specific driver. I have mySQL in xampp.
My code is:
try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection c = DriverManager.getConnection(
           "jdbc:mysql://localhost:3306/nombreBaseDatos",
           "user",
           "pass"
     );
} catch (ClassNotFoundException ex) {
    Logger.getLogger(BD1.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
    Logger.getLogger(BD1.class.getName()).log(Level.SEVERE, null, ex);
}

And the error I get is this:

com.mysql.jdbc.CommunicationsException: Communications link failure
  due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.ConnectException MESSAGE: Conexión rehusada
STACKTRACE:
java.net.ConnectException: Conexión rehusada at
  java.net.PlainSocketImpl.socketConnect(Native Method) at
  java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
  at
  java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
  at
  java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
  at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at
  java.net.Socket.connect(Socket.java:579) at
  java.net.Socket.connect(Socket.java:528) at
  java.net.Socket.(Socket.java:425) at java.net.Socket.(Socket.java:241)
  at
  com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
  at com.mysql.jdbc.MysqlIO.(MysqlIO.java:271) at
  com.mysql.jdbc.Connection.createNewIO(Connection.java:2771) at
  com.mysql.jdbc.Connection.(Connection.java:1555) at
  com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
  at java.sql.DriverManager.getConnection(DriverManager.java:571) at
  java.sql.DriverManager.getConnection(DriverManager.java:215) at
  bd.pkg1.BD1.main(BD1.java:25)
** END NESTED EXCEPTION **
Last packet sent to the server was 1 ms ago. at
  com.mysql.jdbc.Connection.createNewIO(Connection.java:2847) at
  com.mysql.jdbc.Connection.(Connection.java:1555) at
  com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
  at java.sql.DriverManager.getConnection(DriverManager.java:571) at
  java.sql.DriverManager.getConnection(DriverManager.java:215)

Can somebody help me make this connection?

A: This would suggest to me that MySql is not accepting connections at localhost:3306
Is this the case ? Does a simple
telnet localhost 3306

connect to a receiving port on your machine ? Do you need to configure MySql for such connections ?


text:
Q: R how to match a data with dot inside and also set boundaries I am using grepl and str_detect to match with data but the some variables have a dot inside, some not, I don't know which has which not. also we need to set a boundary $ at the end.
e.g.
query<-c("3.2","345","1.5","23")
data<-c("342","3.2","34","1.5","165","234","345")

so, if data[which(grepl(x=data,pattern="3.2",value=TRUE)]
we can get 3.2, but if pattern is 23, we will get both 23 and 234
so I use data[which(grepl(x=data,pattern="23$")]
we can get 23 without 234, but if pattern is 3.2, we will get 3.2 and 342.
how to meet these two standard at the same time?

A: You can use \\. to specify the . in your code. If you're looking for any string that ends in 3.2, the below code would work:
vec <- c('342','3.2','34','1.5','165','234','345', '3.22', '193.2', '232')

> grep(pattern = '.*3\\.2$', x = vec, ignore.case = T, value = T)
[1] "3.2"   "193.2"

you can read more on the expressions at: https://cran.r-project.org/web/packages/stringr/vignettes/regular-expressions.html