text:
Q: school project; UDP connection to open/ close a hatch door this is my first post here so please forgive me  if I have put this in the wrong section.
For our school project, i want to open/ close a door by an Android Tablet. For the connection with the ecu of our door i have a can-wlan modul from avisaro.
The problem is that i am not an expert in programming android applications, i dont know anything about it.
from a former projekt i got this UDP THread (UDP_Verbindung ja va)
can someone help me combine the UDP Thread with the layout, which you can see down here?
CAN data byte output should look like this:
button "Öffnen" (open), 13. byte: {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
button "Schließen"(close), 14.byte:{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
button "STOP", 15. byte:{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
Progressbar ("Heckklappengeschwindigkeit"), 16. byte, value: 50...100
UDP_Verbindung.java:
    public class UDP_Verbindung implements Runnable{

        private static final String TAGUDP = "UDP";
        final int UDP_Target_Port = 12345;
        private Thread threadUDP = null;
        private boolean isrunning = false;
        private DatagramSocket udpSocket = null;
        byte[] buffin = new byte[28];
        byte[] buffout = {0, 0, 0, 0, 0, 0, 8, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        DatagramPacket in = new DatagramPacket(buffin,buffin.length);
        DatagramPacket out = new DatagramPacket(buffout,buffout.length);
        int CAN_ID;
        int CAN_Length;
        private int udpStatus = 0;
        private Handler uiHandler = null;
        private int sendFlag = 0;
    String ip = "168.192.0.74";
    InetAddress addr = intToInetAddress(ipStringToInt( "192.168.0.74"));
    public int receive = 1;
    private Set<String> listenToIds;

    public UDP_Verbindung(Handler uiHandler) {
        this.uiHandler = uiHandler;
        listenToIds = Collections.<String>emptySet();
    }

    public void setMessages(Set<String> messages){
        listenToIds = messages;
        Log.d(TAGUDP, "New Message IDs to listen to: ");
        for(String strId: listenToIds) {
            Log.d(TAGUDP, strId);
        }
    }

    @Override
    public void run() {

         try
            {
             Log.d(TAGUDP,"Verbindungsaufbau");
             udpSocket = new DatagramSocket(UDP_Target_Port);
             udpSocket.setSoTimeout( 3000 );
            } catch (SocketException ex)
            {
                ex.printStackTrace();
                Log.d(TAGUDP,"Verbindungsaufbau fehlgeschlagen");
                this.stop_service();

            }

            udpStatus = 1;
            Message msg1 = new Message();
            Bundle b1 = new Bundle();
            msg1.what = 1;
            b1.putInt("udpStatus", udpStatus);
            msg1.setData(b1);
            uiHandler.sendMessage(msg1);

            while (isrunning)
            {

                try
                {
                udpSocket.receive(in);
                //Log.d(TAGUDP,"Data received:");

                }

                catch (IOException ex)
                {

                        Log.d(TAGUDP,"hier??");
                }

    InetAddress senderIP = in.getAddress();
                    int senderPort = in.getPort();
                    //Log.d(TAGUDP, senderIP.toString() + ":" + Integer.toString(senderPort) );
                    buffin = in.getData();//---------------------Einlesen des Inhalts einer CAN Nachricht
                    /*Log.d(TAGUDP, "LOsgeths:");
                    for (int o = 0; o < 28; o++){
                        Log.d(TAGUDP, buffin[o] + " ");
                    }*/
                    //Log.d(TAGUDP, senderIP.toString() + ":" + Integer.toString(senderPort) );
                    CAN_ID = buffin[8] + buffin[9]*256;//----------Ermitteln der CAN ID einer CAN Nachricht
                    String CAN_ID_hex = Integer.toHexString(CAN_ID);
                    if(listenToIds.contains(CAN_ID_hex)){
                        Log.d(TAGUDP, "Neue CAN Nachricht mit der ID " + CAN_ID_hex);
                        CAN_Length = buffin[6] & 15;//---------------Ermitteln der Länge einer CAN Nachricht
                        //Log.d(TAGUDP,"ID: " + CAN_ID + "    ");
                        byte[] canData = ne

w byte[CAN_Length];
                    for (int l = 0; l < CAN_Length; l++){
                        canData[l] = buffin[12+l];
                        //Log.d(TAGUDP, buffin[12+l] + " ");
                        //Log.d(TAGUDP, Integer.toString(byteToUnsignedInt(buffin[12+l])));
                    }
                    Message msg = new Message();
                    Bundle b = new Bundle();
                    msg.what = 2;
                    b.putString("CAN_ID", CAN_ID_hex);
                    b.putByteArray("CAN_DATA",  canData);
                    b.putInt("CAN_LENGTH", CAN_Length);
                    msg.setData(b);
                    uiHandler.sendMessage(msg);
                }
            }

        }

public static int byteToUnsignedInt(byte b) {
        return (0x00 << 24 | b & 0xff);
      }

public void start_Service(){
        Log.d(TAGUDP, "Start Thread");
        this.threadUDP = new Thread(this);
        isrunning = true;
        threadUDP.start();
    }

public void stop_service() {

        Log.d(TAGUDP, "Trenne Verbindung");
        Log.d(TAGUDP, "Warte bis Thread durchgelaufen");
        isrunning = false;
        while(true) {
            try {
                if (threadUDP != null) {
                    threadUDP.join(500);
                }
                } catch (InterruptedException e) {
                e.printStackTrace();
            }
            break;
        }
        Log.d(TAGUDP, "Thread durchgelaufen");
        if (udpSocket != null)
        {
            Log.d(TAGUDP, "Schließe Socket");
            udpSocket.close();
            Log.d(TAGUDP, "geschlossen");
        }
        threadUDP = null;
        Log.d(TAGUDP, "UDP Thread geschlossen");

        udpStatus = 0;
        Message msg = new Message();
        Bundle b = new Bundle();
        msg.what = 1;
        b.putInt("udpStatus", udpStatus);
        msg.setData(b);
        uiHandler.sendMessage(msg);

    }

    public void setsendFlagValue(int flag) {
        this.sendFlag = flag;
    }

    public int getsendFlagValue() {
        return this.sendFlag;
    }

    public static int ipStringToInt(String str) {
         int result = 0;
         String[] array = str.split("\\.");
         if (array.length != 4) return 0;
         try {
             result = Integer.parseInt(array[3]);
             result = (result << 8) + Integer.parseInt(array[2]);
             result = (result << 8) + Integer.parseInt(array[1]);
             result = (result << 8) + Integer.parseInt(array[0]);
         } catch (NumberFormatException e) {
             return 0;
         }
         return result;
     }

    public static InetAddress intToInetAddress(int hostAddress) {
        InetAddress inetAddress;
        byte[] addressBytes = { (byte)(0xff & hostAddress),
                                (byte)(0xff & (hostAddress >> 8)),
                                (byte)(0xff & (hostAddress >> 16)),
                                (byte)(0xff & (hostAddress >> 24)) };

        try {
           inetAddress = InetAddress.getByAddress(addressBytes);
        } catch(UnknownHostException e) {
           return null;
        }
        return inetAddress;
    }

}

my layout:
layout
in code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="de.yargeldi.heckklappenapp.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Öffnen"
        android:id="@+id/button"
        android:layout_marginTop="19dp"
        android:textSize="30sp"
        android:layout_below="@+id/imageView"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Schließen"
        android:id="@+id/button2"
        android:textSize="30sp"
        android:layout_below="@+id/button"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="STOP"
        android:id="@+id/button3"
        android:textSize="30sp"
        android:layout_below="@+id/button2"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/hochschule" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Heckklappengeschwindigkeit:"
        android:id="@+id/textView"
        android:textSize="20sp"
        android:layout_below="@+id/button3"
        android:layout_centerHorizontal="true" />

    <SeekBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/seekBar1"
        android:layout_below="@+id/textView"
        android:layout_marginTop="25dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:max="50"
        android:progressTint="#FF0000"
        android:thumbTint="#0000CD"
        android:indeterminateTint="#0000CD"
        android:foregroundTint="#0000CD"
        android:backgroundTint="#0000CD" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:id="@+id/textView1"
        android:text="50%-100%:"
        android:layout_below="@+id/seekBar1"
        android:layout_alignStart="@+id/textView2" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Heckklappenöffnungswinkel:"
        android:id="@+id/text2"
        android:layout_marginTop="49dp"
        android:layout_below="@+id/seekBar1"
        android:layout_alignStart="@+id/textView3" />

</RelativeLayout>

I tried to complete it, i know that there are all of mistakes, because i am an absolut beginner and i do not know how to use the commands.
I would be very happy, if someone could show how i have to do it right.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Set;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button openbutton,closebutton,stopbutton;
    Handler handler;
    Thread thread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /////////////////////Button Finder//////////////////////
        openbutton=(Button)findViewById(R.id.buttonopen);
        closebutton=(Button)findViewById(R.id.buttonclose);
        stopbutton=(Button)findViewById(R.id.buttonstop);

        /////////////////////Button Listener///////////////////////
        openbutton.setOnClickListener(openbuttonListener);
        closebutton.setOnClickListener(closebuttonListener);
        stopbutton.setOnClickListener(stopbuttonListener);

        thread= new Thread(new UDP_Verbindung(handler));
        thread.start();
    }
}

public Button.OnClickListener openbuttonListener= new Button.OnClickListener(){
    @Override
    public void onClick(View arg0) {

        buffout[12]=1;
        new sendThread().execute();
    }

};

public Button.OnClickListener closebuttonListener= new Button.OnClickListener(){
    @Override
    public void onClick(View arg0) {

        buffout[13]=1;
        new sendThread().execute();
    }

};

public Button.OnClickListener stopbuttonListener= new Button.OnClickListener(){
    @Override
    public void onClick(View arg0) {

        buffout[14]=1;
        new sendThread().execute();
    }

};

public class sendThread extends AsyncTask<String, Integer, Boolean>{

    @Override
    protected Boolean doInBackground(String... arg0) {

        try {
            inet_addr = addr;
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        DatagramPacket out = new DatagramPacket(buffout, buffout.length, inet_addr, UDP_Target_Port);
        try {
            socket= new DatagramSocket();
            socket.send(out);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
}

class UDP_Verbindung implements Runnable{

    private static final String TAGUDP = "UDP";
    final int UDP_Target_Port = 12345;
    private Thread threadUDP = null;
    private boolean isrunning = false;
    private DatagramSocket udpSocket = null;
    byte[] buffin = new byte[28];
    byte[] buffout = {0, 0, 0, 0, 0, 0, 8, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    DatagramPacket in = new DatagramPacket(buffin,buffin.length);
    DatagramPacket out = new DatagramPacket(buffout,buffout.length);
    int CAN_ID;
    int CAN_Length;
    private int udpStatus = 0;
    private Handler uiHandler = null;
    private int sendFlag = 0;
    String ip = "168.192.0.74";
    InetAddress addr = intToInetAddress(ipStringToInt( "192.168.0.74"));
    public int receive = 1;
    private Set<String> listenToIds;

    public UDP_Verbindung(Handler uiHandler) {
        this.uiHandler = uiHandler;
        listenToIds = Collections.<String>emptySet();
    }

    public void setMessages(Set<String> messages){
        listenToIds = messages;
        Log.d(TAGUDP, "New Message IDs to listen to: ");
        for(String strId: listenToIds) {
            Log.d(TAGUDP, strId);
        }
    }

    @Override
    public void run() {

        try
        {
            Log.d(TAGUDP,"Verbindungsaufbau");
            udpSocket = new DatagramSocket(UDP_Target_Port);
            udpSocket.setSoTimeout( 3000 );
        } catch (SocketException ex)
        {
            ex.printStackTrace();
            Log.d(TAGUDP,"Verbindungsaufbau fehlgeschlagen");
            this.stop_service();

        }

        udpStatus = 1;
        Message msg1 = new Message();
        Bundle b1 = new Bundle();
        msg1.what = 1;
        b1.putInt("udpStatus", udpStatus);
        msg1.setData(b1);
        uiHandler.sendMessage(msg1);

        while (isrunning)
        {

            try
            {
                udpSocket.receive(in);
                //Log.d(TAGUDP,"Data received:");

            }

            catch (IOException ex)
            {

                Log.d(TAGUDP,"hier??");
            }

            InetAddress senderIP = in.getAddress();
            int senderPort = in.getPort();
            //Log.d(TAGUDP, senderIP.toString() + ":" + Integer.toString(senderPort) );
            buffin = in.getData();//---------------------Einlesen des Inhalts einer CAN Nachricht
                /*Log.d(TAGUDP, "LOsgeths:");
                for (int o = 0; o < 28; o++){
                    Log.d(TAGUDP, buffin[o] + " ");
                }*/
            //Log.d(TAGUDP, senderIP.toString() + ":" + Integer.toString(senderPort) );
            CAN_ID = buffin[8] + buffin[9]*256;//----------Ermitteln der CAN ID einer CAN Nachricht
            String CAN_ID_hex = Integer.toHexString(CAN_ID);
            if(listenToIds.contains(CAN_ID_hex)){
                Log.d(TAGUDP, "Neue CAN Nachricht mit der ID " + CAN_ID_hex);
                CAN_Length = buffin[6] & 15;//---------------Ermitteln der Länge einer CAN Nachricht
                //Log.d(TAGUDP,"ID: " + CAN_ID + "    ");
                byte[] canData = new byte[CAN_Length];
                for (int l = 0; l < CAN_Length; l++){
                    canData[l] = buffin[12+l];
                    //Log.d(TAGUDP, buffin[12+l] + " ");
                    //Log.d(TAGUDP, Integer.toString(byteToUnsignedInt(buffin[12+l])));
                }
                Message msg = new Message();
                Bundle b = new Bundle();
                msg.what = 2;
                b.putString("CAN_ID", CAN_ID_hex);
                b.putByteArray("CAN_DATA",  canData);
                b.putInt("CAN_LENGTH", CAN_Length);
                msg.setData(b);
                uiHandler.sendMessage(msg);
            }
        }

    }

    public static int byteToUnsignedInt(byte b) {
        return (0x00 << 24 | b & 0xff);
    }

    public void start_Service(){
        Log.d(TAGUDP, "Start Thread");
        this.threadUDP = new Thread(this);
        isrunning = true;
        threadUDP.start();
    }

    public void stop_service() {

        Log.d(TAGUDP, "Trenne Verbindung");
        Log.d(TAGUDP, "Warte bis Thread durchgelaufen");
        isrunning = false;
        while(true) {
            try {
                if (threadUDP != null) {
                    threadUDP.join(500);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            break;
        }
        Log.d(TAGUDP, "Thread durchgelaufen");
        if (udpSocket != null)
        {
            Log.d(TAGUDP, "Schließe Socket");
            udpSocket.close();
            Log.d(TAGUDP, "geschlossen");
        }
        threadUDP = null;
        Log.d(TAGUDP, "UDP Thread geschlossen");

        udpStatus = 0;
        Message msg = new Message();
        Bundle b = new Bundle();
        msg.what = 1;
        b.putInt("udpStatus", udpStatus);
        msg.setData(b);
        uiHandler.sendMessage(msg);

    }

    public void setsendFlagValue(int flag) {
        this.sendFlag = flag;
    }

    public int getsendFlagValue() {
        return this.sendFlag;
    }

    public static int ipStringToInt(String str) {
        int result = 0;
        String[] array = str.split("\\.");
        if (array.length != 4) return 0;
        try {
            result = Integer.parseInt(array[3]);
            result = (result << 8) + Integer.parseInt(array[2]);
            result = (result << 8) + Integer.parseInt(array[1]);
            result = (result << 8) + Integer.parseInt(array[0]);
        } catch (NumberFormatException e) {
            return 0;
        }
        return result;
    }

    public static InetAddress intToInetAddress(int hostAddress) {
        InetAddress inetAddress;
        byte[] addressBytes = { (byte)(0xff & hostAddress),
                (byte)(0xff & (hostAddress >> 8)),
                (byte)(0xff & (hostAddress >> 16)),
                (byte)(0xff & (hostAddress >> 24)) };

        try {
            inetAddress = InetAddress.getByAddress(addressBytes);
        } catch(UnknownHostException e) {
            return null;
        }
        return inetAddress;
    }

}


text:
Q: I am having trouble iterating through an array of objects I am trying to go through an array of objects, I stored them in my SharedPreferences where I go the data from firebase and add the quantity for each object, now I only want to display the title, price, and quantity of the product in the cart. I was able to pull all the values belonging to the product to the cart screen but how to loop through the nested values in the cart screen is the problem. please can anyone help me still learning more on flutter?
Cart screen
@override
  Widget build(BuildContext context) {
    SharedPreferences prefs = SharedPreferences.getInstance() as SharedPreferences;
    var cart = prefs.getStringList('userCart');
    return Row(
      children: [
        SizedBox(
          width: getProportionateScreenWidth(88),
          child: AspectRatio(
            aspectRatio: 0.88,
            child: Container(
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: Color(0XFFF5F6F9),
                borderRadius: BorderRadius.circular(15),
              ),
              child: Image.network(cart![0]),
              // child: Image.network(cart.product.images[0]),
            ),
          ),
        ),
        SizedBox(
          width: getProportionateScreenWidth(20),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              cart.first,
              // cart.product.title,
              style: TextStyle(fontSize: 16, color: Colors.black),
              maxLines: 2,
            ),
            const SizedBox(
              height: 10,
            ),
            Text.rich(
              TextSpan(
                text: "\$${cart.product.price}",
                style: TextStyle(
                  color: kPrimaryColor,
                ),
                children: [
                  TextSpan(
                    text: " x${cart.numOfItem}",
                    style: TextStyle(
                      color: kTextColor,
                    ),
                  ),
                ],
              ),
            ),
          ],
        )
      ],
    );
  }

Storing the data from firebase and adding quantity
Future<void> checkItemInCart(
    Product product, int quantity, BuildContext context) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();

  // convert to map
  var product_str = product.toMap();

  // combine product with quantity
  String productWithQuantity =
      product_str.toString() + '-quantity-' + quantity.toString();

  // check if project exists first
  List<String> userCartPref = (prefs.getStringList('userCart') ?? <String>[]);
  ['Product-quantity-2'];

  /*
   update {
   check if found
   }
  */

  List<String> temp = (prefs.getStringList('userCart') ?? <String>[]);
  // add f
  //userCartPref ['iphone 1','laptop 3'];
  // temp ['laptop 3'];
  var foundInCart = false;
  for (var i = 0; i < userCartPref.length; i++) {
    var item = userCartPref[i];
    var items = item.split('-quantity-'); //list [product,quantity]
    var old_product = items[0];
    var old_qty = items[1];
    if (old_product.contains(product.pid)) {
      foundInCart = true;
      // product exists
      // delete the current item
      temp.removeAt(i);
      // set pref to temp
      prefs.setStringList('userCart', temp);

      // sum the quantity 2 1
      String finalQuantity = (quantity + int.parse(old_qty)).toString();
      // create string for pref with the updated quantity
      String updatedProductWithQuantity =
          product_str.toString() + '-quantity-' + finalQuantity;
      //add item with the updated quantity iphone 2
      addItemToCart(updatedProductWithQuantity, context);
      showSnackBar(context, "Quantity has been updated successfully");

      break;
    }

  }
  if (userCartPref.length == 0 || foundInCart == false) {
    addItemToCart(productWithQuantity, context);
    showSnackBar(context, "Product added successfully to cart");
  }

  await getProducts();
}

Future<void> addItemToCart(String product, BuildContext context) async {
  // await clearPref();
  print("inside");
  SharedPreferences prefs = await SharedPreferences.getInstance();
  List<String> tempCartList = (prefs.getStringList('userCart') ?? <String>[]);
  // print(tempCartList);
  tempCartList.add(product);
  prefs.setStringList('userCart', tempCartList);
}

Future<void> getProducts() async {
  SharedPreferences preferences = await SharedPreferences.getInstance();
  List<String> tempCartList =
      (preferences.getStringList('userCart') ?? <String>[]);
  for (var i = 0; i < tempCartList.length; i++) {
    var item = tempCartList[i];
    var items = item.split('-quantity-');
    var product_ = items[0];
    var quantity_ = items[1];
  }
}

A: you can use ListView.builder or GridView.builder to iterate over the array and render them on screen. So if I use ListView.builder, my code in cart screen would look like:
return ListView.builder(
  itemCount: cart.length, //length of cart
  itemBuilder: (context, index) {
    return Row(
      children: [
        SizedBox(
          width: getProportionateScreenWidth(88),
          child: AspectRatio(
            aspectRatio: 0.88,
            child: Container(
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: Color(0XFFF5F6F9),
                borderRadius: BorderRadius.circular(15),
              ),
              child: Image.network(cart![index]),
              // child: Image.network(cart.product.images[0]),
            ),
          ),
        ),
        SizedBox(
          width: getProportionateScreenWidth(20),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              cart[index].product.title,
              // cart.product.title,
              style: TextStyle(fontSize: 16, color: Colors.black),
              maxLines: 2,
            ),
            const SizedBox(
              height: 10,
            ),
            Text.rich(
              TextSpan(
                text: "\$${cart[index].product.price}",
                style: TextStyle(
                  color: kPrimaryColor,
                ),
                children: [
                  TextSpan(
                    text: " x${cart[index].numOfItem}",
                    style: TextStyle(
                      color: kTextColor,
                    ),
                  ),
                ],
              ),
            ),
          ],
        )
      ],
    );
  },
);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I parse a value with Storybook AddOns optionsKnob I'm building a Storybook for a client, and I want to dynamically change the color theme of components with the use of radio buttons. I've been following the docs, and this is how my code looks:
import { withKnobs, optionsKnob as options } from '@storybook/addon-knobs'

const label = 'Theme color';
const valuesObj = {
  Red: 'red',
  Blue: 'blue',
  Purple: 'purple',
  Green: 'green'
};
const defaultValue = 'red';

const optionsObj = {
  display: 'inline-radio'
};

const groupId = '';

const themeValue = options(label, valuesObj, defaultValue, optionsObj, groupId);

This will display the correct inline radio buttons as intended, but as soon as I click on another radio, the inline buttons will disappear. I also tried to console.log the themeValue, and initially, it shows my default value (red), but it does not change on clicking on another value.

I've been searching through the documentation, and I can only find how to implement it, but not how to parse / actually use the value. Am I missing something here?

A: I figured it out, well, a colleague of mine did.
Instead of doing this:
const themeValue = options(label, valuesObj, defaultValue, optionsObj, groupId);

I'm now doing this in my React component:
<ExampleComponent theme={options(label, valuesObj, defaultValue, optionsObj, groupId)} />

Problem solved!


text:
Q: How do I synchronize these two functions? No1)
  const handleCheckList = (id, checked,findCost) => {
    if (checked) {
      setCheckLists([...checkLists, id]);
    } else if (!checked) {
      // checkLists에서 입력된 id랑 같은걸 찾아서 같지 않은거만 filter
      const tmp = checkLists;
      const newarr = tmp.filter((it) => it !== id);
      setCheckLists(newarr);
    }
    findCost();<< Here!!
  };

No2)
  const findCost = () => {
    for (let i = 0; i < checkLists.length; i++) {
      const tmparr = cart;
      const findobj = tmparr.find((it) => it.id == checkLists[i]);
      console.log(findobj);
    }
  };

I want to run the findCost function after completing the setState operation in the handelCheckList function.
However, setState is asynchronous, so the previous value is passed to findCost.
How can I run findCost after the setState runs completely?
new promise(){
if function...
}.then(findCost())
--> but the result is not good... :(


text:
Q: How to Add Facebook like button to iOS application using Webview? Right now i am struggling with adding Facebook like button to my App.I referred many sites and even developers.Facebook also not provided proper explanation.They just gave frame for like button. Can any one please help in adding Facebook like button in my App using Webview.
Thanks in Advance

A: Ok, this is from working project:
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:URL, @"object", nil];

  if (FBSession.activeSession.isOpen) {
    if (FBSession.activeSession.accessTokenData.accessToken) {
      [FBRequestConnection startWithGraphPath:@"/me/og.likes"
                                   parameters:params
                                   HTTPMethod:@"POST"
                            completionHandler:^(FBRequestConnection *connection, id result, NSError *error) { }];
    } else NSLog(@"FBSession.activeSession.accessToken IS NULL");
  }

URL is the URL of object what you want to like.
There's no code for completionHandler block and for FB-authentification, I hope you can do it as you need.

A: To get count of Likes for some URL you can use this code:
NSString *likesRequestURL = [[NSString stringWithFormat:@"https://graph.facebook.com/fql?q=SELECT+total_count,+url+FROM+link_stat+WHERE+url+=\"%@\"&access_token=%@", URL, FBSession.activeSession.accessTokenData.accessToken] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:likesRequestURL]
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval:60.0f];

    __block NSString *result = [NSString string];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

                               if (error == nil) {
                                   NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   SBJsonParser *jsonParser = [[[SBJsonParser alloc] init] autorelease];
                                   result = [NSString stringWithFormat:@"%@", [[[[jsonParser objectWithString:jsonString] objectForKey:@"data"] objectAtIndex:0] objectForKey:@"total_count"]];
                                   [jsonString release];
                               } else {
                                   NSLog(@"Error = %@", error);
                               }
                           }];

Note. In this case was used SBJSONParser, you can use it or replace by something else, just slightly change corresponding code.
Now you can to create fully customized like-button.

A: It's not right. There is a way to realize Like feature not with UIWebView bit with FBRequestConnection. If you want to use UIWebView - colleague Shan gives right answer, but if you want to use another way - let me to know.


text:
Q: How to set Doctrine 1.2 ATTR_CASCADE_SAVES off in databases.yml? I'm using Symfony 1.4 with Doctrine 1.2 and I've got the following databases.yml:
all:
  doctrine:
    class: sfDoctrineDatabase
    param:
      dsn:      xxxxx
      username: xxxxx
      password: xxxxx
      attributes:
         cascade_saves: false

I was under the impression that using the above would set ATTR_CASCADE_SAVES in Doctrine to false, but having run into some issues with freeing objects, I'm noticing that it actually remains true.
Var_dumping the following in any action file:
Doctrine_Manager::getInstance()->getAttribute(Doctrine::ATTR_CASCADE_SAVES);

... gives me (bool)true. Explicity setting it to false with setAttribute() fixes it, but I don't want to call this in several places in my code. Incidentally, setting it to false fixes the problems I'm having with freeing certain objects after saving.
Can anyone advise me on the correct databases.yml syntax for disabling cascading saves, or am I looking at this wrong somewhow? I can't seem to find anything useful via Google.
Thanks in advance.

A: Looks correct to me - but I do things a slightly different way .... Create a new function in your config/ProjectConfiguration.class.php file  ->
public function configureDoctrineConnectionDoctrine(Doctrine_Connection $connection)
{
  $connection->setAttribute('CASCADE_SAVES', false);
}

you will need to change the function name to match your connection name ... (just then end "Doctrine" part)


text:
Q: Items not draggable after tiny mce is initialised and destroyed I've functionality to drag drop elements such as text, image etc on page. The elements once dragged on to the page needs to be drag-gable so that their positions can be changed. I'm using tiny mce to edit the text elements. I initialize editor on click of the text element and save its content and destroy it by clicking outside of the editor. The drag drop of the elements already added to the page works until, I initialize tiny mce. After editing text and saving, drag drop stops working.
While saving the contents of editor, I'm just replacing the content of text element by the content of editor, so also, copying the classes and add them to the text element. I confirmed that the element has ui-draggable class, but it is not drag-gable...what may be the reason?
Code:
$('.TEXTElementC').live('mouseover', function(e){
    var thistarget=$(this);
    $(thistarget).draggable({
        scroll:true,
        revert:true,
        handle: $(thistarget),
        cursorAt:{left: 5}
        });
});


text:
Q: Add Header, Footer and navbar files on multiple pages Let says below are my web directories:

From web searching i get to use include or require_once and something similar.But I'm confuse in different directory causes much of directory error.
And my question is, how to include Navbar or Footer or Specific Pages in different directory.
Condition: Same directory as above;

A: For header,navBar and footer you should used simple
include(page/header.php);

About require and include function Reference

The require() function is identical to include(), except that it
  handles errors differently. If an error occurs, the include() function
  generates a warning, but the script will continue execution. The
  require() generates a fatal error, and the script will stop.

But for image,css files and other js files you should follow these steps
Create config.php file
add this in config.php
define('BASE_URL', 'http://your_website_url');//OR define('BASE_URL', 'localhost')

you can use this path like
<?php
    include('config.php');//add this code into top of the page
?>

and finally you can used where you want, like
For Style sheet
<link rel="stylesheet" href="<?php echo BASE_URL; ?>/css/styles.css" />

A: Create a config.php file in your home directory.
<?php
    /* Saves the directory path to base directory as `BASE_DIR`
       Example: /var/user1/home/public_html/
       'Base directory' is where your homepage/index.php is located */

       define('BASE_DIR', dirname(__FILE__) . '/');
?>

now just require this config.php file
<?php
    require_once('config.php'); //add this line at top of your pages
    // No need to include this inside 'header.php' and 'footer.php'
?>

Now u can include files easily, use it in index.php as follows:
<?php
    require_once('config.php');

    require(BASE_DIR . 'query/conn.php');
    // becomes '/var/user1/home/public_html/query/conn.php'

    include(BASE_DIR . 'pages/header.php');
    include(BASE_DIR . 'pages/navbar.php');
    include(BASE_DIR . 'pages/footer.php');
?>

Note: Similar approach is used by WordPress (learn more)


text:
Q: Grails : Plugin [controllers:3.3.9] could not reload changes to file I am running into a ghost of a problem. It happens sporadically. It has to do with controllers reloading after changes. Most times I am able to work around by reverting changes and starting fresh, however I am currently stuck. Below is the stacktrace.
File /Users/mcroteau/Development/projects/greenfield/grails-app/controllers/greenfield/DataController.groovy changed, recompiling...
2019-01-07 20:05:32.374 ERROR --- [       Thread-7] o.g.plugins.AbstractGrailsPluginManager  : Plugin [controllers:3.3.9] could not reload changes to file [/Users/mcroteau/Development/projects/greenfield/grails-app/controllers/greenfield/DataController.groovy]: No signature of method: grails.core.DefaultGrailsApplication.isArtefactOfType() is applicable for argument types: (java.lang.String, org.springframework.core.io.FileSystemResource) values: [TagLib, file [/Users/mcroteau/Development/projects/greenfield/grails-app/controllers/greenfield/DataController.groovy]]
Possible solutions: isArtefactOfType(java.lang.String, java.lang.Class), isArtefactOfType(java.lang.String, java.lang.String)

groovy.lang.MissingMethodException: No signature of method: grails.core.DefaultGrailsApplication.isArtefactOfType() is applicable for argument types: (java.lang.String, org.springframework.core.io.FileSystemResource) values: [TagLib, file [/Users/mcroteau/Development/projects/greenfield/grails-app/controllers/greenfield/DataController.groovy]]
Possible solutions: isArtefactOfType(java.lang.String, java.lang.Class), isArtefactOfType(java.lang.String, java.lang.String)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:71)
        at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:53)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:136)
        at org.grails.plugins.web.GroovyPagesGrailsPlugin.onChange(GroovyPagesGrailsPlugin.groovy:305)
        at org.grails.plugins.DefaultGrailsPlugin.notifyOfEvent(DefaultGrailsPlugin.java:750)
        at grails.plugins.DefaultGrailsPluginManager.informObservers(DefaultGrailsPluginManager.java:210)
        at org.grails.plugins.DefaultGrailsPlugin.notifyOfEvent(DefaultGrailsPlugin.java:774)
        at org.grails.plugins.AbstractGrailsPluginManager.informOfClassChange(AbstractGrailsPluginManager.java:548)
        at org.grails.plugins.AbstractGrailsPluginManager.informOfFileChange(AbstractGrailsPluginManager.java:488)
        at grails.plugins.GrailsPluginManager$informOfFileChange$2.call(Unknown Source)
        at grails.boot.GrailsApp$_enableDevelopmentModeWatch_closure1.doCall(GrailsApp.groovy:250)
        at grails.boot.GrailsApp$_enableDevelopmentModeWatch_closure1.doCall(GrailsApp.groovy)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1427)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
        at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:264)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1034)
        at groovy.lang.Closure.call(Closure.java:418)
        at groovy.lang.Closure.call(Closure.java:412)
        at groovy.lang.Closure.run(Closure.java:499)
        at java.lang.Thread.run(Thread.java:748)

Here is one project it is currently happening in: https://github.com/opengreenfield/greenfield - branch internationalization, DataController. Im ok with deleting things.
Thank you in advance for your help!

A: I see that your package definition and folder structure do not match. I am guessing grails gets confused by this. Try lining them up.


text:
Q: Can't make Discord bot leave the voice channel in Python I'm trying to make my Discord bot leave the voice channel when someone types "leave" as a message, but I don't get any errors and the bot doesn't disconnect. Can someone help me?
@client.command(pass_context=True)
async def leave(ctx):
    server = ctx.message.guild.voice_client
    await server.disconnect()

A: There are certain cases where the voice client can get into a bad state and think that you're not connected when you are. Try using the force argument for VoiceClient.disconnect and setting it to True when you disconnect.


text:
Q: How to dynamically set JAVA_HOME in Jenkins docker agent My Jenkins pipeline is running on a docker agent containing several jdks. The specific jdk version to use to build a project is chosen within the pipeline description.
(As I am using JTE plugin (https://jenkinsci.github.io/templating-engine-plugin/2.5/), this is done by passing the jdk version to use via the JTE config variable to the libraries used to define the jenkins pipeline.)
The end result at the moment (once the variables are resolved) is that the maven commands look as followed:
sh("env JAVA_HOME=/opt/jdk-11 /opt/maven-3/bin/mvn compile")

where:
/opt/jdk-11 is the folder in the docker agent container where the jdk-11 is installed (there is also the possibility to choose jdk-17, and other)
/opt/maven-3/bin/mvn is the folder in the docker agent container where maven is installed
Is it be possible, instead of declaring env JAVA_HOME=/opt/jdk-11 in the command line, to declare it as a environment variable in the docker agent dynamically so that for all steps
sh('echo $JAVA_HOME')

would return /opt/jdk-11
and the maven command line would look like:
sh("/opt/maven-3/bin/mvn compile")

?


text:
Q: ! Extra }, or forgotten $ What's wrong with following algorithm?
\documentclass[journal]{IEEEtran}

\usepackage{graphicx}
\usepackage{subfigure}
\usepackage{overpic}
\usepackage{amsmath}
\usepackage{flushend}
\usepackage{amssymb}
\usepackage{multirow}
\usepackage{makecell}
\usepackage{color, soul}
\usepackage[ruled]{algorithm2e}

\begin{algorithm}
\caption{Sample Mixup Algorithm}\label{al_sm}
\LinesNumbered
\KwIn{Training dataset $(X,Y)$, number of training epochs $m$, two parameters $p$ and $q$ satisfying (0 $\leq$ $p$ $<$ $q$ $\leq$ 1), Beta distribution parameter $\alpha$ for sample mixup.}
\For{$i = 1$ $to$ $m$}{
Draw a mini-batch ($x_b$, $y_b$).\\
\uIf(\tcc*[f]{First stage}){$i$ $\leq$ $pm$}{
($\Tilde{x_b}$, $\Tilde{y_b}$) = mixup($x_b$, $y_b$, $\alpha$)}
\uElseIf(\tcc*[f]{Second stage}){$i$ $\leq$ $qm$}{
$\epsilon = \frac{m-i}{m(1-q)}$\\
Randomly generate threshold $\theta\in \mathbb{$[0,1]$}$.\\
\uIf{$\theta < \epsilon$}{
($\Tilde{x_b}$, $\Tilde{y_b}$) = mixup($x_b$, $y_b$, $\alpha$)}
\Else{($\Tilde{x_b}$, $\Tilde{y_b}$) = ($x_b$, $y_b$)}}
\Else(\tcc*[f]{Third stage}){($\Tilde{x_b}$, $\Tilde{y_b}$) = ($x_b$, $y_b$)}
Train model with mini-batch ($\Tilde{x_b}$, $\Tilde{y_b}$).}
\end{algorithm}

A: Adaptations

*

*added document environment

*cause of the error message (! Extra }, or forgotten $): changed \mathbb{$[0,1]$} to [0,1] (don't use math mode inside math mode again)

*use indentation to not lose track of the code (and the curly braces)

*don't put every single sign in a seperate math environment, e.g., 0 $\leq$ $p$ $<$ $q$ $\leq$ 1 should be $0 \leq p < q \leq 1$

*reduced packages for MWE

Code
\documentclass[journal]{IEEEtran}

\usepackage{amsmath}
\usepackage[ruled]{algorithm2e}

\begin{document}

\begin{algorithm}
    \caption{Sample Mixup Algorithm}
    \label{al_sm}
    \LinesNumbered
    \KwIn{Training dataset $(X,Y)$, number of training epochs $m$, two parameters $p$ and $q$ satisfying ($0 \leq p < q \leq 1$), Beta distribution parameter $\alpha$ for sample mixup.}
    \For{$i = 1$ to $m$}{
        Draw a mini-batch ($x_b$, $y_b$).\\
        \uIf(\tcc*[f]{First stage}){$i \leq pm$}{
            ($\Tilde{x_b}$, $\Tilde{y_b}$) = mixup($x_b$, $y_b$, $\alpha$)
        } \uElseIf(\tcc*[f]{Second stage}){$i$ $\leq$ $qm$}{
            $\epsilon = \frac{m-i}{m(1-q)}$\\
            Randomly generate threshold $\theta\in [0,1]$.\\
            \uIf{$\theta < \epsilon$}{
                ($\Tilde{x_b}$, $\Tilde{y_b}$) = mixup($x_b$, $y_b$, $\alpha$)
            } \Else{
                ($\Tilde{x_b}$, $\Tilde{y_b}$) = ($x_b$, $y_b$)
            }
        } \Else(\tcc*[f]{Third stage}){
            ($\Tilde{x_b}$, $\Tilde{y_b}$) = ($x_b$, $y_b$)
        }
        Train model with mini-batch ($\Tilde{x_b}$, $\Tilde{y_b}$).
    }
\end{algorithm}

\end{document}


text:
Q: display textbox when item is selected from dropdown list html php?

                *Camera name

                <select name="cam_name" class="span3" id = "ddlPassport" onchange = "ShowHideDiv()">
                  <option>Select camera:</option>
                  <option>canon</option>
                  <option>nicon</option>
                  <option>sony</option>
                  <option>pentex</option>
                  <option>olympus</option>
                  <option>others</option>
                </select>

              Your camera name:

                <input type="text" placeholder="Enter model" name="cam_name" class="input-xlarge">

javascript


text:
Q: best way to run a script that takes a long time using an API call in Python I have an API that currently runs a script and returns a status code based on the output of the script. It also serves a file via another API upon completion of the script. However, in production I have found that the process could take a long time and the request could time out before the script finishes running. How can I make this API such that it wont wait for the script to finish and the script will send the file well after the first API call responded?

A: Web servers like to keep request/response cycles short. When some requests take increasingly longer to satisfy, there comes a point where that work needs to be "out of process" to avoid gumming up the web server.
This need is why things like celery exist. The idea is that a client describes the work to be done in a request. The handler will queue up that description, getting an id in return, and will pass that id back to the client in the response. The client remembers that id, and then polls, passing that id. Meanwhile, a worker process running elsewhere has picked up the work description from the queue, done done the work, and return the result. Eventually a poll request will say "done!" instead of "please wait", and the client can retrieve the results.
The Flask Mega Tutorial, in chapter 22, covers a way way to do this using Rq, which is simpler, but less robust, than celery. It's worth looking at that chapter to solidify the general idea.


text:
Q: force ie8 standard browser mode view even if user selects IE8 Compat View I am using the below meta tag
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

This is my full html
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Compatability Mode?</title>

        If the red box is outside the line, it's ie8 mode

        If the red box is inside the line, it's ie7 mode

Now what i want to achieve is, if the user goes to browser mode and changes it to IE8 Compat View or if IE8 Compat view is defaulted in compatibility view settings, i want the page to be rendered in IE8 mode only
How can i do that?
I am ok with any solution(javascript,jquery) or anything else

A: You can't.
By design, the user (or admin) is fully in control of the experience and can do many things to view your design in unexpected ways.  You know about the CV button (which actually forces a page to be displayed in IE7 mode).  There's also the F12 tools, compatibility view settings, group policies, IE Enterprise mode, and more.
A better approach is to design the page to determine whether the current capabilities support your needs using things like feature detection, progressive enhancement, graceful fallback, etc.
There are things you can do to influence the decision, but there's always going to be some path, or feature, or workaround, update, or other factor that you didn't think of or predict.
What's the IE7 problem you're trying to solve?  Perhaps there's a different way to achieve the effect, one that doesn't rely on a feature unique to IE8.
Hoping to help...
-- Lance
P.S.  You might want to look at your smart quote settings, as the sample you posted uses "smart" quotes in the meta element.


text:
Q: As of 2021, what is the latest record for lowest temperature? From what I understand in this article, absolute zero(0 kelvin) is an impossible task.
They state that the lowest temperature achieved in the laboratory was 0.1 nanokelvin.

The lowest temperature ever recorded was back here on Earth in a laboratory. In September 2003, scientists at the Massachusetts Institute of Technology announced that they'd chilled a cloud of sodium atoms to a record-breaking 0.45 nanokelvin. Earlier, scientists at the Helsinki University of Technology in Finland achieved a temperature of 0.1 nanokelvin in a piece of rhodium metal in 1999. However, this was the temperature for just one particular type of motion – a quantum property called nuclear spin – not the overall temperature for all possible motions.

As of 2021, what is the lowest temperature achieved in an experiment (laboratory)?


text:
Q: Pulling data from a SQL table I have an Intranet, that is SQL based on the back end.
Users submit documents to the Intranet, but sometimes they set an expiry on the document.
There is a table "dbo.article" that lists all these documents, who submitted them and when (if ever) they expire. I get get this data by doing:
SELECT TOP 999 [NEWSID]
  ,[EXPIRES]
  ,[HEADLINE]
  ,[AUTHORID]
  ,[AUTHOR]
   FROM [ARTICLE]
   ORDER BY [EXPIRES] ASC

I would like this to run, say once a week, and then email me when an article is about to expire.
What would be the best way to achieve this?
Gavin.

A: a couple of ways to achieve this,
option 1 - write a stored procedure checking the expiry and sending notification emails if necessary, there are ways to send emails from sql server, for example, this link - How to send email from SQL Server?
option 2 - use some script (vbs or powershell, again, either use stored procedure or plain sql query) and when the condition is met, fire an email, and this is more flexible and could be installed at any client machine (not necessary on the SQL server). one sample on how to send email using vbs - http://social.technet.microsoft.com/Forums/en-US/7779b3bb-dfcc-4ab3-966d-9c71d5369ad7/send-email-using-vbscript
option 3 - implement a simple console app or even win form app to do stuff in option 2, instead of using script.
but all the options require you to add a scheduled task on the installed box to run it at your desired timeframe.


text:
Q: Unable to send/receive custom metadata on Amazon S3 Upload (using ng-file-upload) I am using ng-file-upload to upload a JPG file to my S3 Bucket.
file.upload = Upload.upload({
    url: "https://<my-bucket-name>.s3.amazonaws.com/",
    method: "POST",
    data: {
        key: "custom-filename.jpg",
        AWSAccessKeyId: "<AWSAccessKeyId>",
        acl: "public-read",
        policy: <policy>,
        signature: <signature>,
        "Content-Type": "image/jpeg",
        filename: file.name,
        file: file,
        Metadata: {
            "x-amz-meta-hello": "Custom Metadata Value"
        }
    }
});

I have also tried the following (in the above code)
Metadata: {
    hello: "Custom Metadata Value"
}

& simply
"x-amz-meta-hello": "Custom Metadata Value"

I have included the Custom Metadata in my Policy file as
["starts-with", "x-amz-meta-hello", ""]

Also, the CORS Configuration under Bucket Permissions on S3 is
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <ExposeHeader>x-amz-meta-hello</ExposeHeader>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>

The above code and settings are working, the JPG file is successfully uploaded, but somehow the Custom Metadata value is not being set.
On successful upload, I am calling a Lambda function to resize the JPG and storing it in a separate bucket. Even this part is working but I am not able to read the Custom Metadata (x-amz-meta-hello) value in my Lambda Function. I need that value to assign a separate folder to the uploaded file.
To read the Custom Metadata in my Lambda Function
var s3 = new AWS.S3();
s3.headObject({
    Bucket: <BucketName>,
    Key: <S3ObjectKey>
}, function(err, data) {
    if (err) {
        console.log(err);
    }
    else
    {
        console.log(data);
    }
});

Not sure what am I missing here ... Please advise.
Thanks.
(AngularJS version 1.5.0, ng-file-upload version 12.2.9, Google Chrome version 53.0.2785.113 on OSX 10.10.5)

A: Remove the Metadata: { ... } construct, because you're building an HTML form, which has a flat keyspace.  Elsewhere you may see metadata given special treatment, where something like Metadata: { "hello": "world" } magically becomes x-amz-meta-hello: world but that is not applicable, here. Instead, metadata needs to start with x-amz-meta-, and since we are making a POST request, it is provided in the form data, rather than as a header.
Because the file data needs to be the last form element, place the metadata key above the file info, e.g.:
...
"Content-Type": "image/jpeg",
"x-amz-meta-hello": "Custom Metadata Value",
filename: file.name,
...

Your policy condition must reference the metadata name with a $ in order to work (["starts-with", "$x-amz-meta-hello", ""]). Note that having the policy is required for the field to be accepted, but this specific condition does not constrain the field to contain a specific value.
Note also that <ExposeHeader>x-amz-meta-hello</ExposeHeader> is not necessary in order to allow the upload.  <ExposeHeader> allows the browser to return that response header to the calling code on an AJAX request. Headers not listed (other than the "simple" standard ones, like Content-Type) are otherwise hidden from calling code.  CORS is initially counterintuitive, until you understand that it's based on the idea that the web browser itself is assumed to be well-intentioned but naïve. CORS gives the browser permission to do things that it would not otherwise do, such as returning specific headers back to a caller.


text:
Q: Holiday Booking system, search for date - return a list of employees who are on holiday on that date I seem to be asking a lot of questions on here recently, thanks in advance for any help!
First - I have a calendar table which may make this easier. Calendar table is pretty standard, a dateID, Date and varying different formats of that date.
I want to give the query a date, and for it to return a list of all employees and whether or not they were on holiday on that date.

LeaveTypeID is 1 for holiday 2 for sickness, 3 for compassionate, etc, etc, I'm only concerned with holiday at this point.
StartDate and EndDate are as they appear
StartMidday is whether or not the holiday starts at midday on the first day (so working the morning and starting the holiday at lunch), same for endmidday but for the end of the holiday period)
Would ideally like it to say whether that day is a half day as well if possible?
So I want my result to be something like (assuming I chose the date of the 4th Nov, 2016)
EmployeeID  OnHoliday   IsHalf
1             TRUE       TRUE
2             FALSE      FALSE
3             FALSE      FALSE
4             FALSE      FALSE
5             FALSE      FALSE

Hopefully that's enough info. Thanks again in advance!

A: i think you can use between for this purpose:
    declare @InputDate date='2016-09-16' --yur input date

   select EmployeeId,
   case when (select count(1) from EmployeeLeave
   where (@InputDate between StartDate and EndDate)
   and EmployeeLeave .EmployeeId=Employee .EmployeeId)>1 then 'True' else 'False' end as [OnHoliday],
   case when ((select StartMidDay from EmployeeLeave
   where (@InputDate between StartDate and EndDate)
   and EmployeeLeave .EmployeeId=Employee .EmployeeId))=0.5 then 'True' else 'False' end as [IsHalf] ,
   from Employee

A: I think I may have come up with a solution by myself
declare @DateAdd int=0 --add Days From Monday
declare @LeaveType int=1 -- Leave Type

declare @SelctedDate date = DATEADD(DD, @DateAdd, CAST('2016-11-21' AS DATE)) --Week Commencing

select
      (CASE
            WHEN (leaveTemp.StartMidday = '0.5' AND leaveTemp.StartDate = @SelctedDate) THEN '4:00'
            WHEN (leaveTemp.EndMidday = '0.5' AND leaveTemp.EndDate = @SelctedDate)  THEN '4:00'
            WHEN LeaveID is not null THEN '8:00'
            ELSE NULL
      END ) as HolMon

from Employee left join
(select employeeID, LeaveID, StartDate, EndDate, StartMidday, EndMidday
      from EmployeeLeave
      where LeaveTypeID=@LeaveType and @SelctedDate between startdate and enddate
) as leaveTemp
on Employee.EmployeeID = leaveTemp.EmployeeID
ORDER BY Employee.EmployeeForename, Employee.EmployeeID

This seems to bring back what I was after but is the best way to do it?


text:
Q: how to fill the area between the bars in the given example d3js I am trying to create somehing like this

I am thinking it as a horizontal stacked bar chart with a twist. I need some guideline on how to convert this
 horizontal Stacked bar chart
    state.each(function(d,i) {
 //var line = focus.append("line").style("stroke", "black")
            //.attr("x1", x11(450))
            //.attr("y1", y(585))
            //.attr("x2", that.options.width - 210)
            //.attr("y2", that.options.height-(that.options.height - 20)).style("shape-rendering","auto");
    d3.select(this).append("circle").attr("cx",this.getBBox().width).attr("cy",this.getBBox().y).attr("r",2)
    d3.select(this).append("circle").attr("cx",this.getBBox().x).attr("cy",this.getBBox().y).attr("r",2)
    d3.select(this).append("circle").attr("cx",(this.getBBox().x)).attr("cy",this.getBBox().height+this.getBBox().y).attr("r",2)
    d3.select(this).append("circle").attr("cx",(this.getBBox().x+this.getBBox().width-4)).attr("cy",this.getBBox().height+this.getBBox().y-2).attr("r",2)
    console.log(this.getBBox())
});

to that or at least look like that.
First problem I am facing is to center align the stacked bar chart. Means if remove yaxis and make all bars center align.

A: How to center all the stacks.
Your current implementation here.
Answer
Rotate this via the center of the graph by 90 degrees as shown below in the code
var svg = d3.select("body").append("svg")
    .attr("id", "mySVG")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")rotate(90," + width / 2 + "," + height / 2 + ")");
var legend = d3.select("svg").append("g");

This will rotate the graph and it will look like this.
Next how to show legends with the graph.
   //this will get the last g(group) element as we want to attach the legend to it
    var lastG = d3.select(d3.selectAll(".state")[0].pop());
   //this will get all the rectangles in the last group
    var lastRect = d3.select(d3.selectAll(".state")[0].pop()).selectAll("rect");
   //to get the bbox's y (since its rotated by 90 so x will become y)
    var lastx = lastG.node().getBBox().y;
    var lineFunction = d3.svg.line()
        .x(function (d) {
        return d.x;
    })
        .y(function (d) {
        return d.y;
    })
        .interpolate("step-before");
    //to each rectangle in the last group
    lastRect[0].forEach(function (d, i) {

        //make an svg point
        var point = document.getElementById("mySVG").createSVGPoint();
        point.x = (d3.select(d).attr("x") + +parseFloat(d3.select(d).attr("width")));
        point.y = (parseFloat(d3.select(d).attr("y")) + parseFloat(d3.select(d).attr("height")));
        //the point after rotation moves to the new position.
        var newPoint = point.matrixTransform(d.getScreenCTM());
        //making a circle and appending to the legend group

        legend.append("circle").attr("r", 2).attr("cx", newPoint.x).attr("cy", newPoint.y).style("fill", "red").attr("class", "entry");

        var x1 = lastx;
        var y1 = newPoint.y + 50 + (10 * i);
        legend.append("circle").attr("r", 2).attr("cx", x1).attr("cy", y1).style("fill", "red").attr("class", "entry");

        //making the line with start point and end point
        var lineData = [{
            x: newPoint.x,
            y: newPoint.y
        }, {
            x: x1,
            y: y1
        }];
        //make the line and append it to legend
        legend.append("path")
            .attr("d", lineFunction(lineData))
            .attr("stroke", "blue")
            .attr("stroke-width", 2)
            .attr("fill", "none");
        //adding the text with label
        legend.append("text").attr("x", x1+20).attr("y", y1).text(d3.select(d).data()[0].name)
    });

Full working code here.
I have added comments to help you understand the code.


text:
Q: Did Dumbledore know during Tom Riddle's time at Hogwarts that Riddle was the heir of Slytherin? I remember in The Chamber of Secrets during the flashback scene that while Dumbledore distrusted Riddle, there didn't seem to be any indication that he knew that Tom was the one unleashing the basilisk. That said, we also know Dumbledore is a great chess master and may not have had a reason to show he knew at that time. At the same time, we can't know if Dumbledore could at the time verify Hagrid's innocence (or even knew of it himself). It wasn't until Armando Dippet retired that Dumbledore was able to hire Hagrid, and at that point there may or may not have been several intervening years for Dumbledore to discover the true culprit.
Is there conclusive canon evidence to show if or if not Dumbledore knew the true culprit during the first time the chamber was opened?


text:
Q: What statistical functions come native to C# and T-SQL? I'm a fledgling DBA dealing with some medical data.  While I've not yet gotten to the point of needing top-tier statistical methods, I will soon.  I plan to put several databases online and searchable for whatever the user wants.  My question is, besides average, standard deviation, etc. does T SQL have any other statistical functions?  And for C#?  Are free libraries for things such as this readily available, or would I have to make it?  Thanks!

A: I don't know about T-SQL, but in C# there is dnAnalytics which offers various functions concerning descriptive statistics. I've used it on various occasions and was very satisfied with the results achieved, performance and overall library design.


text:
Q: Web Scraping images (Beautiful Soup) into a directory with one function, trying to append those images into a list in another function, struggling
So I am trying to add each image from each reddit post that I extract and store in a directory with Beautiful soup into my list "post_imgs" This is only part of my program, not the complete thing. I'm just not sure how I do this since my web scraping function and appending list function are separate. The two functions need to be separate for my program to work. This is for a Bot i'm working on as a personal project.

import bs4 as bs
import requests
import praw

img_dir = 'pics'

def get_image(img_url):
    if not os.path.exists(img_dir):
        os.makedirs(img_dir)

    url = img_url
    r = requests.get(url)
    data = r.text
    soup = bs(data, 'lxml')

    image_tags = soup.findAll('img')

    os.chdir(img_dir)
    x = 0

    for image in image_tags:
        try:
            url = image['src']
            source = requests.get(url)
            if source.status_code == 200:
                img_file = img_dir + str(x) + '.jpg'
                with open(img_file, 'wb') as f:
                    f.write(requests.get(url).content)
                    f.close()
                    x += 1
                    return img_file #is this right?
        except:
            pass
    return ''

def appending_lists(subreddit_info):
    post_links = []
    post_titles = []
    post_ids = []
    post_imgs = []

    for submission in subreddit_info.new(limit=5):
        if not already_tweeted(submission.id):
            post_titles.append(submission.title)
            post_links.append(submission.shortlink)
            post_ids.append(submission.id)
            post_imgs = os.listdir(get_image(submission.shortlink)) #this is where my problem is
            #How do I add the image file into this list.

    return post_links, post_titles, post_ids, post_imgs

If you are confused about the "submission.id,submission.title" etc. stuff, It just means that I am extracting, using praw, the ID and title of the Reddit posts.

Here is the updated version
def get_image(img_url):
    url = img_url
    r = requests.get(url)
    data = r.text
    soup = bs(data, 'lxml')

    image_tags = soup.findAll('img')

    os.chdir(img_dir)
    x = 0
    mylist = []
    for image in image_tags:
        try:
            url = image['src']
            source = requests.get(url, stream = True)
            if source.status_code == 200:
                img_file = img_dir + str(x) + '.jpg'
                with open(img_file, 'wb') as f:
                    f.write(requests.get(url).content)
                    mylist.append(img_file)
                    f.close()
                    x += 1
                    return img_file
        except:
            mylist.append(None)
    return mylist

def appending_lists(subreddit_info):
    post_links = []
    post_titles = []
    post_ids = []
    post_imgs = []

    for submission in subreddit_info.new(limit=5):
        if not already_tweeted(submission.id):
            post_titles.append(submission.title)
            post_links.append(submission.shortlink)
            post_ids.append(submission.id)
            post_imgs = get_image(submission.shortlink).copy() #this is where my problem is
            #How do I add the image file into this list.

    return post_links, post_titles, post_ids, post_imgs

A: Almost! You can either create a list of the URLs in your first function and return the list to use in the second function, or, you can open the file in your second function that you've just written to and take the information directly from there.
with open(img_file, 'r') as file:
#Read the file then perform list appending


text:
Q: No events from notify icon my application is running in Background completely but shows it's activity via a notification icon in system tray. Now I wanted to add a popup-menu to that notification icon. Unfortunately I do not receive any events from it. That's what I'm doing currently to create the icon and its event handler:
First create an invisible window to use it's event handler
ZeroMemory(&wc,sizeof(WNDCLASSEX));
wc.cbSize=sizeof(WNDCLASSEX);
wc.lpfnWndProc=WndProc;
wc.hInstance=hInstance;
wc.lpszClassName=L"myCL";
RegisterClassEx(&wc);

hWnd=CreateWindowEx(WS_EX_CLIENTEDGE,L"myCL",L"myWN",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,
                    CW_USEDEFAULT,1,1,NULL,NULL,hInstance,NULL);

Next create and show the icon itself:
ZeroMemory(&niData,sizeof(NOTIFYICONDATA));
niData.cbSize=sizeof(NOTIFYICONDATA);
niData.uID=IDI_AAAA; // the icon's identifier
niData.uFlags=NIF_ICON|NIF_MESSAGE|NIF_TIP;
niData.hIcon=(HICON)LoadImage(hInstance,MAKEINTRESOURCE(IDI_AAAA),IMAGE_ICON,
                              GetSystemMetrics(SM_CXSMICON),GetSystemMetrics(SM_CYSMICON),
                              LR_DEFAULTCOLOR);
niData.hWnd=hWnd;
niData.uCallbackMessage=MY_TRAY_ICON_MESSAGE;
Shell_NotifyIcon(NIM_ADD,&niData);

And the event handler that is assigned to the invisible window and where I would have assumed the events from the icon should arrive too:
LRESULT CALLBACK WndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
   switch(msg)
   {
      case WM_CLOSE:
         DestroyWindow(hwnd);
         break;
      case WM_DESTROY:
         PostQuitMessage(0);
         break;
      case MY_TRAY_ICON_MESSAGE: // this should be related to notification icon but is never called
         switch (lParam)
         {
            case WM_LBUTTONDOWN:
            case WM_RBUTTONDOWN:
            case WM_CONTEXTMENU:
               break;
         }
         break;
      default:
         return DefWindowProc(hwnd,msg,wParam,lParam);
   }
   return 0;
}

Anybody an idea what is wrong here?


text:
Q: Fetch records from multiple tables using join I have three tables such as "tbl_purchase", "tbl_user" & "tbl_contestant". I need all records from tbl_purchase with "name" that has in two tables "tbl_user" & "tbl_contestant".
My Query,
    SELECT tp.*, tu.*
       FROM tbl_purchase tp
       INNER JOIN tbl_user tu
       ON tu.user_id = tp.user_id

Table: tbl_purchase
 +-------+-------------+------+
 | p_id  | user_id     | Star |
 +-------+-------------+------+
 | 1     | 1           | 50   |
 | 2     | 4           | 100  |
 | 3     | 6           | 150  |
 +-------+-------------+------+

Table: tbl_user
 +-------+-------------+
 | u_id  | name        |
 +-------+-------------+
 | 1     | Sachin      |
 | 4     | Akshay      |
 +-------+-------------+

Table: tbl_contestant
 +-------+-------+-------------+
 | c_id  | u_id  |  Name       |
 +-------+-------+-------------+
 | 1     |   6   |  Mayank     |
 | 2     |   8   |  Nikhil     |
 | 3     |   9   |  Vipul      |
 +-------+-------+-------------+

I want below result,
 +-------+-------+-------------+------+
 | p_id  | u_id  |  Name       | Star |
 +-------+-------+-------------+------+
 | 1     | 1     |  Sachin     | 50   |
 | 2     | 4     |  Akshay     | 100  |
 | 3     | 6     |  Mayank     | 150  |
 +-------+-------+-------------+------+

A: Try this SQL query:
select p.p_id, u.u_id, u.name, p.star
from tbl_purchase p
inner join (
    select u_id, name from tbl_user
    union
    select u_id, name from tbl_contestant
) u on p.user_id = u.u_id;

Result:
p_id    u_id    name    star
1       1      Sachin   50
2       4      Akshay   100
3       6      Mayank   150

Explanation:

*

*Your users are in 2 tables - tbl_user and tbl_contestant

*So, you have to combine the users using a UNION (which removes duplicates)

*Then, you can join with your purchase table

Example: https://rextester.com/RKHXL43587

A: Try this. Because of your name is not in a single table so leftJoin on both user and contestant table. and as @Akina said in comment COALESCE returns first non-null value from the list Reference
select tbl_purchase.p_id,
tbl_purchase.user_id as u_id,
COALESCE(tbl_user.name, tbl_contestant.Name) as name
        from tbl_purchase
        LEFT JOIN tbl_user ON tbl_user.u_id = tbl_purchase.user_id
        LEFT JOIN tbl_contestant ON tbl_contestant.u_id = tbl_purchase.user_id


text:
Q: Embedded Jetty doGet called, expected doPost Problem: Only doGet gets called when I expect doPost to be called.
I have an embedded Jetty server that I start as follows:
server = new Server(8080);
ServletContextHandler myContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
myContext.setContextPath("/Test.do");
myContext.addServlet(new ServletHolder(new MyServlet()), "/*");

ResourceHandler rh = new ResourceHandler();
rh.setResrouceBase("C:\\public");

HandlerList hl = new HandlerList();
hl.setHandlers(new Handler[]{rh, myContext});

server.setHandler(hl);

//server.start() follows

After I start the server, I open up the following page (resides in "public" folder, and opened via http://localhost:8080/test.html):

<title>Test Page</title>

Test for Post.

<form method="POST" action="Test.do"/>
<input name="field" type="text" />
<input type="submit" value="Submit" />
</form>

When I press the Submit button, I expect my servlet's doPost method to be called, however doGet seems to be getting called instead.  MyServlet class (extends HttpServlet) contains:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
  System.out.println("   doGet called with URI: " + request.getRequestURI());
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
  System.out.println("   doPost called with URI: " + request.getRequestURI());
}

I never get the doPost print, just the one from doGet (on Submit button press).
Obviously, Jetty (and web technology in general) is brand new to me.  I've been combing through the Jetty examples, but just can't seem to get a POST to actually get picked up by the doPost method.
Appreciate any help.  Thanks in advance.

A: The problem is your context path.  B/c the path is set as

myContext.setContextPath("/Test.do");

Jetty is returning an HTTP 302 Found with a location that tells the browser "get the page from here":

HTTP/1.1 302 Found
Location: http://localhost:8080/test.do/
Server: Jetty(7.0.0.M2)
Content-Length: 0
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Date: Wed, 04 Apr 2012 19:32:01 GMT

The actual page is then retrieved with a GET.  Change the contextPath to / to see your expected results:

myContext.setContextPath("/");


text:
Q: sms url scheme not working on IOS5 In my web app targeted to iphone and android, I have a "TEXT ME" button which when clicked, leads the user to sms with number and body prefilled. This works fine in iphone prior to ios 5.
In IOS 5, clicking on the button does not lead to sms applicatin. Is there any change in IOS 5 for sms url scheme which i am missing. Here is what i am using
sms:2062142930?body=Mobile%20Inquiry&
Thanx
zAfar

A: Perhaps try this without a message body. The Apple URL scheme reference [1] says this about text links:

*

*The sms scheme is used to launch the Text application. The format for URLs of this type is "sms:", where  is an optional parameter that specifies the target phone number of the SMS message. This parameter can contain the digits 0 through 9 and the plus (+), hyphen (-), and period (.) characters. The URL string must not include any message text or other information*

So while this may have worked in the past they may have enforced the last part (must not include any message text), probably to mitigate some misuse.
[1] http://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/iPhoneURLScheme_Reference.pdf


text:
Q: Parsing XML with PHP I have a simple xml file.  I know which fields it will have ahead of time.  What can you guys recommend is the best way for me to get the value of those fields using php?
Thank you :)

A: SimpleXML is great for quick reading/writing of XML files. Here's an example:
<root>
   <node>
      Text
   </node>
</root>

$xml = new SimpleXMLElement('xml_file.xml', 0, true);
echo $xml->node->sub; // Displays "Text"

A: Simplexml works great.

A: You can go with XML Parser, however the nice and simply way is to use SimpleXML


text:
Q: replace string after each second occurence of character Working with a javascript-variable, I want to replace each occurence of a word (in the example: 'OR' with the ||-sign), but only if it does NOT occur in a doublequoted string.
Is it possible using a regular expression?
An example of what I'm looking upon:
'one OR " two OR " OR three OR five OR " OR six "'.replace( regex , ???) is giving
'one || " two OR " || three || five || " OR six "'

I've tried with:
regex = new RegExp("([^\"]*)(OR?)([^\"]*\"[^\"]*\")" , "gi");
text = text.replace( regex , "$1||$3");

result:
'one || " two OR " OR three OR five || " OR six "'

which leaves me with some ORs to be replaced.
If I try to do the replacement one more time, to get rid of the remaining ORs, the replacement does (of course) not work:
'||ne || " two OR " OR three || five || " OR six "'

The letter 'o' in 'one' has been replaced with the ||-sign, which wasn't intended!
Is it possible to do with with an regExp?

A: OKAY you want regex? I will give you regex:
var str = 'one OR " two OR " OR three OR five OR " OR six "';
var res = str.replace(/OR/g, '||');
console.log(res.replace(/(.*?)(\".*?)\|\|(.*?\")/g, '$1$2OR$3'));

ENJOY MADI !

A: Rather than try to do this with a single regex, I would split up the work:
spl = text.split(/(".*?")/);
result = "";
spl.forEach(function (piece) {
    if (~piece.indexOf('"')) {
        result += piece;
    }
    else {
        result += piece.replace("OR", "||");
    }
});

http://jsfiddle.net/UkBZF/

A: Use this:
var str = 'one OR " two OR " OR three OR five OR " OR six "';
var res = str.replace(/or/gi,"||");

This will replace all or words case-insensitive.


text:
Q: Sign conventions in Devoret Les Houches course on quantum fluctuations in electrical circuits In this article on p. 364 Devoret writes the "equations of motion" (using KCL) for the electric circuit shown on p. 363. He uses flux instead of voltages.
The sign convention he uses, as shown on p. 360 is strange for me since I was taught that, on passive elements, the direction of the voltage and the current should be the same. As Devoret's convention seems to be the opposite, the laws for the passive elements should hold with a sign opposite the usual one.
The next problem is that however I try to choose the directions of currents going into or coming from the node, I can't get the equations 2.14 and 2.15. Please explain how to derive those equations.

A: Isn't it just a convention you have to choose once and for all. It's all about how to pass from Maxwell to lumped element circuits. Especially, I can choose the two different conventions (all quantities are vectorial in the following)
$$E=\pm\nabla V$$
since I didn't choose my field-to-potential rules yet. Usually one chooses to conform to the classical mechanics where force and potential go as $F=-\nabla V$ and choose then $E=-\nabla V$ alongside the usual Lorentz force $F=qE + v\times B$.
Then integrate the definition above along a line, one has
$$\int_{a}^{b}E\cdot dl=V\left(a\right)-V\left(b\right)$$
which is nothing more than the relation (2.1) in Devoret's lecture. Remark: Devoret clearly notes $v_{b}$ what I call $V\left(a\right)-V\left(b\right)$.
If one chooses (as Devoret) that $V\left(a\right) > V\left(b\right)$ (the voltage is positive by convention), one has that $E$ is opposed to $V=V\left(a\right)-V\left(b\right)$ from the relation $E=-\nabla V$.
Finally, the definition of the current is given by the Ohm's law in circuits: $j=\sigma E$, and so the current is opposed to the voltage convention, as the electric field along the (lumped) element.

A: Partial answer here about what the author means by flux:

We now introduce the flux $\phi_n$ of a node $n$ which is defined by the time integral of the voltage measured along the path connecting the node to the ground on the spanning tree. (Defined a few pages prior to 363.)

It then seems $\dot\phi$ is voltage as we would normally define it.


text:
Q: Android: How does Application class work with remote processes? Say that my app implements a subclass of Application has 2 different services running different processes.
What happens if I call getApplication() in each Service? Will I get back 2 completely independent instances, 1 for each process?
If so, then will the 2 instances be somehow linked? In other words, would modifications made to the instance in one process show up in the instance made in the other?

A:
Say that my app implements a subclass of Application has 2 different services running different processes.

99.9999% of Android applications do not need this, and it wastes RAM, CPU, and battery.

Will I get back 2 completely independent instances, 1 for each process?

Of course. They are different processes.

If so, then will the 2 instances be somehow linked?

No.


text:
Q: How to save css property with jquery?     $(document).ready(function(){
    $("#coverValue").click(function(){
      var img = $("input[name='cover']:checked").val();
     $(".backgroundImage").css("background-image" , "url("+ img +")");
     $(".backgroundImage").css("background-size" , "100% 100%");
   });
});

So I have this code which does what it is supposed to, it applies the image to the wanted cover area. Now how do I actually save it so that the image stays on refresh?


text:
Q: How to run a function after wp() in the wp-blog-header.php file? I want to run a function after the wp(); line in the file wp-blog-header.php, what is the proper hook to use here?
<?php
/**
 * Loads the WordPress environment and template.
 *
 * @package WordPress
 */

if ( !isset($wp_did_header) ) {

    $wp_did_header = true;

    // Load the WordPress library.
    require_once( dirname(__FILE__) . '/wp-load.php' );

    // Set up the WordPress query.
    wp();

    /********************************************
       I WANT TO RUN THE FUNCTION AT THIS POINT
     ********************************************/

    // Load the theme template.
    require_once( ABSPATH . WPINC . '/template-loader.php' );

}

Why do I need the hook
We are migrating to a new website and we have to care about the old URLs, so what I did:

*

*Added the following rewrite rule to our NGINX config file:

rewrite \D+(\/\d+\/\D+)$ /index.php?redirect=$1 break;
This rule will add an extra parameter redirect to the URL (old URL) with a value that I will be using to get the new final URL.

*Then I will run the following code to get this value from the incoming URL and get the final URL by querying a 2-columns table that maps each value redirect_from with a final URL redirect_to:

/**
 * 1. Check if the URL has a parameter [redirect]
 * 2. If NO, proceed to the next step
 * 3. If YES, then get that parameter value and look into [redirects] table
 * 4. If you found a row that has that value, then get the [redirect_to] value
 * 5. Redirect to that URL [redirect_to]
 */

if (isset($_GET['redirect'])) {
    // Get the parameter value from the URL
    $redirect_from = $_GET['redirect'];
    // Add the table prefix to the table name
    $table_name = $wpdb->prefix . 'redirects';
    // The SQL query
    $query = "
        SELECT redirect_to
        FROM $table_name
        WHERE redirect_from = '$redirect_from';
    ";
    // Run the SQL query and get the results
    $result = $wpdb->get_results($query, OBJECT);

    // If there was a result then do the redirection and exit
    if (wp_redirect($result[0]->redirect_to)) {exit;}
}

Note:
No way to get the new URLs from old URLs, here is an example of the old and new URLs:
Redirect from:
http://www.example.com/category/sub-category/post-id/slug
to:
https://www.example.com/category/sub-category/yyyy/mm/dd/slug


text:
Q: Oracle / windows hardware recommendation I'm specifying a Windows server to run Oracle for (time based) performance tests of our application.
Although the total data volume & number of users will be low, we would like the performance to be comparable to a high-powered server which is hosting many users & much more data; in other words the type of machine a large enterprise client would have.
My questions are:
- is this realistic, can we get comparable performance?
- if so, any things to look out for in the server specification?
Many thanks

A: I've just setup some HP DL380 G6 servers for a departmental level Oracle database.
8 cores, i7, 12+ GB of RAM.
8 15k rpm disks in a 2u rack mount.
We got ours for about $AUD 15,000
Not sure what your budget is though... ideas vary about what is 'enterprise' level.

A: I would aim for the enterprise level hardware, then something like Swingbench / Hammerora to generate accurate data volumes and load levels. If the application is well designed, it should scale. If it is poorly designed, it may work wonderfully for small data/user levels then fail miserably when trying to scale up.


text:
Q: How to install numpy in python with Pynsist If i have built an application using Pynsist package and then after the installation of that application, I will have a numpy package in the pkg folder of the application path just like what i mentioned in the installer.cfg.
But there wont be any numpy in the site-packages of Python 2.7 (installed because of the python installer downloaded by NSIS built application.
So how would the python know if there is a numpy in the computer or not?
In other words, how would the numpy package in the application folder will link itself to Python lib/site-package folder? Do we need to copy that folder into the site-package location or am I missing something?
Below is the installer.cfg code
[Application]
name=FaceLock
version=1.0
# How to launch the app - this calls the 'main' function from the 'myapp' package:
entry_point=openApplication:self

[Python]
version=2.7.14

[Include]
# Packages from PyPI that your application requires, one per line
# These must have wheels on PyPI:
pypi_wheels=opencv-contrib-python==3.4.1.15
            numpy==1.14.0

# To bundle packages which don't publish wheels, see the docs on the
# config file.
packages=cv2
        PIL
        Tkinter
        glob

# Other files and folders that should be installed
files=detector.py
        dataSetGenerator.py
        trainData.py
        storeDictionary.py
        CheckFace.py
        CheckFace.py
        Classifiers/
        trainer/
        Trying/

A: Here, to let the application know that numpy has also to be imported, we add a dependency in installer.cfg file. The dependency is: anaconda-project.
Now the numpy can be imported properly.


text:
Q: Malloc an array of an array of structs Objective
Dynamically create an array of an array of Element strucs (defined below)
typedef struct {
    void* data;
    } Element;

Question
I know how to malloc an array of Element strucs
Element* arrayOfElements = malloc(4 * sizeof(Element));

But then how do I Malloc an array of the above? (an array of arrayOfElements)
Question 2
Lets say the array of arrayOfElements is called arrayOfArrayStruc how would I proceed to set values inside of it
For Example I want to copy 65 to arrayOfElements[2] which is inside arrayOfArrayStruc1 how would I got about that ?
I know how to do that if I wanted to copy 65 straight to arrayOfElements[2]
arrayOfElements[2].data = malloc( sizeof(int) );
ptr = arrayOfElements[2].data;
*ptr = 65;

but im not sure how to do that if arrayOfElements[2] is inside arrayOfArrayStruc1.
EDIT
To make it more clear my goal i've made a picture

So in green is the structure Element defined by
typedef struct {
    void* data;
    } Element;

Then in red ( which had 4 green boxes) is an Array of Element structures which I malloc'd using
Element* arrayOfElements = malloc(4 * sizeof(Element));

What im looking to do is store the above ^^ in an array or make an array of pointers (which is the blue box with red boxes in it)
So in the picture "Array Of Element" holds 4 Element Structures, then I want to make an array to store 4 "Array Of Element" (or an array of 4 pointers to point to each "Array of Element")

A: arrayOfElements is the name of a pointer variable. You cannot have an array of names.
You could have an array of pointer variables. You can write the code for that, it is the same as the code for an array of int, but use a pointer type instead of int.  Then, you would need to initialize each of those pointer variables in the array the same way as you are doing now.
However, as posted, the question asked for "array of arrays", not "array of pointers".  An "array of arrays" is an array where the element type is an array (not a pointer).
Here is a non-dynamically-allocated array: int x[4][5]; . This is an array of 4 elements, with each element being an array of 5 ints.
To dynamically allocate one of these, it is the same code as dynamically allocating any array of 4 elements.  We just use int[5] as the element type, instead of int or whatever.
The type of the pointer to the first element is: "pointer to int[5]".  In C syntax this is written int (*)[5]  -- not int *[5] which is an array of pointers.
One way to write the code would be:
int (*px)[5] = malloc(4 * sizeof(int[5]));

hopefully you can see the similarity between this and the malloc in your question. We just replaced Element with int[5]. (So, your job now, is to use Element[5] instead of int[5]. Or whatever size instead of 5).
To avoid repetition (and so avoid the possibility of errors) it's possible to use the common idiom:
int (*px)[5] = malloc(4 * sizeof *px);

which is 4 elements each of the right size for what the pointer is pointing to.

A: If you want an array of Element* then you could do something like this where is n is the number of pointers:
Element** arrayOfStructs = malloc( n* sizeof(Element*) );

So for n = 4; you get an array of 4 pointers:
arrayOfStructs
+---+
|   | ->
+---+
|   | ->
+---+
|   | ->
+---+
|   | ->
+---+

Now allocate for each entry in the arrayOfStructs so if m is the number of Elements:
for (int i = 0; i < n; ++i)
{
  arrayOfStructs[i] = malloc(m * sizeof(Element));
}

Since each element has a data pointer, you need to allocate what that points to as well:
for (int i = 0; i < n; ++i)
{
  arrayOfStructs[i] = malloc(m * sizeof(Element));
  for (int j = 0; j < m; ++j)
  {
    arrayOfStructs[i][j].data = malloc(sizeof(int));
  }
}

After this you will have the following in memory:
Let's say m = 3;
arrayOfStructs
+---+    +---+---+----+
|   | -> |   |   |    |  array of Elements
+---+    +---+---+----+    +---+---+----+
|   | -------------------> |   |   |    |
+---+    +---+---+----+    +---+---+----+
|   | -> |   |   |    |
+---+    +---+---+----+    +---+---+----+
|   | -------------------> |   |   |    |
+---+                      +---+---+----+

each element in "array of Elements" 1..3(or rather 0..2) point to a different "data" (below  on array of Elements is turned around 90 degrees so I can more easily draw boxes):
+---+    +---+
|   | -> |   | integer
+---+    +---+   +---+
|   | ---------> |   |
+---+            +---+     +---+
|   | -------------------> |   |
+---+                      +---+


text:
Q: Conditional formatting for multiple rows (highlight lowest value in each) I have a table in a sheet in Excel with over 2000 rows and about 500 columns of data (numbers). Values in a particular column header are being compared to each row underneath that header, and I am using a VBA function to calculate these values (in other words, I am comparing the value in B1 to the values in A2 through A2146, the value in C1 to the same range, etc). I want to highlight the lowest number in each row by filling the cell. I have researched this issue and tried to solve the problem by implementing this solution, but by using MIN instead of MAX:
=A1=MIN($A1:$TX1)

Columns A through TX contain data.
However, when I use this function as a formatting rule, Excel highlights the wrong values and sometimes multiple values in a row. For example, I have a row with a cell containing the value 10.2, which is the only cell highlighted in this row, even though it is neither the MIN nor MAX of the specified row. Additionally, I have another row which contains values 10.6, 8.4, 5.2, and 20.8. Each one of these values is highlighted based on the formatting rule above, though 5.2 is the obvious MIN; the other three cells with the aforementioned values, then, should not be formatted.
How can I remedy this? I have tried adjusting relative/absolute cell references to determine if this could be the problem, but I am quite sure that the way I'm referencing the cells is correct.

A: Courtesy @barry houdini  (copied from a Comment):

Select the whole range of numbers B2:TX2146 (you can do that by typing that range in the box above A1 then press RETURN). Now set CF with the formula that applies to top left cell, i.e. =B2=MIN($B2:$TX2)


text:
Q: Visual studio doesn't let compile "Sgen could not be run" Getting the error:
"The specified task executable "sgen.exe" could not be run. The filename or extension is too long F:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets   3408"

And Warning:
"The command-line for the "SGen" task is too long. Command-lines longer than 32000 characters are likely to fail. Try reducing the length of the command-line by breaking down the call to "SGen" into multiple calls with fewer parameters per call.   DAYAnalytics    F:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets 3408"

At this part of Microsoft.Common.CurrentVersion.targets :
<SGen
    BuildAssemblyName="$(TargetFileName)"
    BuildAssemblyPath="$(IntermediateOutputPath)"
    References="@(ReferencePath)"
    ShouldGenerateSerializer="$(SGenShouldGenerateSerializer)"
    UseProxyTypes="$(SGenUseProxyTypes)"
    UseKeep="$(SGenUseKeep)"
    KeyContainer="$(KeyContainerName)"
    KeyFile="$(KeyOriginatorFile)"
    DelaySign="$(DelaySign)"
    ToolPath="$(SGenToolPath)"
    SdkToolsPath="$(TargetFrameworkSDKToolsDirectory)"
    EnvironmentVariables="$(SGenEnvironment)"
    MSBuildArchitecture="$(SGenMSBuildArchitecture)"
    SerializationAssembly="$(IntermediateOutputPath)$(_SGenDllName)"
    Platform="$(SGenPlatformTarget)"
    Types="$(SGenSerializationTypes)">

The explanation is pretty straightforward, But I don't understand how to fix it.
How do I reduce the command line length?

A: Set the "Generate serialization assembly" option in the Build options to "Auto" or "Off", unless you need them (that is, you make extensive use of the XmlSerializer), in which case you'll find more info here: Generating an Xml Serialization assembly as part of my build


text:
Q: App is terminating because of timer I am creating an app which deals with day to day activity. In my app user create some task to improve him/her. I'm using coredata to store data of user task.
In my app I have a NSTimer, and a selector - (void)Time_Update
timer = [NSTimer scheduledTimerWithTimeInterval:40.0f target:self selector:@selector(Time_Update) userInfo:nil repeats:YES];

My app also have delete method for deleting task. The problem is when timer call and delete task occurs at same time my app crashes.
If anyone can help me with this problem. Ask me if you need any other information about it.
This is crash log


text:
Q: Golang language, combine some fields of anonymous structure? Database entities, retention and data mapping.
type User struct{
        UserId int
        Org   int
        Name string
        Password string
        Sex int
        Age  int
        Avatar string
 }
type Address struct{
     AddressId int
     UserId int
     Province int
     City int
     District int
     Address int
     Description string
}

In DAO, I want to combine, cut, and expand the entity structure...
for example:
      type UserInfo struct{
           User
           []Address
       }

But the anonymous structure is embedded and can only be quoted in its entirety. How can I quote some fields?
    type UserInfo struct{
           User
           []Address

           Password string `json:"-"`
           Sex int `json:"-"`
           Age  int `json:"-"`
       }

A: You can't "quote" some fields. You may embed (or use a regular field) of User, or if you don't need all its fields, just explicitly list the needed ones.
Don't be afraid to repeat 3 fields. Quoting Sandi Metz:

Duplication is far cheaper than the wrong abstraction.

If you need "too many" fields and you do want to avoid duplicates, you may put those fields into another struct, and have that embedded both in User and in UserInfo:
type BaseUser struct {
    Password string `json:"-"`
    Sex      int    `json:"-"`
    Age      int    `json:"-"`
}

type User struct {
    BaseUser

    UserId int
    Org    int
    Name   string
    Avatar string
}

type UserInfo struct {
    BaseUser
    Addresses []Address
}

Note that you may choose to use a struct tag when embedding BaseUser to exclude it from JSON marshalling instead of marking all of BaseUser's fields.

A: You can try this
type UserInfo struct{
    User
    Addresses []Address

    Password string `json:"-"`
           Sex int `json:"-"`
           Age  int `json:"-"`
       }