text:
Q: Not Connecting Gatt Server I trying to connect two android device over the Gatt Protocol.
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.ParcelUuid;
import android.util.Log;

import java.util.HashSet;
import java.util.Set;

public class GattServer {
    private final String TAG = GattServer.class.getSimpleName();

    private Context applicationContext;
    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;
    private LocationManager locationManager;

    BluetoothLeAdvertiser bluetoothLeAdvertiser;

    private static GattServer gattServer;
    private BluetoothGattServer bluetoothGattServer;

    private Set<BluetoothDevice> connectedDevices = new HashSet<>();

    public GattServer(Context applicationContext) {
        this.applicationContext = applicationContext;
        bluetoothManager = (BluetoothManager) applicationContext.getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        locationManager = (LocationManager) applicationContext.getSystemService(Context.LOCATION_SERVICE);
        registerBluetoothStateReceiver();
    }

    public static GattServer getInstance(Context context) {
        if (gattServer == null) {
            gattServer = new GattServer(context.getApplicationContext());
        }
        return gattServer;
    }

    private BroadcastReceiver bluetoothStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
            switch (state) {
                case BluetoothAdapter.STATE_ON:
                    println("Bluetooth adapter state is changed to ON");
                    break;
                case BluetoothAdapter.STATE_OFF:
                    println("Bluetooth adapter state is changed to OF");
                    break;
                default:
                    // Do nothing
            }
        }
    };

    private void println(String message) {
        Log.e(TAG, message);
    }

    private void registerBluetoothStateReceiver() {
        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        try {
            applicationContext.registerReceiver(bluetoothStateReceiver, filter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void unregisterBluetoothStateReceiver() {
        try {
            applicationContext.unregisterReceiver(bluetoothStateReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void destroy() {
        stop();
        unregisterBluetoothStateReceiver();
        gattServer = null;
    }

    private AdvertiseCallback advertiseCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);
            println("Advertise Started");
            listener.onAdvertiseStarted();
        }

        @Override
        public void onStartFailure(int errorCode) {
            super.onStartFailure(errorCode);
            println("Advertise Failed : " + errorCode);
            listener.onAdvertiseFail(errorCode);
        }
    };

    private void startAdvertising() {
        bluetoothLeAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
        if (bluetoothLeAdvertiser == null || !bluetoothAdapter.isMultipleAdvertisementSupported()) {
            Log.e(TAG, "Failed to create advertiser");
            listener.onAdvertiseFail(-1);
            return;
        }

        AdvertiseSettings settings = new AdvertiseSettings.Builder()
                .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
                .setConnectable(true)
                .setTimeout(0)
                .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
                .build();

        AdvertiseData data = new AdvertiseData.Builder()
                .setIncludeDeviceName(true)
                .setIncludeTxPowerLevel(false)
                .addServiceUuid(new ParcelUuid(GattServerConfiguration.SERVICE_UUID))
                .build();

        bluetoothLeAdvertiser.startAdvertising(settings, data, advertiseCallback);
    }

    private BluetoothGattServerCallback gattCallback = new BluetoothGattServerCallback() {
        @Override
        public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
            super.onConnectionStateChange(device, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                println("Device Connected : " + device.getAddress());
                connectedDevices.add(device);
                listener.onDeviceConnected(device);
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                println("Device Disconnected : " + device.getAddress());
                connectedDevices.remove(device);
                listener.onDeviceDisconnected(device);
            }
        }

        @Override
        public void onServiceAdded(int status, BluetoothGattService service) {
            super.onServiceAdded(status, service);
            Log.d(TAG, "onServiceAdded() called with: status = [" + status + "], service = [" + service + "]");
            listener.onServiceAdded();
        }

        @Override
        public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
            Log.d(TAG, "onCharacteristicReadRequest() called with: device = [" + device + "], requestId = [" + requestId + "], offset = [" + offset + "], characteristic = [" + characteristic + "]");
            listener.onReceive(device, characteristic);
        }

        @Override
        public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
            super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);
            Log.d(TAG, "onCharacteristicWriteRequest() called with: device = [" + device + "], requestId = [" + requestId + "], characteristic = [" + characteristic + "], preparedWrite = [" + preparedWrite + "], responseNeeded = [" + responseNeeded + "], offset = [" + offset + "], value = [" + value + "]");
        }

        @Override
        public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) {
            super.onDescriptorReadRequest(device, requestId, offset, descriptor);
            Log.d(TAG, "onDescriptorReadRequest() called with: device = [" + device + "], requestId = [" + requestId + "], offset = [" + offset + "], descriptor = [" + descriptor + "]");

            if (GattServerConfiguration.CCC_DESCRIPTOR_UUID.equals(descriptor.getUuid())) {
                Log.d(TAG, "Config descriptor read");
                byte[] returnValue;
                if (connectedDevices.contains(device)) {
                    returnValue = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
                } else {
                    returnValue = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
                }
                bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, returnValue);
            } else {
                Log.w(TAG, "Unknown descriptor read request");
                bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, 0, null);
            }

        }

        @Override
        public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
            super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);
            Log.d(TAG, "onDescriptorWriteRequest() called with: device = [" + device + "], requestId = [" + requestId + "], descriptor = [" + descriptor + "], preparedWrite = [" + preparedWrite + "], responseNeeded = [" + responseNeeded + "], offset = [" + offset + "], value = [" + value + "]");
            if (GattServerConfiguration.CCC_DESCRIPTOR_UUID.equals(descriptor.getUuid())) {
                Log.d(TAG, "Config descriptor read");
                byte[] returnValue;
                if (connectedDevices.contains(device)) {
                    returnValue = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
                } else {
                    returnValue = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
                }
                bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, returnValue);
            } else {
                Log.w(TAG, "Unknown descriptor read request");
                bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, 0, null);
            }
        }

        @Override
        public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
            super.onExecuteWrite(device, requestId, execute);
            Log.d(TAG, "onExecuteWrite() called with: device = [" + device + "], requestId = [" + requestId + "], execute = [" + execute + "]");
        }

        @Override
        public void onNotificationSent(BluetoothDevice device, int status) {
            super.onNotificationSent(device, status);
            Log.d(TAG, "onNotificationSent() called with: device = [" + device + "], status = [" + status + "]");
        }

        @Override
        public void onMtuChanged(BluetoothDevice device, int mtu) {
            super.onMtuChanged(device, mtu);
            Log.d(TAG, "onMtuChanged() called with: device = [" + device + "], mtu = [" + mtu + "]");
        }

        @Override
        public void onPhyUpdate(BluetoothDevice device, int txPhy, int rxPhy, int status) {
            super.onPhyUpdate(device, txPhy, rxPhy, status);
            Log.d(TAG, "onPhyUpdate() called with: device = [" + device + "], txPhy = [" + txPhy + "], rxPhy = [" + rxPhy + "], status = [" + status + "]");
        }

        @Override
        public void onPhyRead(BluetoothDevice device, int txPhy, int rxPhy, int status) {
            super.onPhyRead(device, txPhy, rxPhy, status);
            Log.d(TAG, "onPhyRead() called with: device = [" + device + "], txPhy = [" + txPhy + "], rxPhy = [" + rxPhy + "], status = [" + status + "]");
        }
    };

    private void startServer() {
        bluetoothGattServer = bluetoothManager.openGattServer(applicationContext, gattCallback);
        if (bluetoothGattServer == null) {
            println("Server is null");
            return;
        }

        bluetoothGattServer.addService(GattServerConfiguration.createGattService());
    }

    public void launch() {
        if (isReady()) {
            startServer();
            startAdvertising();
        }
    }

    private void stopAdvertising() {
        if (bluetoothLeAdvertiser == null) return;
        bluetoothLeAdvertiser.stopAdvertising(advertiseCallback);
    }

    private void stopServer() {
        if (bluetoothGattServer == null) return;
        bluetoothGattServer.close();
    }

    public void stop() {
        stopAdvertising();
        stopServer();
        connectedDevices.clear();
    }

    private boolean isReady() {
        if (bluetoothManager == null) {
            return false;
        }

        return bluetoothAdapter.isEnabled() && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    private IGattServer listener;

    public void setCallback(IGattServer listener) {
        this.listener = listener;
    }
}

Above code, successfully starts advertisement,
Another device successfully receive device in LE Scan (Using UUID's filter)
But connectGatt() not providing any callback.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            bluetoothGatt = bluetoothDevice.connectGatt(
                    getApplicationContext(), true, gattCallback,
                    BluetoothDevice.TRANSPORT_LE
            );
        } else {
            bluetoothGatt = bluetoothDevice.connectGatt(getApplicationContext(), true, gattCallback);
        }

Gatt Callback Sample Code.
private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            writeLog("onConnectionStateChange() called with: gatt = [" + gatt + "], status = [" + status + "], newState = [" + newState + "]");
            broadcastUpdate(
                    ACTION_GATT_MESSAGE,
                    "onConnectionStateChange() called with: gatt = $gatt, status = $status, newState = $newState"
            );
            if (status == 8) {
                writeLog("BLE Out Of Range");
                broadcastUpdate(ACTION_GATT_MESSAGE, "BLE Out Of Range status == 8");
            } else if (status == 19) {
                writeLog("BLE Disconnected By Device");
                broadcastUpdate(ACTION_GATT_MESSAGE, "BLE Disconnected By Device status == 19");
            } else if (status == 22) {
                writeLog("BLE Issue with bond");
                broadcastUpdate(ACTION_GATT_MESSAGE, "BLE Issue with bond status == 22");
            } else if (status == 133 || status == 62) {
                writeLog("BLE Device not found");
                broadcastUpdate(
                        ACTION_GATT_MESSAGE,
                        "BLE Device not found status == 133 || status == 62"
                );
                disconnect();
                close();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                connectDevice(bluetoothAdapter.getRemoteDevice(PrefManager.getInstance(getApplicationContext()).getLeAddress()));
                return;
            }

            if (newState == BluetoothProfile.STATE_CONNECTED) {
                connected = true;
                broadcastUpdate(ACTION_GATT_CONNECTED);
                bluetoothGatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                connected = false;
                broadcastUpdate(ACTION_GATT_DISCONNECTED);
                stopSelf();
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            writeLog("onServicesDiscovered() called with: gatt = [" + gatt + "], status = [" + status + "]");
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Intent intent = new Intent(ACTION_GATT_SERVICES_DISCOVERED);
                ArrayList<BluetoothGattService> services = new ArrayList<BluetoothGattService>();
                for (BluetoothGattService gattService : gatt.getServices()) {
                    services.add(gattService);
                }
                intent.putParcelableArrayListExtra("services", services);

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                broadcastUpdate(intent);
            } else {
                broadcastUpdate(ACTION_GATT_NO_SERVICES_DISCOVERED);
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            Log.e(
                    TAG,
                    "onCharacteristicRead() called with: gatt = $gatt, characteristic = $characteristic, status = $status"
            );

            if (status == BluetoothGatt.GATT_SUCCESS) {
                Intent intent = new Intent(ACTION_DATA_AVAILABLE);
                intent.putExtra("bytes", characteristic.getValue());
                //lintent.putExtra("data", characteristic.getValue().toString());
                broadcastUpdate(intent);
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
            Log.e(
                    TAG,
                    "onCharacteristicWrite() called with: gatt = " + gatt + ", characteristic = " + characteristic + ", status = " + status
            );

            if (canceled || !connected || writeCharacteristic == null) {
                writeLog("Return Form write 1");
                return;
            }
            if (status != BluetoothGatt.GATT_SUCCESS) {
                writeLog("Return Form write 2");
                broadcastUpdate(ACTION_DATA_WRITE_FAIL);
                return;
            }
            if (canceled) return;
            writeLog("Write Success Checking for next bytes");
            if (characteristic.getUuid().toString().equals(writeCharacteristic.getUuid().toString())) { // NOPMD - test object identity
                writeNext();
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            Log.e(
                    TAG,
                    "onCharacteristicChanged() called with: gatt = $gatt, characteristic = $characteristic"
            );

            if (characteristic.getUuid().toString().equals(readCharacteristic.getUuid().toString())) {
                Intent intent = new Intent(ACTION_DATA_AVAILABLE);
                intent.putExtra("bytes", characteristic.getValue());
                broadcastUpdate(intent);
            }
        }

        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorRead(gatt, descriptor, status);
            Log.e(
                    TAG,
                    "onDescriptorRead() called with: gatt = $gatt, descriptor = $descriptor, status = $status"
            );
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorWrite(gatt, descriptor, status);
            writeLog("onDescriptorWrite() called with: gatt = [" + gatt + "], descriptor = [" + descriptor + "], status = [" + status + "]");
        }

        @Override
        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
            super.onReliableWriteCompleted(gatt, status);
            writeLog("onReliableWriteCompleted() called with: gatt = [" + gatt + "], status = [" + status + "]");
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            super.onReadRemoteRssi(gatt, rssi, status);
            writeLog("onReadRemoteRssi() called with: gatt = [" + gatt + "], rssi = [" + rssi + "], status = [" + status + "]");
        }

        @Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            super.onMtuChanged(gatt, mtu, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                payloadSize = mtu - 3;
                writeLog("payload size $payloadSize");
            }
            enableTxNotification();
        }

        @Override
        public void onServiceChanged(@NonNull BluetoothGatt gatt) {
            super.onServiceChanged(gatt);
        }
    };

A: I solved connection issue by.
bluetoothGatt = bluetoothDevice.connectGatt(
            getApplicationContext(), false, gattCallback,
            BluetoothDevice.TRANSPORT_AUTO
    );


text:
Q: List the content of the last 5 hidden directories I was asked to list the content of the last 5 hidden directories in the current working directory with a single command. I thought something like this would do the job:
ls -a -1 | grep "^\." | tail -n 5 | ls

But it just lists the names of the last five directories.. how do I list the content?

A: ls -a -1 | grep "^\." | tail -n 5 | xargs ls

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to redirect/route IP address to another IP address? How to redirect/route an IP address to another IP address?
E.g.: 10.10.10.10 -> 20.20.20.20 and then when I type in 10.10.10.10 in my browser, it connects to 20.20.20.20.
Let's assume 10.10.10.10 and 20.20.20.20 are external IP addresses.

A: Intro Considerations
Before implementing any of this, it would be really helpful to know just what routing actually does.
Routing doesn't change network addresses.  (Well, NAT does.  And NAT can be performed while routing gets applied.  However, if you want to learn how to do something, you should be trying to keep things simple.  And it is best to think of simple/traditional routing as a separate process, because that is a much simpler way to think about it.)
Before looking at changing stuff like addresses, let's make sure there's a thorough understanding of how stuff actually works, so that we don't try to do something that will violate common network design rules (and which will probably be rejected by a majority of hardware and software that typically implements those rules).  If this stuff gets learned, then at least if we try something crazy, we will understand that what we are trying is crazy, and will be mentally prepared for the types of obstacles we are trying to face.  That is much better than not knowing these details.
About Routing
Routing is typically designed to make sure that traffic gets from one network (often called a "subnetwork", or "subnet") to another network.
When you computer sends network traffic, it is likely sending "frames" of network traffic.  These frames are called "Layer 2" traffic.  (Layer 1 focuses on physical connections, like cables or antennas and airwaves.)  Frames are delivered to MAC-48 addresses (also known as EIU-48 addresses, and much more commonly just called "MAC addresses").  The most common ways that frames get delivered are by using Ethernet (over UTP copper cabling) or Wi-Fi.
Frames tend to contain packets.  The most common types of packets these days are IPv6 and IPv4.  (Probably not in that order...)  These packets are considered Layer 3 traffic.  The packets tend to contain TCP segments or UDP datagrams, which are layer 4 traffic.  I'm using the term "layer" consistently with what is described by the "OSI Model", which tends to get taught in a lot of professional-level networking classes/training.
Now, let's say you're at 192.168.1.103 and want to communicate with 4.2.2.2.  This could be UDP port 53 traffic (DNS), but I will instead use ICMP (ping) as an example.
Typically, your computer will compare 192.168.1.103 and the size of your network, which is specified by the prefix length (e.g., IPv4 /24).  Prefix lengths (especially IPv6 /64) are most common for IPv6.  For IPv4, the size of the network is very often written out as a subnet mask.  The binary values of common subnet masks start with all the ones, with all of the zeros towards the end of the subnet masks, so you often end up with subnet masks like 255.255.255.0.  Using these examples of IPv4 /24 and 255.255.255.0, the size of the network is 256 addresses.  So the computer figures out which addresses would be at the start and end of a group of 256 addresses if all possible Internet addresses are divided into evenly-sized groups of that size.  So, if all possible Internet addresses were split into groups of 256 addresses, then 192.168.1.103 would be in a group that is goes from 192.168.1.0 and 192.168.1.255 (inclusive).
Since the desired destination is 4.2.2.2, and 4.2.2.2 is not between 192.168.1.0 and 192.168.1.255, then the traffic doesn't just get sent to 4.2.2.2's MAC address using a frame.  (We are unlikely to be able to use IPv4's Address Resolution Protocol (ARP) or Neighbor Discovery Protocol (if we were using IPv6) to discover the MAC address, because that is on a different network.  This has to do with limitations that affect ARP and IPv6 NDP.)  So, if we can't send a frame to there, how can we communicate with 4.2.2.2?
By routing.  We can find a gateway that will help us get traffic to 4.2.2.2.  For most common consumer equipment, people are often used to having just two types of networks: a network that the computer is part of, and the worldwide Internet.  (Corporations sometimes have multiple sites, and may have other networks.)  A gateway that is meant to handle addresses to anywhere in the world (the entire Internet) is sometimes called the "gateway of last resort", and much more commonly called the "default gateway".  That is the gateway that will be used for any address if there isn't a more specific gateway that happens.
So, your computer will send an IPv4 ARP request for the default gateway, which will need to be in your network.  Quite commonly, that will be the first "usable" address on your network.  (Due to some very old broadcast standards, and perhaps also due to some common confusion, many people just treat the first address of a subnet as unusable.  This includes creators of some software and hardware, so the decisions of those people often affect the rest of us.  So 192.168.1.0 may be unusable in this example.)  So 192.168.1.1 may be the first usable address, and may be the default gateway.  I will use that example.
Once your computer figures out the MAC address of your default gateway, then your computer sends out the ICMP message by using an IP packet that is addressed for 4.2.2.2, and that IP packet is part of a frame that goes to the MAC address of the gateway.
So, the network traffic containing the ICMP message doesn't actually get sent to the IP address of 192.168.1.1.  The traffic gets sent to the MAC address that is related to 192.168.1.1.
Then, your local router will pay attention to the traffic because the traffic is going to the MAC address.  Because it is a router, it will cooperate by routing the traffic.  So your router will figure out if it knows how to communicate directly to 4.2.2.2, by being on the same network.  In all likelihood, your router won't know how to get 4.2.2.2's MAC address.  So the process gets repeated, as your router will then "route" the traffic to the MAC address of another router, which may be located at your Internet Service Provider (ISP).
Now, the point in explaining all this is that even if you did manage to get your computer to translate the 10.10.10.10 to 20.20.20.20, that might be useless if the receiving equipment is not expecting traffic for 10.10.10.10.  The receiving device at 20.20.20.20 might receive the traffic, but may ignore it if the traffic is meant for 10.10.10.10.
Keep in mind that in my working example, even though the IP traffic got sent to the MAC address related to the default gateway, the IP packet's destination of 4.2.2.2 remained unchanged during the entire process of routing traffic.
So, if you are trying to change the destination IP address, that isn't simple routing.  That is NAT.  NAT is an abbreviation for Network Address Translation.  So, when network traffic involves a specific network address (10.10.10.10), it gets translated to another address (20.20.20.20).  See: NAT in Windows.
TCP's Limit
Note that a lot of Internet traffic uses TCP.  If you are trying to get a TCP connection going to 20.20.20.20, TCP's requirement for two-way communication may cause some troubles.  Even if you could get traffic sent to 20.20.20.20, then 20.20.20.20 needs to be able to successfully respond, because TCP requires two-way communication in order to complete the "TCP handshake" at the start of the TCP connection, before any of your ("payload") data gets sent.  If your software program thinks that it is sending traffic to 10.10.10.10, then your software program will not accept response traffic from 20.20.20.20.  So, in addition to NATting outgoing traffic, you may also need to be able to reverse the NAT effects if you're using TCP.  TCP is very common, e.g. HTTP (web) and SMTP (E-Mail).  The main exceptions are traffic which is very small (e.g. classic DNS which uses UDP.  Another example is ICMP) or traffic which is very sensitive to slowness (maybe VOIP, news (like stock prices, where old information is useless than re-updated newer information), real-time games).  It can be very helpful to learn whether the protocol you intend to use will rely upon a lower-level protocol like TCP.  Network sniffing (e.g., tcpdump or Wireshark) can also be quite useful in understanding why things don't work.
NAT availability
Typically, you don't bother with NAT on end user machines.  Typically, that is done by a router.  Some versions of Windows do support the feature of being a router, which means the computer can treat network traffic similar to how other routers treat the traffic.
This question has the "Windows" tag, so I'm guessing you're wanting to do this using software built into Microsoft Windows, I would think that NAT would be supported by a feature called "Routing".  Modern versions of Windows have this feature built into some software called "Routing and Remote Access" (abbreviated "RRAS").
As far as I know, RRAS is often not supported by "Home" versions of Microsoft Windows.  It is often supported by the Windows Server releases (e.g., Windows Server 2008 R2).  I think it might be supported by "Professional" end user releases, like "Windows 7 Professional".  I'm rather suspecting that this feature might be entirely missing from Home releases like "Windows 7 Home".
Even if the feature is potentially available in your version of Windows, it is probably so disabled by default that it is even uninstalled.  So you might need to go to a spot where you can install Windows Features (e.g., "Server Manager", or maybe Control Panel's applet that includes the word "Programs" as part of its name, and then the left frame of that applet may have a hyperlink for adding/installing/enabling "Features").

*

*Possible Resource: TechNet: Enable and Configure NAT

*Possible resource: TechNET: Netsh Routing IP NAT Context Commands
Now, in theory, you might be able to tell your computer to route traffic to a proxy that NATs the traffic and sends it out as a different IP address.  So what you're asking for might be possible.
Approaches
One possible alternative: Consider manipulating DNS instead of IP traffic.  e.g., point a DNS name to a different IP address, possibly by using CNAMES (if you can affect the DNS records for the relevant domain names), or by using hosts files.  Often much easier to implement, and to reverse (if you decide to undo your changes).
Chances sound very, very good that this isn't going to be the best approach for whatever you're really trying to accomplish.  Understand that trying to do things normally, according to the rules, can be very challenging.  Trying to invent your own ways of doing things is much more challenging.  It is highly inadvisable to get too inventive when designing networks before you have had experience successfully designing networks using standard methods, and you know the limitations of the standard methods (and probably also why those limitations exist), and you really know that what you're doing is better (and why it is better).  Otherwise, you're likely to run into a host of problems.  (I can speak from some experience.  Eventually, I simply learned to try doing things the straightforward way first.)
The question looks like a classic case of XY Problem.  If you're trying to accomplish something other than what you just asked for, try creating another question where you are asking for what you are really trying to accomplish.

A: You can use command:
route add 10.10.10.10 MASK 255.255.255.255 20.20.20.20 METRIC ? IF ?
you need to place appropriate numbers in place of '?'.
Found out what is metric and if here.

metric Metric : Specifies an integer cost metric (ranging from 1 to
  9999) for the route, which is used when choosing among multiple routes
  in the routing table that most closely match the destination address
  of a packet being forwarded. The route with the lowest metric is
  chosen. The metric can reflect the number of hops, the speed of the
  path, path reliability, path throughput, or administrative properties.
if Interface : Specifies the interface index for the interface over
  which the destination is reachable. For a list of interfaces and their
  corresponding interface indexes, use the display of the route print
  command. You can use either decimal or hexadecimal values for the
  interface index. For hexadecimal values, precede the hexadecimal
  number with 0x. When the if parameter is omitted, the interface is
  determined from the gateway address.

Use command route print to find out what IF value you need to use.


text:
Q: How to reduce size of fonts I have site, which size (in browser) is ~90kb. But i have 5 fonts(Bold, extra bold, medium, regular, light), which size is 600kb. It amazing size, how can i reduce it? Fonts format is woff2

A: *

*The FontForge program -
https://fontforge.github.io/en-US
With its help, you will need to remove unnecessary glyphs, export the resulting font to OTF.

*Then run the resulting file through -
https://transfonter.org
For the web, WOFF is universally suitable, but it is better to mark TTF, WOFF and WOFF2 (all the same, the one needed and determined by the browser itself will be loaded). Download the resulting archive (fonts + CSS) and connect them to the project.

*You can also use https://www.fontsquirrel.com/. This service allows you to extract unnecessary characters from the font to reduce its weight. For example, you can pull out all the Cyrillic characters, or the Latin alphabet, or the punctuation marks, or even if these are large fonts they have a lot of Chinese characters, and so on.
You can additionally compress fonts by manually editing glyphs if they contain a lot of artifacts, unnecessary anchor points, etc. As a rule, there are no such fonts, if they are not self-made, of course.


text:
Q: Is there a limit for max number of tags viewed at once? I have a rather large list of interesting tags, and when i try to use a Greasemonkey extension (forget what it is) to view all of my interesting tags at once, i get an HTTP 400 request error invalid. So, what exactly is the limit for queries such as those?
Edit: this is the extension.

A: There are two syntaxes:
https://meta.stackexchange.com/questions/tagged/fun
and this:
https://meta.stackexchange.com/questions/tagged?tagnames=fun
The latter seems to be more tolerant of long URLs.
(and for completeness, there is also a synonym of the first, like so:)
https://meta.stackoverflow.com/tags/fun


text:
Q: SQL table transform I have Table A
customerID  Product
-------------------
 101            A
 101            B
 102            B
 102            C

Want to transform it to a Table B like:
customerID  ProductA ProductB ProductC
---------------------------------------
 101             1        1        0
 102             0        1        1

My ultimate goal is to leverage this intermediate table to get Table C like this:
customerID   Product_Combo
--------------------------
 101              AB
 102              BC

I think I know how to change it from B to C. But how to go from A to B? Thanks! Suppose we do this in MS SQL and we only have three products A,B, and C.

A: You can use cursor for customerId and this sql:
declare @Products varchar(10) = '';

--start cursor
set @Products = '';
SELECT @Products = @Products + [Product]
  FROM [test].[dbo].[TableA]
  WHERE customerId = @cursor

print @Products
--end cursor

A: Simplest way would be to use case :
SELECT custId
,MAX(CASE WHEN product = 'A' THEN 1 ELSE 0 END) AS productA
,MAX(CASE WHEN product = 'B' THEN 1 ELSE 0 END) AS productB
,MAX(CASE WHEN product = 'C' THEN 1 ELSE 0 END) AS productC
 FROM A
Group by  custId

Result
custId  productA    productB    productC
 101    1             1           0
 102    0             1           1

A: You can use query like this to get into B
SELECT
    CustomerId,
    CASE
        WHEN [A] = 'A' THEN 1
        ELSE 0
    END AS ProductA,
    CASE
        WHEN [B] = 'B' THEN 1
        ELSE 0
    END AS ProductB,
    CASE
        WHEN [C] = 'C' THEN 1
        ELSE 0
    END AS ProductC
FROM #tableA
PIVOT (MAX(Product) FOR Product IN ([A], [B], [C])) AS p


text:
Q: Cannot figure out why query is failing I am trying migrate over some code that inserts data into a database to work moving forward w postgres. The code/queries below are failing and after looking at the sizes of the arrays it seems as if it should be working.
Any input as to why this is failing would be fantastic.
Where my SQL looks like:
sql = "insert into postgres.options.options (delta,gamma,rho,theta,\"impVol\",value,vega,date,ticker,\"callPut\",\"Chg\",\"maturity\",\"Symbol\",\"Strike\",\"Implied\",\"Last\",\"Vol\",\"Ask\",\"Bid\") values " \
      "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"

And where my data looks like this:
data=[0.782154229511169, 0.026557152004256603, 0.005658995525391192, -0.4087164010990902, 136.71875, 8.94733166658628, 0.02387435675989819, 20150706, u'SVXY', u'C', -2.9, 20150710, u'SVXY150710C00070000', 70.0, 0.0, 7.9, 5.0, 9.2, 8.7]

And my python code reads as:
       cur.execute(sql,data)
        conn.commit()

And my create statement on the table reads as:
CREATE TABLE options.options
(
  delta double precision,
  gamma double precision,
  rho double precision,
  theta double precision,
  "impVol" double precision,
  value double precision,
  vega double precision,
  _id text,
  date bigint,
  ticker text,
  "callPut" text,
  "Chg" double precision,
  maturity integer,
  "Symbol" text,
  "Strike" double precision,
  "Implied" double precision,
  "Last" double precision,
  "Vol" double precision,
  "Ask" double precision,
  "Bid" double precision
)

And my error is:
Traceback (most recent call last):
  File "C:/Users/jasonmellone/PycharmProjects/price_options_multithread/migrate_error_options.py", line 41, in <module>
    cur.execute(sql,data)
InternalError: current transaction is aborted, commands ignored until end of transaction block

A: There is a error in your insert statement. postgres.options.options is not a valid table because PostgreSql thinks, you mean a reference to another database. Change this:
insert into postgres.options.options...

to this:
insert into options.options...

A: You have created a table options in options schema. Whereas you are inserting with postgres schema.
Change your insert:
sql = "insert into options.options  ..."

A: Building my query string in python, and by using SQLAlchemy I was able to insert using the following logic:
def get_engine():
    engine = create_engine('postgresql+psycopg2://user:password@localhost/postgres')
    return engine

db = get_engine()
connection = db.connect()
connection.execute(sql)


text:
Q: Is there a way to print the prime number itself and the overall count after having filtered non-prime? I have the code below and it's annotated. It is essentially based on 'Sieve of Eratosthenes.' I am modifying it to have the remaining prime numbers printed and counted in the last for loop of the code. However, the output is '1There are 1 primes.'
#include <stdio.h>

#define SIZE 50000

int main(void) {
    int i, mult, count, count2;
    int flag[SIZE + 1];

    count = 0;
    count2 = 0;

    //sets up all numbers
    for (i = 1; i <= SIZE; i++) {
        flag[i] = 1;
        //printf("%d",flag[i]);
    }

    //step 1: selects the prime number
    for (i = 2; i <= SIZE; ++i) {
        if (flag[i] == 1)
            ++count;
        mult = i;

        //step 2: filters out numbers multiple of that prime number in step 1
        while (mult <= SIZE) {
            flag[mult] = 0;
            mult = mult + i;
        }
    }

    //Now that the non-prime numbers have been filtered, this then prints the number and counts the prime numbers
    for (i = 1; i <= SIZE; i++) {
        if (flag[i] == 1) {
            ++count2;
            printf("%d", i);
        }
    }

    printf("There are %d primes. \n", count2);

    return 0;
}

A: In your second for loop, you start with:
mult = i;

and then in the while that is just after you set:
flag[mult] = 0;

In essence you say this number is not a prime.
If you replace the line mult = i with:
mult = i + i ;

Then your program is working.


text:
Q: Trying to show an Off Canvas over the current content - CSS - HTML I have some off canvas content that I am showing with a basic slide animation.  The sidebar just slides in from the right side.  When the content slides in, it pushes my current content to the left, and I just want the content to be displayed over the content on the page.  Here is my html:

And here is the important css:
@media screen and (max-width: 767px) {
  .row-offcanvas {
    position: relative;
    position: relative;
    -webkit-transition: right .3s ease-in;
    -most-transition: right .3s ease-in;
    transition: right .3s ease-in;
  }
  .sidebar-offcanvas {
    right: -80%;
    width: 80%;
    position: absolute;
    top: 0;
    background-color: #F7F7F7;
    padding: 0;
    height: auto;
  }
  &.active {
    right: 80%;
  }
}

What do I need to do?


text:
Q: SELECT non-duplicate records joined to table with duplicate date records, by last date The title probably doesn't make much sense, so I'll try to be descriptive here in the subject.
Consider 2 tables in MSSQL2005:
Cases table:
id int,
caseNo string

Events table:
id int,
caseID int,
eventDate date/time

I need a select statement for a view which will return single rows of:
cases.caseNo, events.eventDate (date part only)
They are related/joined by events.caseID = cases.id many to one. There are multiple event records per case records.  I want the resultset to be single caseNo with the latest/most recent value of events.eventDate.
Thanks in advance.

A: There are 5 ways to do this, these are described here: Including an Aggregated Column's Related Values
Basically something like this if you need more than just the date and the case id
select e.*,c.*
from(
select caseID,max(evendate) as MaxEventDate
from Events
group by caseID) x
join Cases c on c.Id = x.caseID
join Events e on e.eventDate =  x.MaxEventDate
and e.caseID = x.caseID

otherwise just group by id and use max for date
select  max(e.EventDate) as MaxEventDate,
    c.CaseNo
from
    Cases c
    join Events e on
        e.caseid = c.id
group by c.caseNo

A: You can just use the max function to grab the latest date, like so:
select
    c.caseNo,
    max(e.eventDate) as eventDate
from
    cases c
    inner join events e on
        c.id = e.caseid
group by
    c.caseNo


text:
Q: Clean LC-Tank drive and thankyou for any support.
I have the following circuit

Here we have a circuit where are two coupled LC-Tanks (1.5MHz) and the second one has a load modulator (MOSFET).
We want to use the coupling as a transmision media and therefore modulate the load with the MOSFET ad sense it on the driving side. (I think NFC is doing it such way. But I can not find any schematic)
The only way I can see to detect the load on the inductor on the driving side is by measuring the current flowing in the 100Ohm resistor. In simulation it works, but only when driven with a sinusoidal wave at natural LC frequency that do not produce current spikes on the drive resistor but rather produces a clean very low amper sine.
I have evaluated different driving solutions where the cleanest sine is produced while including the tank in a LC oscillator. But the current produced through the tank is all about clean and constant as the OP-AMP switch from - supply to + supply.
How will you suggest to drive the LC tank in order to be still able to detect load variations on the coupled inductor?
EDIT:
I'm editing here as i noticed from answers that my question may be misleading. From simulations i'm feeling good with the simple RLC configuration after the sine generator. As i'm transmitting between two guite good coupled inductors with a very low modulation frequency (5-10kHz) and i'm getting a good difference (from 3mA to 15mA peak-to-peak) on the 100Ohm resistor. But i need a circuit that helps me drive LC tank with good sine wave, as when the sine is not clean the current spikes (at carrier frequency) overcome the current difference that is producing the load MOSFET on the transmitter side.

A:
How will you suggest to drive the LC tank in order to be still able to
  detect load variations on the coupled inductor?

Drive it via a small capacitor from the voltage source. In this way the Q of the tank is kept reasonably high and any modulations from the coupled secondary circuit can more easily be seen. You will still need some "loss" component so maybe keep the 100 ohm resistor but put 2.2pF (or maybe a bit bigger) in series with it.

A: This is just a comment, but too big to fit in the comment section.
You never start a filter design for a transmitter receiver by saying " How do you drive a tank better??
You start a design with required parameters like Frequency band, power level, impedance,  band pass gain, Q, band reject levels, insertion loss, return loss or define all the "s parameters" with upper lower limits.

But FYI, series resonators are driven from Voltage sources with low series R for high Q and parallel tanks are driven from current sources for high Q (like common emitter) but poor for RF current since they often too high impedance for transmitters and easily detuned but ok for receivers.

And complex 5th order filters may have complex parameters for the passband and band-reject for either deep notches for interference rejection impedance matching and is beyond the scope of this question.

FYI, Here is an NFC transceiver filter from Texas Instruments with both Tx and Rx using series resonators and not coupled shunt resonators as you requested. So I suspect your antenna is the series resonator kind.

Passive high nth order Filter designs require much reading to learn how they work to get voltage gain, impedance matching , band pass and band reject all working harmoniously. The value of n is the number of equivalent reactive L and C components in a filter. Note that the receiver has two pins here and the transmitter has an on-board loop and connector for external.


text:
Q: Cms Pages Layout Update Xml not from admin Hi i'm using below code in my cms page->design->layout update xml
<reference name="left">
<block type="cms/block" name="Cms Pages Left Sidebar" as="Cms Pages Left Sidebar" before="-">
       <action method="setBlockId"><block_id>cms_pages_left_sidebar</block_id></action>
    </block>
</reference>

Everything working fine, but i have more then 200 pages, so it's a tidious process to update in all pages.
So i've added the same in mytheme's config.xml but now the issue is it's coming in product and category pages too.
Is there any way to show them only in cms pages ?

A: Welcome to Magento.SE and great job getting this far in figuring out layout XML.
Firstly, I would advise you that you do not place this in the config.xml file. It is advisable to place it into a layout update file.
Secondly, you're very close here - the only thing you need to do is target the CMS "handle" (a fancy name for the topmost node in the layout xml) - looks like you're already targeting something - likely default or root.
Instead use this:
<cms_page>
    <reference name="left">
    <block type="cms/block" name="Cms Pages Left Sidebar" as="Cms Pages Left Sidebar" before="-">
           <action method="setBlockId"><block_id>cms_pages_left_sidebar</block_id></action>
        </block>
    </reference>
</cms_page>


text:
Q: Searching dates within a Datatable returning no results I can't seem to get any results back when searching a datetime column.
DateCreated field is saved as datetime type, within the mssql database.
// datatable
"data": "DateCreated", "name": "DateCreated",
                 render: function (data, type, row) {
                 return moment(data).format('DD-MM-YYYY HH:mm:ss A');
                }

//  code within controller
searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();

tAccounts = dbcontext.ApproveAccounts.Where(x => x.UserID.ToString().Contains(searchValue) || x.DateCreated.ToString().Contains(searchValue)).ToList();

Any pointers much appreciated.
Joe

A: You could attempt to parse the searchValue as a DateTime (adjust as needed per your culture and style). Then compare the Dates (eliminating time element). This assumes nothing will match DateTime.MinValue which is what you will get if parsing fails.
_ = DateTime.TryParse(searchValue, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime searchDt);

tAccounts = dbcontext.ApproveAccounts
    .Where(x => x.UserID.ToString().Contains(searchValue) || x.DateCreated.Date == searchDt.Date).ToList();

A: _ = DateTime.TryParse(searchValue, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime searchDt);

tAccounts = dbcontext.ApproveAccounts
    .Where(x => DbFunctions.TruncateTime(x.DateAccountCreated) == searchDt.Date || x.UserID.ToString().Contains(searchValue)).ToList();


text:
Q: Plotting seasonal data, with years on top of each other in SAS? Hi I have a time series data table from October 2013 to October 2016. I would like to plot the time series from October 2013 to November 2014, October 2014 to November 2015, and October 2015 to November 2016 on top of each other on the same graph to analyze any seasonal trends.
My idea is to create separate data tables with each subsegment, but is there an easier way to do this in SAS?
This is an example of the data table I want to plot the seasonality of.

A: The workflow I think here is to add a group variable that indicates, say, year, which has the same value for all rows you want plotted in one plot-grouping.
Then you use the group statement in whatever plot type you want.  Something like:
data stocks_years;
  set sashelp.stocks;
  date_year = intck('YEAR','01AUG1986'd,date,'c')+1986;
  date_month= month(date);
run;

proc sgplot data=stocks_years;
  vline date_month/response=close group=date_year stat=mean;
run;

This is an example of doing that to see the average close per month of the three stocks in the SASHELP.STOCKS dataset.  It is a terrible plot of course but it should give you some idea of what it would look like. Each of those differently colored lines is from a different year (aug->jul being defined as a year, with the number being the year number of aug).

A: The lead off provided by Joe gave me everything I needed. Here is the completed code for anyone else's reference.
%macro Plot_Seasonal_Worse_TP(tbl_name, tp, cutoff_date);
/*tp = transition probability */

proc sql;
create table &tbl_name._trim as
    SELECT *
    FROM &tbl_name
    WHERE asofdt > &cutoff_date;
run;

data &tbl_name._trim;
set &tbl_name._trim;
    date_year = intck('YEAR','01NOV2013'd,asofdt,'c')+2014;
    date_month= MOD(month(asofdt)+2, 12);   /* move november and december of previous year to front of time series */
run;

proc sgplot data=&tbl_name._trim;
  vline date_month/response=&tp group=date_year;
  title &tbl_name  (&tp);
run;

%mend Plot_Seasonal_Worse_TP;

Output looks like this as well.


text:
Q: Matching gnmap Output in Python I'm trying to match the following line in a gnmap file:
23/open/tcp//telnet
and I'd like it to out put just the port number. Sometimes the port is 23. Othertimes, its 2323 or 6000, or some other number.
I've tried this code, but the regex will not match properly:
import re

class REMatcher(object):
    def __init__(self, matchstring):
        self.matchstring = matchstring

    def match(self,regexp):
        self.rematch = re.match(regexp, self.matchstring)
        return bool(self.rematch)

    def group(self,i):
        return self.rematch.group(i)

gnmap_file = "telnet.gnmap"

with open(gnmap_file, "r") as f:
    lines = f.readlines()
    for line in lines:
        m = REMatcher(line)
        if m.match("([0-9])*\/open\/tcp\/\/telnet"):
            print m.group(1)

I think I'm missing something in the regex. Any help would be appreciated.


text:
Q: laravel 5.7 cURL error 60: SSL certificate problem: unable to get local issuer certificate i am using this package for laravel 5.7
composer require ipecompany/smsirlaravel

all my links are working fine but the package admin panel link gives the ssl error .
i tried to download cacert.pem file and place it both on
C:\wamp64\bin\php\php7.1.9\extras\ssl\cacert.pem

and
C:\wamp64\bin\apache\apache2.4.27\bin\cacert.pem

but yet no luck with this error
cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

and i am using wamp 3.1.0 and php version 7.1.9 so any idea how this error can be solved ??

A: Try to disable check:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

UPDATE
ok, sorry, my bad, didn't noticed that you are using external package. This package uses Guzzle, to disable in Guzzle this check you need to add this option.
As an option you need to create your own class and extend this Ipecompany\Smsirlaravel\Smsirlaravel class and override methods. The bad thing is that in each method of this class class creates new instance of GuzzleClient, so you need to override all methods... I advice to add field to your class $client and in constructor just create it:
<?php

namespace App\Vendors\Smsirlaravel;

use Ipecompany\Smsirlaravel\Smsirlaravel;
use GuzzleHttp\Client;

class SendSmsIr extends Smsirlaravel {
  protected $client;

  public function __construct()
  {
    $this->client = new Client(['verify' => config('smsirlaravel.ssl_verify')]);
  }

  /** other methods */
}

in config/smsirlaravel.php just add this line to array
'ssl_verify' => false, // true, false or path to certificate '/path/to/cert.pem'


text:
Q: Why is my MultiSelectList not returning data to model? I have the following View Model:
public class SendGroupEmailViewModel
{
    public int EmailID { get; set; }
    public IEnumerable<SelectListItem> Roles { get; set; }
    public int[] SelectedRoles { get; set; }

}

The controller action that sends the appropriate information to the view:
var viewModel = new SendGroupEmailViewModel
        {
            Roles = db.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Id.ToString(), Text = rr.Name }).ToList(),

        };

Then in my view:
@Html.ListBoxFor(model => model.SelectedRoles, new MultiSelectList(Model.Roles, "Value", "Text"), new { @class = "" })

The list appears correctly within the view but when the form with the above ListBoxFor in is posted SelectedRoles returns as null.
Can anyone tell me why this is and how I can remedy it?

A: Your code looks fine. The only reason this won't work is because the SELECT element's option value's are not numeric type (EX : Guid /String). In that case the model binder will not be able to bind the non numeric value array to an int array type (Which is the type of your SelectedRoles property).
The solution is to change the  type of SelectedRoles to a collection of type which is the type of your Id property in Role entity.
Assuming your Role.Id is of string type, This should fix the problem
public class SendGroupEmailViewModel
{
    public int EmailID { get; set; }
    public IEnumerable<SelectListItem> Roles { get; set; }
    public string [] SelectedRoles { get; set; }
}

Also you do not need to create an object of MultiSelectList in your view again. You can simply do
@Html.ListBoxFor(model => model.SelectedRoles, Model.Roles, new { @class = "" })


text:
Q: What can I use to replace an SV-04F bias diode? I had a nice Wega V3840-2 audio amplifier, but sadly, it broke. During my attempts to test what was wrong, a diode, attached to the heat sink, failed with a nice whiff of magic smoke. According to the Kundendienstanleituing (user service manual), this particular diode is a SV04F. I cannot check the markings on diode itself, since it's embedded in epoxy in a little clamp that attaches it to the heat sink. I cannot find this particular diode at my local stores, so my question is, what can I use to replace it?
For your convencience, I also added part of the schematic. The top rail is +32V (also the leftmost connection coming from above), the bottom rail -32V. The connection center left is the actual audio signal, the output on the right goes to the speakers.
The failed diode is D201, that's attached to the heat sink of T210 (which is in turn attached to the main heat sink of all four final stage transistors).

Note about the circumstances it broke under for those interested: I replaced T210 and T211 with a BD2430 and BD244C in an earlier attempt to fix the amplifier (see first link of this post). I now realise that the trafo is set for 220V even though we have 230V these days, perhaps I'll set it for 240V. Other than that, I still don't know how or why my amp is no longer working...

A: This is from an old Sony service bulletin. It mentions SV04S (not F) but part numbers show SV04, SV04S and SV04F as equivalent, so it should work.

It's a Vbe multiplier, also known as an adjustable diode or rubber diode. It's made from an NPN silicon transistor (in this case 2SD1585) and two resistors.
You could replace both the 1k and 3k3 resistors for one 5k linear trim pot, so you can precisely adjust the DC bias for the output transistors, like so (fig 2.5b):

I built a similar device to fix an old Sony receiver before I bumped into this solution, so I know it works fine. I'm not sure if the resistor values are ok for your particular application, so maybe the 5k trimpot should be the way to go, at least until you find the exact resistance values to use.
As it was said before, it's important to thermally couple this assembly to the output transistors (mounting it to the heatsink close or at the same place as the output transistors should do) to get thermal feedback.
I just replaced my previous fix (BC550 NPN transistor + similar resistors) with this very device on my Sony TA1630, and can confirm it works fine so it should work in your Wega amp as well. I built the device right on top of the D1585 transistor (you may prefer using a PCB, but I think it's overkill. YMMV). With some patience and 1W metal-film resistors, it can be built lifting the base pin, and putting both resistors in front of the transistor. Then, I tapped two holes on the heatsink, on top of the PNP power transistors and fixed the device there.

A: The purpose of D201 is to bias the push-pull darlington output stage.  Since that output stage has 4 B-E drops between the bottom and top of D201, this is probably 4 diodes in series.
It's not clear how much current the diode needs to handle since it's hard to tell how much of the total 64 V drop T206 and T207 eat up.  The remainder of the 64 V that isn't across the diode and transistors is across the sum of R275 and R276, which is 200 Ω.  The absolute worse case is 300 mA, but the actual maximum could be substantially less.
You can replace D201 with 4 diodes in series.  These should be rated for 1/2 A, which rules out the 1N4148.  Just about any ordinary silicon diode that can handle the current should work here.  These diodes are always forward biased and are only used as voltage sources.
If D201 fried, then probably at least one of T206 and T207 has failed shorted.

A: Not sure if this is the same device but I came across this while reverse-engineering an old calculator:

I took some measurements and it looks to be consistent with 4 diodes in series:
  Current (mA)   Forward Voltage
  0.01266        1.871
  0.0522         2.057
  0.1022         2.143
  0.360          2.31
  0.402          2.325
  0.719          2.407
  1.002          2.454
  1.226          2.485


text:
Q: Exact Target SOAP API Authentication Issue I'm having a hard time understanding the authentication model for the Exact Target APIs. The REST API requires a clientId and a clientSecret to obtain an access token for subsequent requests. Yet the SOAP API requires a username and password. I did see this regarding passing the token as a SOAP Header, but it doesn't work. It ALWAYS fails with soap:Server: "Unplanned Outage".  Passing a username/password in a SOAP header and the API calls work fine.
First question, is someone able to explain the authentication disparity between the two APIs?
Second question, does the method of passing the oauth token in a SOAP header not work?

A: First question: SOAP is the older technology, and REST is the new and improved.  REST has made us rethink how we do some things, and retrofitting is still going on.
Second question: I use the oauth all the time in the SOAP header.  Mine is slightly different than what you find on the code@ site, I've posted it below.  Let us know if it works, and we'll update the code@ site.
<soapenv:Header>
   <fueloauth xmlns="http://exacttarget.com">hs828jcnjkwq2bhkve3j4va3</fueloauth>
</soapenv:Header>


text:
Q: Combinatorics : Generating function I am working on the below generating function and confused on how to start:
Let $g(n)$  be the number of subsets of $[n]$ in which the difference between any two elements of the set is at least three. Find the generating function for $g(n).$

A: Let $A_{n-3}$ be a subset of $[n-3]$ satisfying the condition. You know that $A_{n-3} \subset [n]$ and it satisfies the conditions you desire. Additionally, $A_{n-3} \cup \{n\} \subset [n]$.
For each $A_{n-5} \subset [n-5]$ satisfying the condition, $A_{n-5} \subset [n-3]$ and satisfies the condition, so you only need consider sets of the form $A_{n-5} \cup \{n-2\}$. Similarly for $A_{n-4} \cup \{n-1\}$.
This gives a recurrence relation:
$$g(n) = 2g(n-3)+g(n-4)+g(n-5)$$
(I have not fully thought this through, and you should verify that I did not miss any subsets).
Next, let $$f(x) = \sum_{n\ge 0}g(n)x^n$$
Then:
$$f(x)-2x^3f(x)-x^4f(x)-x^5f(x) = g(0)+g(1)x+g(2)x^2+(g(3)-2g(0))x^3+(g(4)-2g(1)-g(0))x^4+(g(5)-2g(2)-g(1)-g(0))x^5+\sum_{n\ge 6} (g(n)-2g(n-3)-g(n-4)-g(n-5))x^n$$
Since $g(n)=2g(n-3)+g(n-4)+g(n-5)$, every term with a power greater than 4 has a coefficient of zero.
So:
$$f(x) = \dfrac{g(0)+g(1)x+g(2)x^2+(g(3)-2g(0))x^3+(g(4)-2g(1)-g(0))x^4}{1-2x^3-x^4-x^5}$$
It is easy to see that $g(0)=1, g(1)=2, g(2)=3, g(3)=4, g(4)=6$. So, this gives the generating function:
$$f(x) = \dfrac{1+2x+3x^2+2x^3+x^4}{1-2x^3-x^4-x^5}$$


text:
Q: How to unit test the Kafka Streams and Producer APIs together Currently, I have a basic Kafka streams application that involves a Topology with only a source and a processor, but no sink. Essentially, the Topology only handles the consumption of messages. As for producing messages, we make calls to the Producer API in the ProcessorSupplier instance passed to the Topology, specifically in the overridden process method. Although I understand that the Producer API is redundant here since I could have simply added a sink to the topology, I am in a position where I have to setup my streams application in this way. As for testing, I tried out the TopologyTestDriver class that is available in the kafka-streams-test-utils package. However, I want to not only test out the topology but also the calls to the Producer API. Using the TopologyTestDriver requires me to mock my Producer instance since that is separate from the Streams API. As a result, because the messages are not "fowarded", I am unable to read messages from the TopologyTestDriver for my unit tests.
Here is a simplified version of my process method:
@Override
public void process(String key, String value) {
    // some data processing stuff that I leave out for simplicity sake
    String topic = "...";
    Properties props = ...;
    //Producer<String, String> producer = new KafkaProducer<>(props);
    ProducerRecord<String, String> record = new ProducerRecord(topic, key, value);
    producer.send(record);
}

And here is a simplification of my sample unit test:
@Test
public void process() {
    Topology topology = new Topology();
    topology.addSource("source", "input-topic");
    topology.addProcessor("processor", ..., "source");
    Properties props = ...;

    TopologyTestDriver testDriver = new TopologyTestDriver(topology, props);

    ConsumerRecordFactory<String, String> factory = new ConsumerRecordFactory<>(new StringSerializer(), new StringSerializer());
    // the following line will work fine as long as the producer is mocked
    testDriver.pipeInput(factory.create("input-topic", "key", "value"));

    // since the producer is mocked, no message can be read from the output topic
    ProducerRecord<String, String> outputRecord = testDriver.readOutput("output-topic", new StringDeserializer(), new StringDeserializer());

    assertNull(outputRecord); // returns true
}

To sum up my question, is there a way to write a unit test that tests both the consumption and production of messages within a Topology that uses the Producer API for writing messages to outgoing topics?

A: You should not use a custom Producer but add a sink to your Topology. Calls to Producer.send() are async and thus you might be subject to data loss. To avoid data loss, you would need to make the call sync, ie, get the Future that is returned by send() and wait for its completion before process() returns. However, this has a big impact on your throughput and is not recommended.
If you add a sink you avoid those issue as Kafka Streams will now understand what data was sent to the output topic, and thus no data loss will happen, while Kafka Streams can use the more performant async call.
Beside the correctness issue, it seem you create a new KafkaProducer for every message you process in you current code, what is quite inefficient. Furthermore, using a sink will simplify your code. And of course, you get proper testing capabilities using the TopologyTestDriver.


text:
Q: TFS Code Coverage out by 0.1 We have an intermittent issue on our TFS 2012 build server against a mature enterprise product.
Occasionally the gated builds fail because the code coverage reported by TFS has decreased by 0.1 when no code has changed or non-testable code such as css has changed.
Any ideas on why this happens or mitigating steps?
Currently updating build to lower code coverage and are planning to add a .1 fudge factor.


text:
Q: How to name a variable after a function argument in Python? My python program need to open (or create if they don't exist) a lot of files, so when I want to open e. g "output.txt", I just need to openfile(output.txt) to have it open. However I need to access the data once the file is open, and I would like to give it the name of the file.
How do I name my var after the "name" argument here ?
def openfile(file, name):
  global name
  if os.path.isfile('./{0}'.format(file)):
    name = open(file,"w")
  else:
    os.mknod(file)
    name = open(file, "w")


text:
Q: Polymer bind object dom-repeate I run on loop on the list (this is array). and for every I create icon-status with property item.status.
I want that is item.status changed for some reason also the property to the icon will change.
<template is="dom-repeat" items="{{list}}">

        <paper-item>
            <paper-item-body>

                    //this is also dont bind on change
                    <icon-status state={{item.status}} size=7></icon-status>

                    //this is not bind on change

{{item.status}}

            </paper-item-body>
        </paper-item>

</template>

I tried using timeout change the status of the items and the view does not update.
How can I bind this?
Thanks

A: To add binding support for list:

*

*To update the value in the current element, use this.set('list.0.status', 'newStatus');

*To update the value in a parent element, add list as a property on the current element:
list: { type: Array, notify: true }

*Consider changing your template binding from two-way to one-way as the data is only flowing in one direction, <template is="dom-repeat" items="[[list]]">


text:
Q: Show every container element with for_each function I like to understand more about templates. I tried to write my own function, that shows every container element.
void show_element(int i){
std::cout << i << endl;
}

int main(){

int dataarr[5]={1,4,66,88,9};
vector<int> data(&daten[0],&daten[0]+5);

std::for_each(data.begin(),data.end(),show_element)

...

My show_element function isn't generic yet. How do i have to write it, so that i can use it for different container-types?
template <typename T>
using type = typename T::value_type;
void show_element(type i){ //type i must be sthg like *data.begin()
std::cout << i << endl;
}

thanks a lot

A: Change to:
template <typename T>
void show_element(T const &i) { std::cout << i << std::endl; }

for_each applies the given function (e.g., show_element) on the result of dereferencing every iterator in the range [first, last), in order. So you don't need to take the value_type of the container.
Also in c++14 and above you could define a generic lambda:
auto show_element = [](auto const &i) { std::cout << i << std::endl; };

and use it as:
int arr[] = {1, 4, 66, 88, 9};
std::vector<int> data(arr, arr + sizeof(arr) / sizeof(int));
std::for_each(arr, arr + sizeof(arr) / sizeof(int), show_element);

LIVE DEMO

A: Instead of a function it is more flexible to use a class. In this case you can  pass additional arguments to the functional object.
For example you could specify a stream where you are going to output the elements or a separator that will separate the elements in the stream.
The class can look the following way
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

template <typename T>
class show_elements
{
public:
    show_elements( const std::string &separator = " ", std::ostream &os = std::cout )
        : separator( separator ), os( os ) {}
    std::ostream & operator ()( const T &value ) const
    {
        return os << value << separator;
    }
protected:
    std::string separator;
    std::ostream &os;
};

int main()
{
    int arr[] = { 1, 4, 66, 88, 9 };
    std::vector<int> v( arr, arr + sizeof( arr ) / sizeof( *arr ) );

    std::for_each( v.begin(), v.end(), show_elements<int>() );
    std::cout << std::endl;
}

The program output is
1 4 66 88 9

A: Another simple way is to use range-based for loop.
for(auto& element : container) {
    cout<<element<<endl;
}


text:
Q: android: activity as dialog: layout_height="wrap_content" but still fullscreen Is this a good title for a question?
My problem is, I use an activity as a dialog (by not using a fullscreen activity), but even though I use layout_height="wrap_content", the dialog stil uses the whole screen.
Tried using a DialogFragment too, same result.
Here the .xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/topLinearLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorDeadBackground"
    android:orientation="vertical"
    android:weightSum="1">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.7"
>
<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler_view_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</RelativeLayout>

<LinearLayout
    android:id="@+id/button_layout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.3"
    android:orientation="horizontal"
    android:weightSum="1">

    <ImageButton
        android:id="@+id/setProfileButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:src="@drawable/outline_portrait_black_48" />

    <ImageButton
        android:id="@+id/deletePictureButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:src="@drawable/outline_delete_black_48" />
</LinearLayout>
</LinearLayout>

Here the AndroidManifest.xml:
 <activity
        android:name=".ShowPicturesActivity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:theme="@style/MyPictures" />

And here styles.xml:
<style name="MyPictures" parent="@style/MyDialogTheme">
    <item name="android:windowFullscreen">false</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert" />

How can I make the topLinearLayout to wrap_content in height?

A: You have specified the fixed height to recycler view wrap content not work in this case as it expands as an item in your adapter increases better use constraint layout and bind recyclerview constraints from top and bottom and set height to 0dp
simply try yourself set height to wrap_content on reyclerview and use
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:orientation="vertical"
tools:listitem="@layout/your_layout"
tools:itemCount="10"


text:
Q: Prepared statements with MySQL? I am having some trouble with, what I believe to by syntax, for prepared statements.
I have the following code
String query2="SELECT lname FROM school_student WHERE sid = ? ORDER BY sid;";

PreparedStatement ps = cn.prepareStatement(query2);
ps.setInt(1, 3);
ResultSet rs = ps.executeQuery(query2);

The problem I am having is that I am getting this error message:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? ORDER BY sid' at line 1

However, when I substitute the "?" in my query for a 3, the query works fine with no error and gives me what I want.  There seems to be something wrong with how I am setting the value of the "?" in my query?  Am I using the wrong syntax?

A: Simply use
ps.executeQuery();

(i.e. use the overloaded executeQuery() method which doesn't take any argument). You already passed the query when preparing the statement.

A: use this query :-

String query2 = "SELECT lname FROM school_student WHERE sid =
  "+attribute+" ORDER BY sid;";

and simply use

ps.executeQuery();

A: I think their is syntax problem while preparing query
try this one...
String query2="SELECT lname FROM school_student WHERE sid = +variablename+ ORDER BY sid;"


text:
Q: Error in creating complex survey design object with imputed data using mi and survey packages in R EDIT: Duplicate of question answered here.
I am trying to work with survey weighted data where there is some substantial missingness across important variables. I am generally following the workflow from this archived tutorial on R-Forge. Unfortunately I am running into an error I can't seem to figure out when I attempt to reference the imputed data when create the complex survey design object.
I can't do a reproducible example of my actual data, but I run into the same issue when trying to do the same thing with the apiclus1 dataset included in the survey package, so putting that example below.
I removed several variables that are unimportant for imputation and a few that were causing issues - this should not meaningfully affect the example.
library(tidyverse)
library(survey)
library(mi)
library(mitools)

data(api)

apisub <- apiclus1 %>% select(-c("name", "sname", "dname", "cname", "flag",
                                 "acs.46", "acs.core"))

mdf <- missing_data.frame(apisub)
mdf <- change(mdf, "cds", what = "type", to = "irrelevant")
mdf <- change(mdf, "stype", what = "type", to = "irrelevant")
mdf <- change(mdf, "snum", what = "type", to = "irrelevant")
mdf <- change(mdf, "dnum", what = "type", to = "irrelevant")
mdf <- change(mdf, "cnum", what = "type", to = "irrelevant")
mdf <- change(mdf, "fpc", what = "type", to = "irrelevant")
mdf <- change(mdf, "pw", what = "type", to = "irrelevant")

show(mdf)

imputations <- mi(mdf)

dsn1 <- svydesign(id = ~dnum, weights = ~pw, data = imputationList(imputations), fpc = ~fpc)

The error I get after running this last line says Error in as.list.default(X) : no method for coercing this S4 class to a vector.
Can someone help me understand what I'm doing wrong?

A: not sure i can answer but maybe this helps a bit?  it's not clear to me how the library(mi) is supposed to fill in the missing data?  svydesign() expects a list of data.frame objects, so the library(tidyverse) and library(mi) might create types not supported by the survey library and mitools..
# is this how to extract the four imputed data.frames from the `imputations` object?
# i am not sure
w <- lapply( imputations@data , data.frame )

# four data.frame objects in a list will now work:
dsn1 <- svydesign(id = ~dnum, weights = ~pw, data = imputationList(w), fpc = ~fpc)

# still missings in this variable, is that expected?
MIcombine( with( dsn1 , svymean( ~ avg.ed ) ) )

# result, ignoring the missings
MIcombine( with( dsn1 , svymean( ~ avg.ed , na.rm = TRUE ) ) )


text:
Q: How to get to "extended" prototype properties or function in JavaScript? Common practice in jQuery pliugins I'm beginner with OOP in JavaScript. I've tried few things but its obvious that i don't understand code.
Here's my problem:
I have a plugin for showing calendar - glDataPicker. It is initialised on input tag like this:
$('#my_input_id').glDatePicker();//parameters may be passed

*

*So i am assuming that after deploying script to my site glDatePicker.min.js inputs in DOM got new method glDatePicker? Am i right here?

Then it has hide and show methods defined:
// Public methods
    glDatePicker.prototype =
    {
        show: function() {
            // Hide others and show this calendar
            $.each($('.gldp-el').not(this.el), function(i, o) {
                if(o.length) { o.options.onHide(o.calendar) ; }
            });

            // Show this calendar
            this.options.onShow(this.calendar);
        },

        hide: function() {
            if(this.options && !this.options.showAlways) {
                this.options.onHide(this.calendar);
            }
        },

So my question is how can I call method `hide' from outside the plugin code?
I've tried:
$('#my_input_id').glDatePicker().calendar.hide()
-> Cannot read property 'hide' of undefined(…)
and so on but i can't hide the calendar. How can i get to this method from global context?

A: Try this :
$('[gldp-el='+ $('#my_input_id').attr('gldp-id') +']').hide()

$('[gldp-el='+ $('#my_input_id').attr('gldp-id') +']').show()

A: ok, I have found, what I need:
// Doing it in a single pass
var myDatePicker = $('#example1').glDatePicker(
{
   showAlways: true,
   selectableDOW: [0, 2, 3]
}).glDatePicker(true);

// Or you can do it with multiple calls
$('example1').glDatePicker(
{
    showAlways: true,
    selectableDOW: [0, 2, 3]
});

var myDatePicker = $('example1').glDatePicker(true);

now I can:
myDatePicker.hide();

so that menas that first glDatePicker doesn't reutrn object.


text:
Q: How to select all checkboxes with class "xxx"? Welcome,
It it possible to select all checkboxes / uncheck all checkboxes what have class "xxx" ?
I can't  use "name" and "ID" because there are generated dynamical via PHP and i don't know their name.
So maybye i can add class "xxx" for these what i wan't control ?
Is is possible ?
Or, if not possible.
Maybye i can select all / unselect  what are inside table with id "selectall" ?
Regards

A: Here is how you can do with jquery's attr method:
$('input.xxx').attr('checked', 'checked');

This finds all input elements with class xxx and checks them all. To un-check, them, you could do like:
$('input.xxx').attr('checked', false);

For checkboxes inside a table with id selectall, you can go about like:
$('table#selectall :checkbox').attr('checked', 'checked');

and to un-check them, you should do:
$('table#selectall :checkbox').attr('checked', false);

Or:
$('table#selectall :checkbox').removeAttr('checked');

A: To select all checkboxes with class "xxx":
$('.xxx:checkbox').attr('checked','checked');

You can use .removeAttr('checked') to unselect them.
To select all checkboxes inside an element with id "selectall":
$('#selectall :checkbox').attr('checked','checked');

A: If this is for a "select all" you can do something like this:
$("#selectAll").change(function() {
  $(".xxx:checkbox").attr('checked', this.checked);
});

You can test a simple demo here, when you check it, all of the .xxx checkboxes get checked, and unchecked when you unchecked it, this is usually what you want in a "Check/Uncheck All" box at the top.


text:
Q: VBA Code in Workbook_Open stops working when I add my code I want to expand code in sub Workbook_Open() with printing to external file functionality. This sub already has some code in it and it works fine. When I add my code whole sub doesn't work most of the time.
My code:
Dim fld As Object
Set fld = CreateObject("Scripting.FileSystemObject")

Dim logFile As Object
Set logFile = fld.CreateTextFile(Application.ActiveWorkbook.Path & "\Last_User.txt", True)
logFile.WriteLine (Application.UserName)
logFile.Close

I've tried putting this code in different parts of the sub, checking references and I made sure that events are enabled.


text:
Q: Android ListView with a checkbox I've now spent a full day on trying to get a custom row to load.  There seem to be plenty of examples here on StackOverflow and other places on how to bind a checkbox to a row of data within an Android listview, but they all seem to be incomplete.
Here's what I have (row.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="40dip"
    android:orientation="horizontal" android:background="@drawable/row_bk"
    android:layout_gravity="center_vertical">

    <TextView android:id="@+id/ItemID"
    android:layout_weight="0" android:visibility="gone"
        android:layout_width="0dp" android:gravity="center"
    android:layout_height="wrap_content" />

<TextView android:id="@+id/Title"
    android:layout_width="0dp" android:textColor="#666"
    android:layout_weight="1" android:layout_height="40dip"
    android:padding="5dp" android:gravity="center_vertical"
    android:textSize="17dip" />

<CheckBox android:id="@+id/chkCheck" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:focusable="false" android:focusableInTouchMode="false" android:clickable="true"></CheckBox>

</LinearLayout>

In code, I have a SimpleCursorAdapter, populating the ListView.
    Cursor oLoop = db
            .rawQuery(
            "select _id, title, is_checked from tbl",null);

    startManagingCursor(oLoop);

    String[] from = new String[] { "_id", "title", "is_checked" };

    int[] to = new int[] { R.id.ItemID, R.id.Title, R.id.chkCheck };

    SimpleCursorAdapter  oList =
     new SimpleCursorAdapter (this, R.layout.task_item_row, oLoop, from,
     to);

     setListAdapter(oList);

Past this, I'm not really sure what to do.  If someone could point me at a good example, that would be great.  The goal is to actually be able to toggle the checkboxes.
Thanks in advance!
Alex

A: Alex,
The next step is to implement ViewBinder.setViewValue()
It would look something like this:
getViewAdapter().setViewBinder(
    new ViewBinder(){
        public boolean setViewAdapter(View view, Cursor cursor, int columnIndex){
            <JavaType> object = cursor.get<JavaType>(columnIndex);

            boolean isHandled = false;
            if(view.getId() == R.id.checkBox){
                CheckBox cb = (CheckBox) view;
                cb.setChecked(isObjectChecked(object));
                // object depends on your underlying data type
                // in the data base, use the debugger to find the actually implemented type.
                isHandled = true;
            }

            return isHandled;
        }
    }
);

This can be a very powerful method with conditionally visible views and loading Uri's from the network, etc.


text:
Q: Android Spinner get ID with data from mysql I have a Tab layout with fragment class which has a listview in it and a spinner. All the data inside the listview is populated from my database. How do I change the data inside my listview by selecting an item in my spinner that gets by ID?
Here is a sample of my JSON file
{
    "game_response": [{
        "EID": "1",
        "teamone": "RRR",
        "teamtwo": "TTT",
        "teamonepts": "69",
        "teamtwopts": "61",
        "e_name": "Basketball",
        "e_gender": "Male"
    }, {
        "EID": "2",
        "teamone": "AAA",
        "teamtwo": "BBB",
        "teamonepts": "61",
        "teamtwopts": "52",
        "e_name": "Basketball",
        "e_gender": "Female"
    }, {
        "EID": "3",
        "teamone": "CCC",
        "teamtwo": "DDD",
        "teamonepts": "56",
        "teamtwopts": "38",
        "e_name": "Football",
        "e_gender": "Male"
    }]
}

The EID is the unique id for each data in my spinner. How do I get to only show all data from EID 2 on my listview when I select "Basketball Female" from my spinner?
Here is my android code
 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.games, container, false);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        lv = (ListView) rootView.findViewById(R.id.listView);
        spinner1 = (Spinner) rootView.findViewById(R.id.sp1);
        getJSON();

        getSpinner();
        spinner_fn();

        return rootView;

    }

    private void getSpinner() {
        list1.clear();
        try {
            URL url = new URL(Config.URL_SPIN);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            is = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            JSONArray JA = new JSONArray(result);
            JSONObject json;

            e_name = new String[JA.length()];
            e_gender = new String[JA.length()];

            for (int i = 0; i < JA.length(); i++) {
                json = JA.getJSONObject(i);
                e_gender[i] = json.getString("e_gender");
                e_name[i] = json.getString("e_name");
            }
            list1.add("All");
            list1.add("NonSports");
            for (int i = 0; i < e_name.length; i++) {
                list1.add(e_name[i] + " " + e_gender[i]);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void showJSON1() {
        JSONObject jsonObject;
        ArrayList<HashMap<String, String>> list9 = new ArrayList<>();
        try {
            jsonObject = new JSONObject(JSON_STRING);
            JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY2);

            for (int i = 0; i < result.length(); i++) {
                JSONObject jo = result.getJSONObject(i);
                String EID = jo.getString(Config.TAG_EID);
                String teamone = jo.getString(Config.TAG_teamone);
                String teamonepts = jo.getString(Config.TAG_teamonepts);
                String teamtwo = jo.getString(Config.TAG_teamtwo);
                String teamtwopts = jo.getString(Config.TAG_teamtwopts);
                String e_name = jo.getString(Config.TAG_e_name);
                String e_gender = jo.getString(Config.TAG_e_gender);
                String m_no = jo.getString(Config.TAG_m_no);
                HashMap<String, String> match = new HashMap<>();
                match.put(Config.TAG_EID, EID);
                match.put(Config.TAG_teamone, teamone);
                match.put(Config.TAG_teamonepts, teamonepts);
                match.put(Config.TAG_teamtwo, teamtwo);
                match.put(Config.TAG_teamtwopts, teamtwopts);
                match.put(Config.TAG_e_name, e_name);
                match.put(Config.TAG_e_gender, e_gender);
                match.put(Config.TAG_m_no, m_no);
                list9.add(match);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        ListAdapter adapter = new SimpleAdapter(
                getActivity(), list, R.layout.gamesadapterlayout,
                new String[]{Config.TAG_EID, Config.TAG_teamone, Config.TAG_teamonepts, Config.TAG_teamtwo, Config.TAG_teamtwopts, Config.TAG_e_name, Config.TAG_e_gender, Config.TAG_m_no},
                new int[]{R.id.team1, R.id.score1, R.id.team2, R.id.score2, R.id.Type, R.id.s_gender});
        lv.setAdapter(adapter);
    }

    private void GETJSON1() {
        class gETJSON1 extends AsyncTask<Void, Void, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();

            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                JSON_STRING = s;
                showJSON1();
            }

            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                s = rh.sendGetRequest(Config.URL_VOLLEYBALL);
                return s;
            }
        }
        gETJSON1 gj = new gETJSON1();
        gj.execute();
    }

    private void spinner_fn() {
        ArrayAdapter<String> spinner = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list1);
        spinner1.setAdapter(spinner);
        spinner1.setSelection(0);
        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {

                    case 0:
                        GETJSON1();
                        List<? extends Map<String, ?>> list = new ArrayList<>();
                        ListAdapter adapter = new SimpleAdapter(
                                getActivity(), list, R.layout.gamesadapterlayout,
                                new String[]{Config.TAG_EID, Config.TAG_teamone, Config.TAG_teamonepts, Config.TAG_teamtwo, Config.TAG_teamtwopts, Config.TAG_e_name, Config.TAG_e_gender, Config.TAG_m_no},
                                new int[]{R.id.team1, R.id.score1, R.id.team2, R.id.score2, R.id.Type, R.id.s_gender});
                        lv.setAdapter(adapter);
                 break;
                    case 1:
                       GETJSON1();
                        List<? extends Map<String, ?>> list = new ArrayList<>();
                        ListAdapter adapter = new SimpleAdapter(
                                getActivity(), list, R.layout.gamesadapterlayout,
                                new String[]{Config.TAG_EID, Config.TAG_teamone, Config.TAG_teamonepts, Config.TAG_teamtwo, Config.TAG_teamtwopts, Config.TAG_e_name, Config.TAG_e_gender, Config.TAG_m_no},
                                new int[]{R.id.team1, R.id.score1, R.id.team2, R.id.score2, R.id.Type, R.id.s_gender});
                        lv.setAdapter(adapter);
                        break;
                    case 2:

                        GETJSON1();
                        List<? extends Map<String, ?>> list = new ArrayList<>();
                        ListAdapter adapter = new SimpleAdapter(
                                getActivity(), list, R.layout.gamesadapterlayout,
                                new String[]{Config.TAG_EID, Config.TAG_teamone, Config.TAG_teamonepts, Config.TAG_teamtwo, Config.TAG_teamtwopts, Config.TAG_e_name, Config.TAG_e_gender, Config.TAG_m_no},
                                new int[]{R.id.team1, R.id.score1, R.id.team2, R.id.score2, R.id.Type, R.id.s_gender});
                        lv.setAdapter(adapter);
                        break;


text:
Q: how to json encode format? i'm trying to get some json print. I have a simple format but i didn't figure it out.
But my result is like that. {"datas":{"title":"table"}}
    $sql = "SELECT * FROM mytable";
    $check = mysqli_fetch_array(mysqli_query($con,$sql));
    $array = array("table"=>$check["title"]);
    $result=json_encode(array('datas' => $array));
    echo($result);
    mysqli_close($con);

I need this is my format {"datas":[{"0":"table","title":"table"}]}
I guess i miss something.

A: You should use this:
    $sql = "SELECT * FROM mytable";
    $check = mysqli_fetch_assoc(mysqli_query($con,$sql));
    $array = array("table"=>$check["title"]);
    $result=json_encode(array('datas' => $array));
    echo($result);
    mysqli_close($con);


text:
Q: Creating a phillotaxic sphere / hemisphere with C#? I'm trying to follow a tutorial which is written in a math programming language I'm not familiar with and attempting to convert the tutorial to C# code for Unity 3d.
See here: http://blog.wolfram.com/2011/07/28/how-i-made-wine-glasses-from-sunflowers/
    float theta = Mathf.PI * (3 - Mathf.Sqrt(5));
    for (int i = 0; i < spawnPoints.Length; i++)
    {
        float r = (radius / 2) * Mathf.Sqrt(i) / Mathf.Sqrt(points);
        float a = theta * i;

        Vector3 coords = transform.TransformDirection( new Vector3(Mathf.Cos(a) * r, 0, Mathf.Sin(a) * r) )+transform.position;

        spawnPoints[i] = coords;
    }

This if course generates the flat phillotaxic arrangement in 2d. I'm trying to modify Y (up) axis for depth (creating the sphere).
I cannot seem to set the Y (up) axis correctly in proportion with i and radius.
Considering the tutorial above, how should I be calculating Y?

A: The 3D version is called a spherical Fibonacci lattice. This paper gives a nice explanation. This stackoverflow post has more links.


text:
Q: Wordpress - Add a new class to an element on same template-page.php depending the active page? I create a custom template "page-products.php" for all my products page.
Inside of this template, i have a horizontal menu with 8 items.
example capture of the menu
When i'm on the page of the current product, i would change the back-ground color of the element menu.
Any ideas to add a new class on an element when on the current page ?
I would like to avoid to create 8 differents template for each different product.

A: If your theme uses body_class() on the body – you can style from the body class down to the element. In my example .page-8 is on the body-tag and .menu would be the menu.
.page-8 .menu {background-color: red;}


text:
Q: How do I use a variable so that it is inside and outside of a function I would like to know how I can use a variable in a function but then outside of the function as well.
Here is a part of my code which is supposed to add 1 to the score when the answer is correct, then print out the overall score afterwards (there is more than one function so I need to the score to be outside of the function):
score=0
def Geography(score):
#Question 1
qa1= input("What is the capital of England? ")
if qa1.lower() == ("london"):
    print ("Correct you gain 1 point")
    score=score+1
else:
    print ("Incorrect")

Geography(score)
print ("This quiz has ended. Your score is " , score, ".")

As you can see, I have tried to use arguments however the code still returns the score as 0 at the end no matter if the person has got the answer right.

A: Return score from the function and assign it back to score
score=0
def Geography(score):
    #Question 1
    qa1= input("What is the capital of England? ")
    if qa1.lower() == ("london"):
        print ("Correct you gain 1 point")
        score=score+1
    else:
        print ("Incorrect")
    return score

score = Geography(score)
print ("This quiz has ended. Your score is " , score, ".")

A: Try using "global" before variable "score" and access it again in the "def Geography():" function. This code should work for all "def" functions in code:
global score
score = 0

def Geography():
    # Question 1
    global score
    qa1 = input("What is the capital of England? ")
    if qa1.lower() == ("london"):
        print("Correct you gain 1 point")
        score = score + 1
    else:
        print("Incorrect")

Geography()
print("This quiz has ended. Your score is ", score, ".")


text:
Q: How to replace only characters located between numbers and leave unchanged those with different locations How to replace "." that is located within numbers with ",", but not replace "." located elsewhere?
Input data:
x_input="23.344,) abcd, 12899.2, (,  efg; abef. gfdc."

Expected ouput:
x_output
"23,344,) abcd, 12899,2, (,  efg; abef. gfdc."

I tried:
x_input<-"23.344,) abcd, 12899.2, (,  efg; abef. gfdc."
x_output<-gsub(".", ",", x_input))))

But this does not work.
Thanks in advance.

A: Replace a digit, dot and digit with the first digit, a comma and the second digit.
(Alternately use the pattern
r"{(\d)\.(\d?)}"

if it is sufficient to have a digit before the dot but not after the dot.)
No packages are used.
gsub(r"{(\d)\.(\d)}", r"{\1,\2}", x_input)
## [1] "23,344,) abcd, 12899,2, (,  efg; abef. gfdc."

A: A possible solution, based on stringr::str_replace_all:
library(tidyverse)

x_input="23.344,) abcd, 12899.2, (,  efg; abef. gfdc."

x_input %>%
  str_replace_all("(?<=\\d)\\.(?=\\d)", ",")

#> [1] "23,344,) abcd, 12899,2, (,  efg; abef. gfdc."

Or, in base R,
gsub("(?<=\\d)\\.(?=\\d)", ",", x_input, perl = T)

#> [1] "23,344,) abcd, 12899,2, (,  efg; abef. gfdc."