text:
Q: Where to put the PID windup guard? Should I put a windup guard on each term of the PID, or just the I, or maybe the whole output?

A: Integrator anti-windup is a measure you need to take because of output saturation or other limits in the system, and such limits are nonlinear behavior.  When you start doing nonlinear control, a lot of the nice, clear, procedural things that we're taught in undergraduate control theory classes don't entirely apply.
In general you should apply integrator anti-windup to just the integrator term, although you may also need to apply limiting to the output term before it's applied to a DAC (assuming you're doing the work in software).  There are a lot of ways to do this.  My preference is to either limit the integrator state to certain bounds by itself:
// (Calculate integrator_state)
if (integrator_state > integrator_max) {integrator_state = integrator_max;}
if (integrator_state < integrator_min) {integrator_state = integrator_min;}

Or to calculate a candidate output, then trim the integrator state:
output_candidate = integrator_state + error * prop_gain;
if (output_candidate > output_max) {
  integrator_state = output_max - error * prop_gain;
} else if (output_candidate < output_min) {
  integrator_state = output_min - error * prop_gain;
}
// Re-calculate the actual output, possibly with a D term

The method that @Chu mentions would work, if you remember to only apply it when the integrator is being pulled to excess, not pulled back (but my first method is equivalent).  Another method that is used often is to hold the integrator term at zero when the error is large, then allow integrator action when the error gets below some threshold, or if you're doing a motion controller that knows when a "move" starts to set the integrator at zero at the start of a move and hold it there for some finite time.  I'm not a big fan of either of those methods, but others are.
Because you're venturing into nonlinear control, even if you're so far in the shallow end of the pool you can lie down without drowning, there are options on options on options, and there's no one right way to do it.  Moreover, you can't find an answer by analysis -- you have to either implement the real system and give it a whirl, or make a simulation and try your algorithm out on that.

A: Windup guard is typically referred to as the protector of the integral term in order that it will not accumulate continually. The controller can overshoot significantly and will continue to overshoot with the integral continuing to grow.
Therefore, the windup guard is just the integral term. As this term can "windup" and keep growing. But, the output of a PID can/should be limited on the output as well.
For example the following code calculates the integral term and then limits it according to a set value. It also limits the output of the controller, but according to a different limiting term.
void PID_Compute(PID *pid)
{

   //Find all error variables
   pid->lastError = pid->error;
   pid->error = pid->setpoint - pid->input;
   pid->derivative = pid->error - pid->lastError;
   pid->integral += pid->Ki * pid->error;

   //Anti-integral Windup
   if(pid->integral > pid->IntegralLimit){
       pid->integral = pid->IntegralLimit;
   }
   else if(pid->integral < -pid->IntegralLimit){
       pid->integral = -pid->IntegralLimit;
   }

   //Calculate PID
   pid->output = (pid->Kp*pid->error) + (pid->integral) + (pid->Kd * pid->derivative);

   //Set limits
   if(pid->output > pid->Outmax){
       pid->output = pid->Outmax;
   }
   else if(pid->output < pid->Outmin){
       pid->output = pid->Outmin;
   }
}

For anything pertaining to writing or understanding a PID controller, refer to Tim Wescott's article.

A: As others have already said, windup is only a problem for the I term.
Where I differ from almost everything else that I've seen, is that I don't like to arbitrarily limit my I.  I want it to be able to saturate the output no matter what it takes to do that, but there's no point in going beyond that.  So my limits are floating, based on the final output.
So I use a bigger datatype to hold the output than what I actually need, so I can detect out-of-range and clamp it.  Then as part of that clamp, I also unwind the I.  For one project, I actually back-calculated what it should have been to saturate exactly, but for another, I just switched on an exponential decay:
I_acc += Error;

//other code here

if (OUTPUT_OUT_OF_RANGE())
{
    CLAMP_OUTPUT();

    //anti_windup
    I_acc -= (I_acc >> 2);
}


text:
Q: Stored Procedure Join Entities Hibernate/Spring Data I got those two tables:
table z_users:

*

*id

*name

table z_phones:

*

*id

*iduser

*phone
I got a stored procedure with this query too:
Select * from z_users INNER JOIN z_phones on z_users.id = z_phones.iduser where z_users.id = 1;

I would like to fetch this stored proc via Spring Data/Hibernate.
So i created two classes:
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Immutable;

import javax.persistence.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Data
@Entity
@Immutable
@NoArgsConstructor
public class ZUser {

    @Id
    private int id;

    private String name;

    public ZUser(String name, ZPhone... zPhones) {
        this.name = name;
        this.zPhone.addAll(Arrays.stream(zPhones).collect(Collectors.toUnmodifiableList()));
    }

    @OneToMany
    private List<ZPhone> zPhone;

}

import lombok.Data;
import org.hibernate.annotations.Immutable;

import javax.persistence.Entity;
import javax.persistence.Id;

@Data
@Entity
@Immutable
public class ZPhone {

    @Id
    private int id;

    private String phone;

}

I tried to call the SP with this code:
import lombok.extern.slf4j.Slf4j;
import net.resourcestorage.demojoin.database.model.ZUser;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Slf4j
@Service
public class ZUserService {

    @PersistenceContext
    private EntityManager entityManager;

    public List<ZUser> getUsers() {
        Session session = (Session) entityManager.getDelegate();
        Query query = session.createSQLQuery("CALL getUsers()").addEntity(ZUser.class);

        log.info(query.getResultList().toString());
        List list = query.getResultList();

        return null; // don't care about this
    }

}

Running this, Hibernate does this:
Hibernate: CALL getUsers()
Hibernate: select zphone0_.ZUser_id as zuser_id1_4_0_, zphone0_.zPhone_id as zphone_i2_4_0_, zphone1_.id as id1_2_1_, zphone1_.phone as phone2_2_1_ from ZUser_ZPhone zphone0_ inner join ZPhone zphone1_ on zphone0_.zPhone_id=zphone1_.id where zphone0_.ZUser_id=?

Here, hibernate should not do the select.
I start to think that I'm not following the best way, which could be the best way to achieve my goal?
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Failed to load resource: the server responded with a status of 404 (Not Found) im trying to load a servlet for grid(xml) and I got that error "Failed to load resource: the server responded with a status of 404 (Not Found) error in server". How can i solve this?
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Data Binding Example</title>

<link rel="stylesheet" type="text/css"
    href="ext-5.1.1/examples/shared/example.css" />

Data Binding Example

A: Also make sure your link is correct, try using an absolute path:
""

If that doesn't work either give some more info.
If you don't have any server side code it will be hard to load a XML File from your directory.
If the content is really simple (eg just a list) then your file could just be a simple array.
var questions = [
  "What time is it?",
  "Is the sky blue?",
  "What do you call a fish with no legs?"
];

You can just include this file in your page with a script tag:

If your question structure is more complicated you can include it in a JSON format that allows for complex nesting etc.
var questions = [
  {
    "id":1,
    "question":"What time is it?",
    "datatype":"text"
  },
  {
    "id":2,
    "question":"Is the sky blue?",
    "datatype":"boolean"
  },
  {
    "id":3,
    "question":"What do you call a fish with no legs?",
    "datatype":"text"
  }
];


text:
Q: How to escape html tags in Extjs? I want to add some examples(see below) curl commands to show users how to do a certain action. The problem is I want to wrap it in a pre tag. So when I use the HTML tag I get the compiled pre tag but the "<>" disappear for '' because it thinks it's HTML. I need both the pre tags to work correctly en literally show the other parts wrapped in '<>'.
curl -XPOST --header "Content-Type: application/json" --data ""
cls: 'curl-example',
    bind: {
         html: '
curl -XPOST --header "Content-Type: application/json" --data "<your json data>"
'
}

This causes the opposite problem. The pre tag get literally printed.
cls: 'curl-example',
    bind: {
         text: '
curl -XPOST --header "Content-Type: application/json" --data "<your json data>"
'
}

A: Try to use Ext.htmlEncode() and Ext.htmlDecode() methods.


text:
Q: TeeChart v8: How to change fonts in runtime? Goal:
I want to change fonts in runtime. For example change font of legend text, titles, axis lables and so on.
Problem:
I can't find any function to change fonts by passing CFont object. I used function SetFont ( m_chartObj.SetFont( pFont ) ) but it doesn't change anything. I think I should change font separately for legend, axis and other objects, but I can't find such functions.
Question:
Does someone know such functions in order to change fonts during runtime, not in editor?

A: As you've probably found, the editor includes the option to change all the fonts at once:

However, there isn't a function to do the same at runtime, so you should change the properties of all the fonts you want to change manually.
Ie, in VB6:
Private Sub Form_Load()
  TChart1.AddSeries scBar
  TChart1.Series(0).FillSampleValues 8

  ChangeFont TChart1.Axis.Left.Labels.Font
  ChangeFont TChart1.Axis.Bottom.Labels.Font
  ChangeFont TChart1.Header.Font
  ChangeFont TChart1.Legend.Font
  ChangeFont TChart1.Series(0).Marks.Font
End Sub

Private Sub ChangeFont(fnt As IChartFont)
  fnt.Bold = True
  fnt.Name = "Arial"
  fnt.Size = 10
End Sub


text:
Q: jsp session timing out I have a jsp page with a button . When the user clicks the button, it starts a particular operation (data processing) on the server.
The problem is that if the size of the data is big , the jsp page crashes after a few minutes and I see an error message : "IE cannot display the page".
However , the server processing is not affected and runs to completion.
I think that the jsp session may be timing out .
Why is this happening and what can I do to solve it ?
I am using Apache Tomcat web server.


text:
Q: How to read data from a BLE device continuously to android app? I am developing an android app that is going to communicate with a BLE device(RN4020) connected with a target  board(micro controller). I developed the app that can able to send data to the target board through RN4020 and it received successfully through UART.But I am unable to receive data to the app from target device.  I am sending data for every one second from microcontroller. But with the app MLDP perminal downloaded from play store can able to send and receive data simultaneously.
While debugging it doesn't reach onCharacteristicRead.
How to receive data from the device to app?
package com.example.designemb5.tempworking;

import android.Manifest;
    import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

BluetoothManager btManager;
BluetoothAdapter btAdapter;
BluetoothLeScanner btScanner;
BluetoothDevice mBluetoothDevice;
public BluetoothAdapter mBluetoothAdapter;
public BluetoothGatt mBluetoothGatt;
public BluetoothGattService mBluetoothGattService;
private int mConnectionState = STATE_DISCONNECTED;
private BluetoothGattCharacteristic mWriteCharacteristic;
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;
Button startScanningButton;
Button stopScanningButton;
Button connectButton;
Button disconnectButton;
public boolean mConnected = false;
public boolean mCharacteristics = true;
private static final String TAG = "BLUETOOTH_LE";
public static List<ParcelUuid> MY_UUID;
public final static String ACTION_GATT_CONNECTED = "com.example.designemb5.tempworking.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED = "com.example.designemb5.tempworking.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.example.designemb5.tempworking.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE = "com.example.designemb5.tempworking.ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA = "com.example.designemb5.tempworking.EXTRA_DATA";

public final static UUID MY_UUID_RN4020_SERVICE = UUID.fromString("00035b03-58e6-07dd-021a-08123a000300");
public final static UUID MY_UUID_RN4020_CHARACTERISTIC_WRITE = UUID.fromString("00035b03-58e6-07dd-021a-08123a000301");
public final static UUID MY_UUID_RN4020_CHARACTERISTIC_READ = UUID.fromString("00035b03-58e6-07dd-021a-08123a0003ff");
TextView peripheralTextView;
private final static int REQUEST_ENABLE_BT = 1;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
public String mDeviceAddress;
public int mTestVal = 1;
public static Map<ParcelUuid, byte[]> mDeviceData;
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    connectButton = (Button) findViewById(R.id.ConnectButton);
    disconnectButton = (Button) findViewById(R.id.disonnectButton);

    peripheralTextView = (TextView) findViewById(R.id.PeripheralTextView);
    peripheralTextView.setMovementMethod(new ScrollingMovementMethod());

    startScanningButton = (Button) findViewById(R.id.StartScanButton);
    startScanningButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startScanning();
        }
    });

    stopScanningButton = (Button) findViewById(R.id.StopScanButton);
    stopScanningButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            stopScanning();
        }
    });
    stopScanningButton.setVisibility(View.INVISIBLE);

    btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
    btAdapter = btManager.getAdapter();
    btScanner = btAdapter.getBluetoothLeScanner();

    if (btAdapter != null && !btAdapter.isEnabled()) {
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
    }

    // Make sure we have access coarse location enabled, if not, prompt the user to enable it
    if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("This app needs location access");
        builder.setMessage("Please grant location access so this app can detect peripherals.");
        builder.setPositiveButton(android.R.string.ok, null);
        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
        });
        builder.show();
    }
}

public void startScanning() {
    System.out.println("start scanning");
    peripheralTextView.setText("");
    startScanningButton.setVisibility(View.INVISIBLE);
    stopScanningButton.setVisibility(View.VISIBLE);
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            btScanner.startScan(leScanCallback);
        }
    });
}

public void stopScanning() {
    System.out.println("stopping scanning");
    peripheralTextView.append("Stopped Scanning");
    startScanningButton.setVisibility(View.VISIBLE);
    stopScanningButton.setVisibility(View.INVISIBLE);
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            btScanner.stopScan(leScanCallback);
        }
    });
}

public void connect(View view) {
    connectButton.setVisibility(View.INVISIBLE);
    disconnectButton.setVisibility(View.VISIBLE);

    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    final BluetoothDevice device = btAdapter
            .getRemoteDevice(mDeviceAddress);
    mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
}

public void disconnect(View view) {
    connectButton.setVisibility(View.VISIBLE);
    disconnectButton.setVisibility(View.INVISIBLE);
    mBluetoothGatt.disconnect();
}

public void senddata(View view) {
    {
        int value = 0x01;
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
    /*check if the service is available on the device*/
        BluetoothGattService mCustomService = mBluetoothGatt.getService(MY_UUID_RN4020_SERVICE);
        if (mCustomService == null) {
            Log.w(TAG, "Custom BLE Service not found");
            return;
        }
    /*get the read characteristic from the service*/
        BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(MY_UUID_RN4020_CHARACTERISTIC_WRITE);
        mWriteCharacteristic.setValue(value, BluetoothGattCharacteristic.FORMAT_UINT8, 0);
        if (mBluetoothGatt.writeCharacteristic(mWriteCharacteristic) == false) {
            Log.w(TAG, "Failed to write characteristic");
        }
    }
}

public void receivedata(View view) {
    {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
    /*check if the service is available on the device*/
        BluetoothGattService mCustomService = mBluetoothGatt.getService(MY_UUID_RN4020_SERVICE);
        if (mCustomService == null) {
            Log.w(TAG, "Custom BLE Service not found");
            return;
        }

        BluetoothGattCharacteristic mReadCharacteristic = mCustomService.getCharacteristic(MY_UUID_RN4020_CHARACTERISTIC_READ);
        if (mBluetoothGatt.readCharacteristic(mReadCharacteristic) == false) {
            Log.w(TAG, "Failed to read characteristic");
        }
        mBluetoothGatt.readCharacteristic(mReadCharacteristic);
    }
}

// Device scan callback.
private ScanCallback leScanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        processResult(result);
    }

    private void processResult(ScanResult result){
        mBluetoothDevice = result.getDevice();
        mDeviceAddress = result.getDevice().getAddress();
        mDeviceData = result.getScanRecord().getServiceData();
        MY_UUID = result.getScanRecord().getServiceUuids();
        peripheralTextView.append("Device Name: " + mDeviceAddress + "\n");
        stopScanning();
    }
};

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicWrite(gatt, characteristic, status);
//            updateStatus(characteristic);
        Log.e("gatt", "writeChar");
    }

    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                        int newState) {
        String intentAction;
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            intentAction = ACTION_GATT_CONNECTED;
            mConnectionState = STATE_CONNECTED;
            broadcastUpdate(intentAction);
            Log.i(TAG, "Connected to GATT server.");
            // Attempts to discover services after successful connection.
            Log.i(TAG, "Attempting to start service discovery:"
                    + mBluetoothGatt.discoverServices());
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    if (mBluetoothGatt != null)
                        mBluetoothGatt.readRemoteRssi();
                }
            };
            Timer mRssiTimer = new Timer();
            mRssiTimer.schedule(task, 1000, 1000);

        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            intentAction = ACTION_GATT_DISCONNECTED;
            mConnectionState = STATE_DISCONNECTED;

            Log.i(TAG, "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {

        if (status == BluetoothGatt.GATT_SUCCESS) {
            broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
        } else {
            Log.w(TAG, "onServicesDiscovered received: " + status);
        }

        BluetoothGattService mCustomService = mBluetoothGatt.getService(MY_UUID_RN4020_SERVICE);

        BluetoothGattCharacteristic mReadCharacteristic = mCustomService.getCharacteristic(MY_UUID_RN4020_CHARACTERISTIC_READ);

        gatt.readCharacteristic(mReadCharacteristic);
        gatt.setCharacteristicNotification(mReadCharacteristic, true);
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic characteristic, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            gatt.readCharacteristic(characteristic);
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic) {
        broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
    }

};

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_COARSE_LOCATION: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                System.out.println("coarse location permission granted");
            } else {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Functionality limited");
                builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                    }

                });
                builder.show();
            }
            return;
        }
    }
}

public void writeCharacteristic(BluetoothGattCharacteristic characteristic) {
    mBluetoothGatt.writeCharacteristic(characteristic);
}

private void broadcastUpdate(final String action) {
    final Intent intent = new Intent(action);
    sendBroadcast(intent);
}

private void broadcastUpdate(final String action,
                             final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    // This is special handling for the Heart Rate Measurement profile. Data
    // parsing is
    // carried out as per profile specifications:
    // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
   /* if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        int flag = characteristic.getProperties();
        int format = -1;
        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
        } else {
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
        }
        final int heartRate = characteristic.getIntValue(format, 1);
        Log.d(TAG, String.format("Received heart rate: %d", heartRate));
        intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
    } else {
        // For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(
                    data.length);
            for (byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));
            intent.putExtra(EXTRA_DATA, new String(data) + "\n"
                    + stringBuilder.toString());
        }
    }*/

    final byte[] data = characteristic.getValue();

    Log.v(TAG, "data.length: " + data.length);

    if (data != null && data.length > 0) {
        final StringBuilder stringBuilder = new StringBuilder(data.length);
        for(byte byteChar : data) {
            stringBuilder.append(String.format("%02X ", byteChar));

            Log.v(TAG, String.format("%02X ", byteChar));
        }
        intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
    }

    sendBroadcast(intent);
}

private void showMessage(String str){
    Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}

}

A: To enable notifications:
 gatt.setCharacteristicNotification(yourCharacteristic, true);

 BluetoothGattDescriptor desc = yourCharacteristic.getDescriptor(UUID);

then:
desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(desc);

After doing this, onCharacteristicChanged() should be called every time data is sent. Confirm that enabling notifications was successful by overriding the onDescriptorWrite() method.


text:
Q: Feed streaming HTTP to Scala's XMLEventReader? Originally I was trying to use Java APIs for this, but now I am going to see if I can use Scala to parse XML documents coming through an XML stream. The following is a basic setup of XMLEventReader:
val reader = new xml.pull.XMLEventReader(IOSource)
while (reader.hasNext) System.out.println(reader.next)

The problem is IOSource must be a form of scala.io.Source and I'm only seeing local file methods for such parsing. What native Scala APIs can I use to feed XML coming from streaming HTTP to the event reader?
Thanks!
Edit
Looks like a Java API is going to be necessary. So instead, is it possible to convert a Java InputStream into a Scala io.Source?

A: Scala 2.10.2 standard library scala.io.Source (you want object Source, not abstract class Source) offers a number of from* methods, including fromInputStream and fromURL.
Scala 2.9.X is, if I recall, similar if not the same.


text:
Q: IVR development I need to build an IVR application (possibly 10 Phone lines). I am entirely new to this domain and am familiar with some concepts, Can someone please provide me with some links/advice on how I can go about building the IVR system?
Also, I need to know the exact process, whats involved, if I need to rent phone lines? etc., If I want to provide a hosted IVR service to my clients, what do I need.
any advice is much appreciated.
Many Thanks

A: Is this programming related?
http://www.asterisk.org/applications/ivr


text:
Q: Bison can't solve conflicts shift-reduce and reduce-reduce I am writing a parser using Bison, but can't seem to get the grammar correct.
There are two conflicts:
Here are some of the rules used around conflict one:
program                 :           function END_OF_FILE {return 0;}
formal_parameters       :           OPEN_PAREN formal_parameter list_E_fparameter CLOSE_PAREN | OPEN_PAREN CLOSE_PAREN
formal_parameter        :           expression_parameter | function_parameter
function                :           return_options IDENTIFIER formal_parameters block
function_parameter      :           return_options IDENTIFIER formal_parameters
expression_parameter    :           VAR identifier_list IDENTIFIER | identifier_list IDENTIFIER
variable_creation       :           identifier_list COLON type SEMI_COLON
labels                  :           LABELS identifier_list SEMI_COLON
list_E_identifiers      :           list_E_identifiers COMMA IDENTIFIER |
identifier_list         :           IDENTIFIER list_E_identifiers
return_options          :           VOID | IDENTIFIER

State 12 conflicts: 1 reduce/reduce
state 12

   56 identifier_list: IDENTIFIER . list_E_identifiers
   60 return_options: IDENTIFIER .
  102 list_E_identifiers: . list_E_identifiers COMMA IDENTIFIER
  103                   | .

    COMMA       reduce using rule 103 (list_E_identifiers)
    IDENTIFIER  reduce using rule 60 (return_options)
    IDENTIFIER  [reduce using rule 103 (list_E_identifiers)]
    $default    reduce using rule 60 (return_options)

    list_E_identifiers  go to state 23

State 64 conflicts: 1 shift/reduce
state 64

    8 body: OPEN_BRACE list_E_statement . CLOSE_BRACE
   17 statement: . opt_declaration unlabeled_statement
   18          | . compound
   31 compound: . OPEN_BRACE list_NE_unlstatement CLOSE_BRACE
   73 opt_declaration: . IDENTIFIER COLON
   74                | .
   94 list_E_statement: list_E_statement . statement

    CLOSE_BRACE  shift, and go to state 68
    IDENTIFIER   shift, and go to state 69
    OPEN_BRACE   shift, and go to state 70

    IDENTIFIER  [reduce using rule 74 (opt_declaration)]
    $default    reduce using rule 74 (opt_declaration)

    statement        go to state 71
    compound         go to state 72
    opt_declaration  go to state 73

Can anyone help me? I've looked at http://www.gnu.org/software/bison/manual/html_node/Understanding.html but can't understand what this means.
I can post the full grammar if that would help.
Thank you!

A: The second conflict is a classic problem with "optional" elements. It's very tempting to write a rule for optional labels as you have done it, but the fact that optional_label could produce nothing forces the parser to try to make a decision before it has enough information.
LR parsers must "reduce" (recognize) a non-terminal before absorbing any further tokens. They can lookahead at the next k tokens (the next 1 token for an LR(1) parser, which is what bison generates), but they can't tentatively use the token and later go back and do the reduction.
So when the parser is at the point where the next token, which is an identifier, should start a statement, it might be looking at a statement which starts with an identifier, or it might be looking at a label which starts with an identifier. It could tell the difference by looking at the colon which follows the identifier (if any) but it can't see that far ahead.
Now, if it weren't for the fact that it is required to reduce either an empty optional_declaration or one containing a label, there would not be a problem. If you had written something like this:
statement: basic_statement | compound
basic_statement: unlabeled_statement | declaration unlabeled_statement
declaration: IDENTIFIER COLON

then the parser would not have to make a decision when it sees the identifier. It only has to make a decision when it reaches the end of a production; it is perfectly capable of pressing forward when there are two possible productions to complete. But when you force it to recognize an optional label, then it has to know whether the label was not there in order to reduce (recognize) the empty production.
For the first conflict, we can see from the output that there is some context in which the lookahead symbol is IDENTIFIER and you could have either a return_options or an identifier_list. Since both of those productions can produce a single IDENTIFIER, the parser will not know which one to reduce.
With the actual grammar available, it is easy to find the context in which both return_options IDENTIFIER and identifier_list IDENTIFIER are possible:
formal_parameter    : expression_parameter | function_parameter
expression_parameter: identifier_list IDENTIFIER
function_parameter  : return_options  IDENTIFIER …

That grammar is not ambiguous. If IDENTIFIER IDENTIFIER is the start of function_parameter, then it must be followed by a (; if it is an expression_parameter, then it must be followed by either , or ). But that's the second next token, which means you'd need an LR(2) parser.
So I will give my usual advice on handling LR(2) grammars. It is possible to rewrite an LR(k) grammar as an LR(1) grammar, regardless of the value of k, but the result is usually bloated and ugly. So if you are using bison and you are willing to live with the possibility that action evaluations could be slightly delayed, then your easiest solution is to ask bison to generate a GLR parser. Often, just adding %glr-parser to the options section is enough.
It's worth noting that your grammar seems to be an uneasy mix between C and Pascal-like syntaxes. In C, the first token in a parameter is always a type; either the return type of a function, or the type of the following identifier. In Pascal, the last token in a parameter is the type. But in your grammar, sometimes the first token is the type and sometimes it's the last token. In a certain sense, it is this inconsistency which leads to the awkwardness in the grammar.
(Pascal has a lot more punctuation: the type is always preceded by a colon and a function parameter is preceded by the word function. These extra tokens are not needed to make the grammar work, but it can be argued that they make the syntax easier to read by humans.)


text:
Q: Circles in an Equilateral Triangle
In the diagram below is an equilateral triangle with side length of 1 unit. $C_1$, $C_2$ and $C_3$ are circles inside the triangle tangent to each other and the sides of the triangle. Find the radius of each circle.

Firstly, I'm inclined to think that the circles must all be equal in size, but I'm not sure how to prove that. And I also tried making a smaller triangle inside the outer triangle by connecting the radii of the circles, but I'm not sure how to proceed after that (or if I'm even on the right track for that matter).

A: By construction you have $$1=\sqrt 3r+r+r+\sqrt 3r\Rightarrow r=\frac{\sqrt3-1}{4}\approx 0.183012701$$ Later add an explanatory figure.

A: Nobody says the circles have the same radii. One can prove it and that's the point of this problem. The condition is that the three circles are in the equilateral triangle (because there are configurations in which one circle can be outside and it's bigger than the other two, but still touches both and each circle touches a pair of "extended" edges of the triangle!).
Proof 1. One way is to use the uniqueness of solution to Apollonius' problem. Indeed, let us assume that the three circles $c_1, c_2, c_3$ are in the equilateral triangle $A_1A_2A_3$ and each circle $c_i$ is simultaneously tangent to the edges $A_iA_j$ and $A_iA_k$ for $i\neq j\neq k \in \{1,2,3\}$. Draw the angle bisector $A_3H_3\,\,$ ($H_3 \in A_1A_2$), which is also a line of reflection symmetry of triangle $A_1A_2A_3$ ($A_3H_3$ is also the median, the altitude and the orthogonal edge bisector to the edge $A_1A_2$). Then the center $O_3$ of circle $c_3$ lies on $A_3H_3$ and if we perform a reflection with respect to $A_3H_3$ the triangle $A_1A_2A_3$ is mapped to itself and $c_3$ is mapped to itself. Now since $c_1$ is tangent to circle $c_3$ and edges $A_1A_2$ and $A_1A_3$, which after reflection are mapped to $c_3, $  $A_2A_1$ and $A_2A_3$, the reflective image of $c_1$ is a circle $c_1'$ which is tangent to circle  $c_3$ and edges  $A_2A_1$ and $A_2A_3$ and is inside the triangle. Now, by the uniqueness of the solution to Apollonius' problem applied to circle $c_3$ and edges $A_2A_1$ and $A_2A_3$, there is only one circle tangent to $c_3$, $A_2A_1$ and $A_2A_3$ and located inside the triangle and since both $c'_1$ and $c_2$ are solutions to Apollonius' problem with these conditions, $c'_1 = c_2$, so $c_2$ is the reflective image of $c_1$ under the reflection with respect to $A_3H_3$. Consequently, the radius $r_1$ of $c_1$  and the radius $r_2$ of $c_2$ are equal, $r_1 = r_2$. Now, carry out the same argument but with respect to vertex $A_2$ and axis of symmetry $A_2H_2$. That would lead to the conclusion that the radius $r_1$ of $c_1$  and the radius $r_3$ of $c_3$ are equal, and consequently  $r_1 = r_2=r_3$.
Proof 2. Assume the radii of the three circles are $r_1, r_2, r_3 > 0$. Since the circles are inside the triangle, $r_1, r_2, r_3 < 1$. Take for instance the two tangent circles $c_1$ and $c_2$ of radii $r_1$ and $r_2$ and centers $O_1$ and $O_2$ respectively. Let $T_1$ and $T_2$ be the points of tangency of $c_1$ and $c_2$ twith the triangle edge $A_1A_2$ tangent to both of them simultaneously. Then $O_1T_1$ and $O_2T_2$ are perpendicular to $A_1A_2$ and are therefore parallel. We have a trapezoid $T_1T_2O_2O_1$ with $T_1T_2$ orthogonal to the parallel $O_1T_1$ and $O_2T_2$. Moreover, $|O_1T_1| = r_1, \,\, |O_2T_2| = r_2$ and $|O_1O_2| = r_1 + r_2$. Then by drawing a line through say $O_2$ parallel to $T_1T_2$, we obtain a right angled triangle with hypotenuse $|O_1O_2| = r_1+r_2$ and another edge of length $|r_1-r_2|$. By Pythagoras' theorem, $$|T_1T_2| = \sqrt{(r_1+r_2)^2 - (r_1-r_2)^2} = 2 \sqrt{r_1r_2}.$$ Analogously,
   $$|T_2T_3| = \sqrt{(r_2+r_3)^2 - (r_2-r_3)^2} = 2 \sqrt{r_2r_3}.$$
$$|T_3T_1| = \sqrt{(r_3+r_1)^2 - (r_3-r_1)^2} = 2 \sqrt{r_3r_1}.$$  The two tangents from $A_1$  to the circle $c_1$ (on of them is $AT_1$) have equal lengths $\sqrt{3}\, r_1$ because triangle $AT_1O_1$ is right angled with angle $\angle \, T_1A_1O_1 = 30^{\circ}$, and since $|A_1O_1| = 2 \, r_1, \, |O_1T_1| = r_1$ and hence $|A_1T_1| = \sqrt{3}\, r_1$. Similarly, for the other vertices of the triangle, the common tangents from the given vertex and the corresponding closest circle have lengths respectively $ \sqrt{3}\, r_2$ and $ \sqrt{3}\, r_3$. Thus the length of the three edges of the equilateral triangle (they are all equal and of length $1$) can be expressed as
\begin{align}
\sqrt{3}(r_1 + r_2) + 2 \sqrt{r_1\, r_2} &= 1\\
\sqrt{3}(r_2 + r_3) + 2 \sqrt{r_2\, r_3} &= 1\\
\sqrt{3}(r_3 + r_1) + 2 \sqrt{r_3\, r_1} &= 1
\end{align}
To solve this system, set $r_2 = x_2^2 \, r_1$ and $r_3 = x_3^2 \, r_1$ and plug in the equations these two expression  to arrive at
\begin{align}
\sqrt{3}(1 + x^2_2) + 2 \, x_2 &= \frac{1}{r_1}\\
\sqrt{3}(x^2_2 + x^2_3) + 2 \, {x_2\, x_3} &= \frac{1}{r_1}\\
\sqrt{3}(1 + x^2_3) + 2 \, x_3 &= \frac{1}{r_1}
\end{align} This is a system that simultaneously finds $r_1$ and $x_2, \, x_3$.
Look at the polynomial
$$f(x) = \sqrt{3}\, x^2 + 2 \, x + \sqrt{3} - \frac{1}{r_1}$$ Then the first and the third equations from above are actually $$f(x_2) = 0 \,\,\, \text{ and } \,\,\, f(x_3) = 0$$ i.e. $x_2$ and $x_3$ are two roots (different or the same) of the polynomial $f$. Consequently
\begin{align}
f(x_2) = \sqrt{3}\, x^2_2 + 2 \, x_2 + \sqrt{3} - \frac{1}{r_1} &=0\\
\sqrt{3}\big((x_2 + x_3)^2 - 2\, x_2x_3\big) + 2 \, {x_2\, x_3} &= \frac{1}{r_1}\\
f(x_3) = \sqrt{3}\, x^2_3 + 2 \, x_3 + \sqrt{3} - \frac{1}{r_1} &=0
\end{align}
or in another form
\begin{align}
f(x_2) = \sqrt{3}\, x^2_2 + 2 \, x_2 + \sqrt{3} - \frac{1}{r_1} &=0\\
\sqrt{3}(x_2 + x_3)^2 + (2- 2\sqrt{3})\, x_2 \, x_3 &= \frac{1}{r_1}\\
f(x_3) = \sqrt{3}\, x^2_3 + 2 \, x_3 + \sqrt{3} - \frac{1}{r_1} &=0
\end{align}
Case1: Assume $x_2$ and $x_3$ are the two roots of $f$ (could be that $x_2\neq x_3$ or could be that $x_2=x_3$ is a double root). By Vieta's formulas
$$x_2+x_3 = - \, \frac{2}{\sqrt{3}} \,\,\,\,\, x_2\, x_3 = 1- \frac{1}{\sqrt{3} \, r_1}$$ so if we plug them in the second equaiton
$$\frac{4 \sqrt{3}}{3} + (2- 2\sqrt{3}) - (2- 2\sqrt{3})\frac{1}{\sqrt{3} \, r_1} = \frac{1}{r_1}$$
$$2 - \frac{2 \sqrt{3}}{3} + \left(2 - \frac{2 \sqrt{3}}{3}\right)\frac{1}{ r_1} = \frac{1}{r_1}$$
$$1 + \frac{1}{r_1}=\frac{3}{6-2\sqrt{3}} \, \frac{1}{r_1}$$
$$1 =  \frac{3}{6-2\sqrt{3}} \, \frac{1}{r_1} - \frac{1}{r_1} = \left( \frac{3}{6-2\sqrt{3}}  - 1\right) \, \frac{1}{r_1}$$ when you solve for $r_1$ one gets
$$r_1 = \frac{\sqrt{3}-1}{4}.$$ The solutions $x_2$ and $x_3$ are different, one of them is, let's say $x_2$ is $1$ and the other, $x_3$, is greater than $1$ in absolute value, which leads to $r_3>1$. This is not a solution to our configuration.
Case 2: $x_2 = x_3 = x$. Then the equations reduce to
\begin{align}
f(x) = \sqrt{3}\, x^2 + 2 \, x + \sqrt{3} - \frac{1}{r_1} &=0\\
(2 \sqrt{3} + 2 )\, x^2 - \frac{1}{r_1} &= 0
\end{align}
which leads to the equation
$$(\sqrt{3} + 2) \, x^2 - 2\, x - \sqrt{3} = 0$$
and it is easy to see that $x=1$ is a solution. Then the other solution is $x^* = - \,\frac{\sqrt{3}}{\sqrt{3} + 2}$.
If $x=1$ then plug it in the second equation of the system above. This leads to $$r_3 = r_2 = r_1 = \frac{\sqrt{3}-1}{4}$$
If $x=x^*$, then one sees that $r_1 > 1$ which is not a solution to our problem, as then circle $c_1$ should not be inside the triangle $A_1A_2A_3$.

A: Make a right triangle by drawing the segment connecting a vertex of your triangle to the center of the nearest circle, and dropping the perpendicular from that circle.  As this is a $30-60-90$ triangle we see that the leg along the triangle side has length $\sqrt 3 \,r$.  Inspection quickly shows that $$1=2\sqrt 3\, r+2r\implies r = \frac {\sqrt3 -1}4$$

A: Here is a simple proof that three circles, each of them touching two sides of the triangle $\triangle$  from the inside, necessarily have the same radius:
Each circle has its center on a symmetry axis of the triangle. Given such a circle $\gamma_c$ with its center on $m_c$, and at least so large  that $\gamma_c$ intersects the incircle of $\triangle$,  the radius $r_a$ of a circle having its center on $m_a$ that touches $\gamma_c$ from the outside is uniquely determined, and due to symmetry with respect to the line $m_c$ it is equal to the radius $r_b$ of the circle having its center on $m_b$ that touches $\gamma_c$. From $r_a=r_b$ it follows that all three radii are equal.


text:
Q: VSCode: fixed current working directory for new R terminal in multi-root projects I have a multi-root project in VSCode. I work with R and have the R LSP Client extension installed. I am on MacOS.
My workspace file looks like this:
{
    "folders": [
        {
            "path": "."
            "name": "myproject"
        },
        {
            "path": "../otherfolder"
            "name": "another_project"
        }
    ],
    "settings": {}
}

I use bash terminal and R terminal. I want these two to open always with current working directory . and not ../otherfolder or having to chose.
Ideally this should be a user setting, not of the workspace.

A: After a bit of practicing, I realised something that is probably quite obvious to more experienced users. The terminal current working directory (cwd)
is chosen accordingly to the file that is opened in the editor. If no file is opened, than the last cwd is used.
So, in the example of the question, if I open a file belonging to 'myproject' and open a terminal, this will have ./ as cwd.
If the file in the editor belongs to 'another_project', the cwdof the terminal will be ../otherfolder.
This does not address exactly the question (having a fixed terminal folder) but it fixes my workflow.
Looking at the settings, the parameter "terminal.integrated.cwd":"./somefolder" would seem to do the job to have a fixed cwd for the terminal as it is described as following:

An explicit start path where the terminal will be launched, this is used as the current working directory (cwd) for the shell process. This may be particularly useful in workspace settings if the root directory is not a convenient cwd.

But I might misunderstand the description, because I tried to set it to some local folder and it had no effect for me.


text:
Q: Robustness of Gaussian Copula I am looking for studies regarding the robustness of a multivariate Gaussian copula. Specifically I am wondering whether estimates of the dependence parameter in a multivariate Gaussian Copula (Sigma) are robust to violations of the underlying assumptions. Many approaches that rely on normal distribution assumptions tend to be robust when those assumptions are violated. I am wondering whether the same extends to the Gaussian copula.
Let me give you some more details on the problem I am struggling with: I am using the approach proposed by Hoff 2007 to estimate the dependence structure between a set of demographic variables. The problem is that the sample I am using is biased in the sense that some demographic groups are over- and others under-represented (e.g., too many old people). I am wondering to which extent my estimate of the dependence structure is robust to mild forms of bias.
Thanks very much for your help in advance.
Michael
Hoff, Peter D. (2007), "Extending the Rank Likelihood for Semiparametric Copula Estimation," The annals of applied statistics, 1 (1), 265 - 83


text:
Q: Chrome is allowing insecure pages via WebDriver Using Chrome 62 with Chrome Driver 2.33 and WebDriver 3.6.0, Chrome allows pages to load with bad SSL certificates -- it says "Not Secure" in the URL bar when the page opens, but the page is loaded none-the-less. If I access the page manually, then I get the expected 'blocker page'.
However, I want Chrome to reject the page via WebDriver just like Chrome does to human users.
Unfortunately I cannot find anyone else reporting this same problem (just lots of people reporting the exact opposite problem -- i.e. they want to allow insecure connections via WebDriver, but Chrome keeps blocking them!).
Is there a flag I can set (or prevent from being set if WebDriver is passing one to Chrome internally)?
const {Builder, Capabilities} = require('selenium-webdriver');

const driver = new Builder()
  .withCapabilities(Capabilities.chrome())
  .build();

driver.get('https://localhost/'); // Uses self-signed certificate.

A: By default, chromedriver accepts untrusted certificates.
To disable this feature, you'll have to exclude the switch ignore-certificate-errors:
var webdriver = require('selenium-webdriver');

var driver = new webdriver.Builder()
  .withCapabilities({
    'browserName': 'chrome',
    'goog:chromeOptions': {
      'args': ['disable-infobars'],
      'excludeSwitches': ['ignore-certificate-errors'],
      'prefs': { }
    }
  }).build();

driver.get("https://self-signed.badssl.com/")


text:
Q: CSS - Making all images have a circular type border In my project, I allow users to upload profile pictures. I want these pictures to have a  circular border, like instagram profile pictures do. Does anybody know how to add this affect?
I have tried the border-radius property, however this makes some images with white/transparent backgrounds looking like they have been cropped, and doesn't have the expected outcome.
Does anybody know how to add a circular type border to any image that is upload by a user? Thank you.
HTML CODE:
.fixedImage {
    position: relative;
    left: 70px;
    width: 25px;
    top: 50px;
    height: 25px;
    border-radius: 50%;
}

A: Use a border and a box-shadow...

div {
  text-align: center;
  display: inline-block;
  padding: 2em 3em;
  border: 1px solid lightgrey;
  background: lightgreen;
}

img {
  display: block;
  border-radius: 50%;
  border: 5px solid transparent;
  box-shadow: 0 0 0 5px red;
}

.white {
  border-color: white;
}

  Transparent border

  White border

A: Instead of img, you can use div and have your image in background. This will allow you to add a background color of your choice to avoid the transparency.
Example:

CSS:
.fixedImage {
    position: relative;
    top: 50px;
    left: 70px;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-color: #fff;
    background-size: 100px 100px;
}

A: I think https://medium.com/@biancapower/how-to-make-a-rectangle-image-a-circle-in-css-2f392bc9abd3 is what you are looking for.
A div around the image gets the border-radius: 50%
HTML:

CSS:
img {
  height: 200px;
  width: 200px;
  padding: 20px;
}

.image-cropper {
  width: 240px; // it seems you need to add the padding twice here
  border-radius: 50%;
  border: 1px solid red;
  position: relative;
  overflow: hidden;
}

Fiddle:
https://jsfiddle.net/bdL8zmu1/
Without background color:
https://jsfiddle.net/94z27bdL/


text:
Q: Drawing CGImage into Bitmap context, with UIBezierPath drawn into the context beforehand this is my first question so please bear with me!
Im trying to write up a simple drawing app basically, I was using Core Graphics before, and the only problem was it was too slow, and when I drew with my finger it lagged, a hell of alot!
So, now I'm trying to use UIBezier paths to draw, as I understood to be alot faster, which it is!
When I was using Core Graphics, to keep the drawing speed up I was drawing to a custom bitmap context I created, which was constantly being updated as I drew.
So, I drew to my custom Bitmap context, then a CGImageRef was set to what was drawn in that context using -
cacheImage = CGBitmapContextCreateImage(imageContext);

and that was then drawn back into the bitmap context using -
CGContextDrawImage(imageContext, self.bounds, cacheImage); )

I also did this so when I changed the colour of the line being drawn, the rest of the drawing stayed as it was previously drawn, if that makes sense.
Now the problem Ive come across is this.
Im trying to draw the UIBezier path to my image context using -
imageContext = UIGraphicsGetCurrentContext();

UIGraphicsPushContext(imageContext);

[path stroke];

if(imageContext != nil){
    cacheImage = CGBitmapContextCreateImage(imageContext);  //invalid context here so added to solve

}

CGContextScaleCTM(imageContext, 1, -1); // using this as UIBezier

CGContextDrawImage(imageContext, self.bounds, cacheImage); // draws the current context;

[path removeAllPoints];

CGImageRelease(cacheImage); // releases the image to solve memory errors.

with path being my UIBezierPath. All the path set up is done in touches began and touched moved then calling [self setNeedsDisplay]; to call drawRect.
What's happening is when I draw, its either not drawing the CGImageRef to the context properly, or it is, but when its capturing the cache image its capturing a white background from somewhere, instead of just the path, and so its pasting over the entire image with the last path drawn together with a white background fill, so you cant see the last path that was drawn to build the image up, even though the views background colour is clearColor.
I really hope I'm making sense, I've just spent too many hours on this and Its drained me completely.  Heres the drawing method I'm using -
This to create the image context -
 -(CGContextRef) myCreateBitmapContext: (int) pixelsWide:(int) pixelsHigh{

    imageContext = NULL;

    CGColorSpaceRef colorSpace; // creating a colorspaceref
    void *          bitmapData; // creating bitmap data
    int             bitmapByteCount; // the bytes per count
    int             bitmapBytesPerRow; // number of bytes per row

    bitmapBytesPerRow   = (pixelsWide * 4); // calculating how many bytes per row the context     needs
    bitmapByteCount     = (bitmapBytesPerRow * pixelsHigh); // how many bytes there are in     total

    colorSpace = CGColorSpaceCreateDeviceRGB(); // setting the colourspaceRef

    bitmapData = malloc( bitmapByteCount ); // calculating the data

    if (bitmapData == NULL)
    {
        //NSLog(@"Memory not allocated!");
        return NULL;
    }

    imageContext = CGBitmapContextCreate (bitmapData,
                                          pixelsWide,
                                          pixelsHigh,
                                          8, // bits per component
                                          bitmapBytesPerRow,
                                          colorSpace,kCGImageAlphaPremultipliedLast);

    if (imageContext== NULL)
    {
        free (bitmapData);
        NSLog(@"context not created allocated!");
        return NULL;
    }
    CGColorSpaceRelease( colorSpace ); //releasing the colorspace

    CGContextSetRGBFillColor(imageContext, 1.0, 1.0, 1.0, 0.0); // filling the bitmap with a     white background
    CGContextFillRect(imageContext, self.bounds);
    CGContextSetShouldAntialias(imageContext, YES);

    return imageContext;
    }

And heres my drawing -
 -(void)drawRect:(CGRect)rect
{

    DataClass *data = [DataClass sharedInstance];

    [data.lineColor setStroke];
    [path setLineWidth:data.lineWidth];
    imageContext = UIGraphicsGetCurrentContext();

    UIGraphicsPushContext(imageContext);

    [path stroke];

    if(imageContext != nil){
        cacheImage = CGBitmapContextCreateImage(imageContext);
    }

    CGContextScaleCTM(imageContext, 1, -1); // this one

    CGContextDrawImage(imageContext, self.bounds, cacheImage); // draws the current     context;

    [path removeAllPoints];

    CGImageRelease(cacheImage); // releases the image to solve memory errors.

}

 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    DataClass *data = [DataClass sharedInstance];

    CGContextSetStrokeColorWithColor(imageContext, [data.lineColor CGColor]);

    ctr = 0;
    UITouch *touch2 = [touches anyObject];
    pts[0] = [touch2 locationInView:self];

}

 -(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];

    ctr++;
    pts[ctr] = p;
    if (ctr == 4)
    {

        pts[3] = CGPointMake((pts[2].x + pts[4].x)/2.0, (pts[2].y + pts[4].y)/2.0); // move     the endpoint to the middle of the line joining the second control point of the first Bezier     segment and the first control point of the second Bezier segment
        [path moveToPoint:pts[0]];
        [path addCurveToPoint:pts[3] controlPoint1:pts[1] controlPoint2:pts[2]]; // add a     cubic Bezier from pt[0] to pt[3], with control points pt[1] and pt[2]
        //[data.lineColor setStroke];

        [self setNeedsDisplay];
        // replace points and get ready to handle the next segment
        pts[0] = pts[3];
        pts[1] = pts[4];
        ctr = 1;
    }
}

 -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

    [path removeAllPoints];
    [self setNeedsDisplay];
    ctr = 0;
}

'path' is my UIBezierPath
'cacheImage' is a CGImageRef
'imageContext' is a CGContextRef
Any Help is much appreciated! And if you can think of a better way to do it, please let me know! I do however need the cache image to have a transparent background, so its just the paths visible, as I'm going to apply something later on when I get this working!
EDIT Also I'm removing the points everytime to keep the drawing speed up, just so you know!
Thanks in advance :)

A: Well, this is a big question. One potential lead would be to verify that you draw exactly what you need (not the whole image all the time), and to divide the invariant bitmap from those regions/rects which actively mutate across multiple layers.


text:
Q: how to catch fatal exceptions in flutter I have the following exception thrown from android(or it can be thrown from ios, it doesn't matter) and I can't catch it to avoid app crash. Is there a solution to do it?
  > [ +276 ms] E/AndroidRuntime( 9658): FATAL EXCEPTION: Thread-2 [
    > ] E/AndroidRuntime( 9658): Process: com.example.myonpu, PID: 9658 [
    > ] E/AndroidRuntime( 9658):
    > com.microsoft.identity.client.exception.MsalClientException:
    > Connection is not available to refresh token [        ]
    > E/AndroidRuntime( 9658):  at
    > com.microsoft.identity.client.internal.controllers.MsalExceptionAdapter.msalExceptionFromBaseException(MsalExceptionAdapter.java:49)
    > [        ] E/AndroidRuntime( 9658):   at
    > com.microsoft.identity.client.PublicClientApplication$9.onError(PublicClientApplication.java:1621)
    > [        ] E/AndroidRuntime( 9658):   at
    > com.microsoft.identity.common.internal.controllers.ApiDispatcher$4$1.run(ApiDispatcher.java:424)
    > [        ] E/AndroidRuntime( 9658):   at
    > android.os.Handler.handleCallback(Handler.java:751) [        ]
    > E/AndroidRuntime( 9658):  at
    > android.os.Handler.dispatchMessage(Handler.java:95) [        ]
    > E/AndroidRuntime( 9658):  at android.os.Looper.loop(Looper.java:154) [
    > ] E/AndroidRuntime( 9658):    at
    > android.app.ActivityThread.main(ActivityThread.java:6682) [        ]
    > E/AndroidRuntime( 9658):  at java.lang.reflect.Method.invoke(Native
    > Method) [        ] E/AndroidRuntime( 9658):   at
    > com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
    > [        ] E/AndroidRuntime( 9658):   at
    > com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) [
    > ] E/AndroidRuntime( 9658): Caused by:
    > com.microsoft.identity.common.exception.ClientException: Connection is
    > not available to refresh token [        ] E/AndroidRuntime( 9658):    at
    > com.microsoft.identity.common.adal.internal.net.HttpWebRequest.throwIfNetworkNotAvailable(HttpWebRequest.java:201)
    > [        ] E/AndroidRuntime( 9658):   at
    > com.microsoft.identity.common.internal.controllers.BaseController.performSilentTokenRequest(BaseController.java:328)
    > [        ] E/AndroidRuntime( 9658):   at
    > com.microsoft.identity.common.internal.controllers.BaseController.renewAccessToken(BaseController.java:204)
    > [        ] E/AndroidRuntime( 9658):   at
    > com.microsoft.identity.client.internal.controllers.LocalMSALController.acquireTokenSilent(LocalMSALController.java:252)
    > [        ] E/AndroidRuntime( 9658):   at
    > com.microsoft.identity.common.internal.controllers.TokenCommand.execute(TokenCommand.java:89)
    > [        ] E/AndroidRuntime( 9658):   at
    > com.microsoft.identity.common.internal.controllers.ApiDispatcher$4.run(ApiDispatcher.java:401)
    > [        ] E/AndroidRuntime( 9658):   at
    > java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    > [        ] E/AndroidRuntime( 9658):   at
    > java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    > [        ] E/AndroidRuntime( 9658):   at
    > java.lang.Thread.run(Thread.java:762)

I need not to catch namely this exception, but to catch "fatal exceptions" like this. I tried try/catch and catchError for Future and nothing can do it.
Also tried FlutterError.onError this way:
mymethod() async{
  await methodWhichCanThrowException();
  FlutterError.onError = (details) {
    FlutterError.dumpErrorToConsole(details);
  };
  ...
}

if it can help here is msal_flutter package https://github.com/moodio/msal-flutter which I use.

A: You can use the default method catchError() of flutter
mymethod() async{
  await methodWhichCanThrowException().catchError((e)=> print(e.toString());
  ...
}


text:
Q: How to use Stripe's secret key and publishable key? I would like to connect with the Stripe API using a https call using the https library.
var https = require('https');

I have gotten the secret key and publishable key and put it inside a object:
var stripe = {
  secret_key: 'secret_key_given_in_the_dashboard',
  publishable_key: 'publishable_key_given_in_the_dashboard'
}

I am now in the part of creating the requestDetail object:
var requestDetails = {
    'protocol'  : 'https:',
    'hostname'  : 'api.stripe.com',
    'method'    : 'POST', //WHICH OF POST GET PUT DELETE SHOULD I USE?
    'path'      : '???????????????????????',// WHICH ENDPOINT SHOULD I USE?
    'auth'      : '???????????????????????',// SHOULD I USE THE SECRET AND PUBLISHABLE KEY HERE?
    'headers'   : {
      'Content-Type'  : 'application/x-www-form-urlencoded',
      'Content-Length' : Buffer.byteLength(stringPayload)
    }
  };

I plan to make use of the requestDetails object in the call using https:
var req = https.request(requestDetails, function(res){
      // Grab the status of the sent request
      var status = res.statusCode;
      //Callback successfully if the request went through
      if(status == 200 || status == 201) {
        callback(false);
      } else {
        callback('Status code returned was ' + status);
      }
    });

Where and how should I use the secret key and publishable key in order to make a call to the stripe API?
Which endpoint?
Which method (POST, GET, PUT,or DELETE)?
I would like to eventually create a order and pay through the STRIPE api.
But for now just any authenticated call through the stripe api will do as I need a sample format that works....
I'm not too sure where to add the secret key and publishable key....

A: You should install official stripe package (source: https://github.com/stripe/stripe-node), require the package and authenticate it using your secret key ( example from the github docs):
const stripe = require('stripe')('your_stripe_secret_key');

stripe.customers.create({
  email: 'customer@example.com',
})
.then(customer => console.log(customer.id))
.catch(error => console.error(error));

The package is an abstraction to make the API requests for you.
More docs: https://stripe.com/docs/api?lang=node
However, if you want to use the https directly for Stripe API requests, which is not recommended, you can check the docs and examples for using the cURL, since it shows the endpoints for each example.
https://stripe.com/docs/api/authentication?lang=curl

A: try using fetch, 'Authorization': 'Bearer ' + sk.
My working example of retrieving a customer based on the customer_id:
const url = `https://api.stripe.com/v1/customers/${stripe_customer_id}`;
return await fetch(url, {
  method: "get",
  headers: {
    "Content-Type": "application/json",
    'Authorization': 'Bearer ' + sk,
  }
})
  .then(function(response) {
    return response.json();
  })
  .then(function(response) {
    // console.log(response);
    return response;
  });
};


text:
Q: Reading a text file to a char[][] using try/catch in Java I'm trying to read a maze text file to a double char array, the text file is formatted like so (with the two integers being the number of rows and columns respectively):
10 10
##########
#        #
#   ###  #
#   #  G #
#   #    #
#        #
#        #
#  #######
#   S    #
##########

My code so far:
public char[][] readFile(String filename) {
    char[][] maze = null;
    try {
        Scanner scan = new Scanner(new File(filename));
        int rows = scan.nextInt();
        int columns = scan.nextInt();

        maze = new char[rows][columns];
        String line;

        do {
            for (int i = 0; i < rows; i++) {
                line = scan.nextLine();
                for (int j = 0; j < columns; j++) {
                    maze[i][j] = line.charAt(j);
                }
            }
        } while (scan.hasNextLine());

        scan.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return maze;
}

I don't know how to return the array outside the try/catch block. The other posts going over this throw exceptions, which I cannot do due to implementing an interface.
I know initializing the array to null fixes any red flags, but then it spits out a StringIndexOutOfBounds in the console.
Sorry for the ugly code, but I haven't done much coding with file input/output.

A: you read too many lines...
let's assert your file has 12 lines, 1 line for the size, 10 lines for the maze and a 12th line with some other input.
your code works perfectly for the first 11 lines, but when your code is through with it you should stop reading further!
because it seems after reading the maze once you try to read it again, and i assume you try to read some content that does not match your input
boolean doneReading = false;
do {
    if(!doneReading){
        for (int i = 0; i < rows; i++) {
            line = scan.nextLine();
            for (int j = 0; j < columns; j++) {
                maze[i][j] = line.charAt(j);
            }
        }
        //now we have all input, now we can stop reading further
        doneReading = true;
    }
} while (scan.hasNextLine());

rather that reading the full file you could simply return the result as soon as you have read it
(alternativ version: return as soon as you can)
do {
    for (int i = 0; i < rows; i++) {
        line = scan.nextLine();
        for (int j = 0; j < columns; j++) {
            maze[i][j] = line.charAt(j);
        }
    }
    //now we have all input, now we even return
    return maze;
} while (scan.hasNextLine());

A: Your algorithm is OK. It simply lacks a call to scan.nextLine() before entering the first loop, to make the scanner match the end of the first line.
About the exception treatment, it should be like this:
public char[][] readFile(String filename)
{
    char[][] maze;
    try
    {
        ...
        maze=<a useful value>
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
        maze=<a default value, maybe null>
    }
    return maze;
}

The default value should be specified in the interface you are implementing. Or else, to throw a RuntimeException from the catch block would be the lesser of two evils.


text:
Q: Angular display div on option select, hide others I want to display a div(mat-card) if an option is selected and hide the other divs if they are not selected
Template
<mat-form-field>
  <mat-label>Select an option</mat-label>
  <mat-select [(value)]="selected">
    <mat-option>None</mat-option>
    <mat-option value="General notifications">General notifications</mat-option>
    <mat-option value="Unread notifications">Unread notifications</mat-option>
    <mat-option value="Read notifications">Read notifications</mat-option>
  </mat-select>
</mat-form-field>

You selected: {{selected}}

<mat-card>These are the unread notifications</mat-card>
<mat-card>These are the read notifications</mat-card>
<mat-card>These are the general notifications</mat-card>

Controller
selected = 'General notifications';

A: One (non-elegant) way to do it would be to add *ngIf to each of your mat-cards like so:
<mat-card *ngIf="selected === 'General notifications'">These are the general notifications</mat-card>
<mat-card *ngIf="selected === 'Unread notifications'">These are the unread notifications</mat-card>
<mat-card *ngIf="selected === 'Read notifications'">These are the read notifications</mat-card>

However, a better way to do it I would say is have a member variable in your .ts file that is an object/map of key-value pairs. The keys will be option values (eg 'General notifications') and the values will contain your desired text for the selected option.
For example
notificationMap = {
  'General notifications': 'These are ...',
  'Unread notifications': 'These are...',
  'Read notifications': 'These are...',
}

Then in your .html you can simply do this:
<mat-card>{{notificationMap[selected]}}</mat-card>


text:
Q: Is it possible to get a regular value from state and not as Observable angular Ngrx? I'm wondering if I can get a regular value type from NGRX state and not an Observable?

A: Since the State class extends BehaviorSubject:
export class State<T> extends BehaviorSubject<any> implements OnDestroy { ... }

I think you can get the current state by injecting State and calling state.getValue().


text:
Q: How do I specify the Product Feed when using the Product Catalog Batch API for Facebook My question is about batch upload API for Product Catalogs. I'm doing a combination of daily batch API uploads and uploads through a CSV file. I'm starting to get conflicts because some products in the CSV have already been created via the batch upload API.

The part I'm interested in is this error message:

Another product with the same id was already uploaded to this catalog in No feed

It looks like the batch upload API creates a different product feed titled "No feed". I'd really like the batch API products to go to the same feed. Is there any way to specify the feed in the API request or at least inspect the "No feed"?
Thanks very much!


text:
Q: SAS lag function no identifying missing values I have this code where I want to identify lines with missing values and then replace a variable with the previous value of the variable (since that variable will always be blank too)
   DATA qfr_channel_split_FY16_SEPT1;
    set qfr_channel_split_FY16_SEPT;
    if order_count=. then do;
    avg_yr1_gm=lag1(avg_yr1_gm);
    avg_yr2_gm=lag1(avg_yr2_gm);
    avg_yr3_gm=lag1(avg_yr3_gm);
    avg_yr4_gm=lag1(avg_yr4_gm);
    avg_yr5_gm=lag1(avg_yr5_gm);
end;
    run;

It does nothing. It's not a problem with the =.
I have also tried outputting to a different variable name.
I suspect it's something lacking in my understanding of how the lag function works.
Anyone know why the above wouldn't work?

A: first define the lagged variable and then do the compare to missing and replace if so.
data want;
set have;

lagged=lag(var);

if var=. then var=lagged;

run;

A: I managed to answer this with the coalesce function
data zeroed (drop=&var. rename=(try=&var.));
set live_sorted;
orig=&var.;
try=coalesce(&var.,lag1(&var.),lag2(&var.),lag3(&var.),lag4(&var.));
run;

This automatically identifies whether a variable is blank and takes the nearest lag (up to 4 as I specified above)


text:
Q: Interpretation of p-values in a factor with multiple levels (summary.lm)

Here is a regression of a continuous response variable on a factor (religion) with 8 levels in R. I am wondering if any conclusions could be drawn from those p-values that are greater than $0.05$?
Aside
I remember that the p-values display in summary() for MLR are the t-test values, it only provides over and extra information when other variables are included. Even some variables have p-values that greater than $0.05$, it doesn't mean it's not useful in the model, to be more accurate, we need to have a sequential F-test to check the usefulness.
Q1 what about the p-values for different levels (not variables)? Can we conclude any levels is not important based on summary(), if not, what kind of test I need to have to say a specific level is not important, rather than this categorical variable?
Q2 If p-values $>0.05$ in summary() is not sufficient to say it's not an important variable, what about the p-values $<0.05$ in summary(), is this situation sufficient to say it's an important variable?
Q3 If the p-values in summary() cannot tell much in the MLR, why do we run summary() for the regression nearly every single time? What we can know from MLR summary() p-values?

A:
I am wondering if any information I could draw from those p-values that are greater than $0.05$?

Short answer: Just that they do not differ significantly from the intercept at $\alpha = 0.05$. Whether this information is useful depends on your research question.
F-test
The omnibus test you are describing is actually included in the output. It is the last p-value in the bottom right. If all group means were equal, there would be a $0.009\%$ of observing at least this large a difference.
Interpreting variable categories in the output (Q1)
If you run something like levels(survey$religion), you'll notice that one category is missing from the output. That category is placed in the intercept. After all, if you don't belong to any of the other groups, you must be the remaining group.
All the estimates and $p$-values of the other categories are a comparison to the reference group, or in other words, the group in the intercept. The estimate for Jewish isn't $2.1870$, it's $7.5361 + 2.1870$. Muslim differs significantly from the reference group. Etcetera.
If a category has a high $p$-value, that simply means it does not differ significantly from the reference group. The variable religion is added to your model, and if any of its categories differ sufficiently, then religion has a significant effect. If this is your research question, then all you need is the omnibus $F$-test.
Taking out categories (Q2)
You can't take out certain categories and leave others in. What you could do to achieve the same effect though, is to merge similar categories. Then again, this isn't a decision that you should make based on the $p$-values in the output, but rather at the start of the analysis (for example because two groups are theoretically similar and both quite small).
What is the point of the summary (Q3)
No one is forcing you to use summary. If all you want is the estimates, then coef(model) works fine too. But the summary includes other relevant information: Jewish has a large difference from the intercept, but then again, its standard error is also large. The $p$-value just gives you a simple guideline for the size of the estimate compared to its standard error.
Yes, religion has a significant effect, but a model with just this variable only explains a miniscule $2.6\%$ of the variance in the outcome variable (Multiple R-squared). Just looking at the coefficients, or their $p$-values alone would not have given you this information.
"Drinks" sounds like a count (see other comments) and is probably strongly right-skewed. You can see this by comparing the extrema and quartiles shown in the residuals tab.
Other comments

*

*If "drinks" is a count, you shouldn't be using normal linear regression, but instead a model for count data, like a Poisson or negative binomial GLM (glm(..., family = "poisson") or glm.nb(...), respectively).

*If you are interested in comparing other groups, you can change the reference group using relevel.

*If you are interested in more than one comparison, you should adjust for multiple testing.


text:
Q: How to completely remove MySQL from a windows 7 machine I'm new to MySQL struggling to find a version and workbench which works stably on my 64 bit windows 7 machine.
I've decided to attempt to completely remove MySQL from my machine and to restart the installation process from scratch.
However, after uninstalling all software linked with MySQL using conventional control panel uninstalling means some MySQL windows services still remain on my machine.
I can't see any obvious method to remove these and they have since been causing me difficulties when trying to install different versions of MySQL.
Could anyone please advise?

A: I've found a post on superuser which answers my question:
How to remove MySQL service from windows
To remove the MySQL service run the command prompt as admin then use the following command:
sc delete MySQL

Where MySQL is the title of the windows service.


text:
Q: Docker volume not available during execution Maybe this question has been asked before, although I didn't find the answer.
I'm using cozy-labs/cozy-docker and I'd like to let it save all the data on a mounted volume.
Actually, I tried putting my database folder in /var/lib/couchdb (as in /etc/couchdb/local.ini, there's no such option therefore this must be the default, right?) and mounting it in docker as follows:
docker run -d --name some-name -v /myData/:/var/lib/couchdb -p 4001:443 cozy/full

But the folder /myData on the host stays empty whereas in the docker, /var/lib/couchdb seems to contain the files it should. I verified this entering the container using docker exec -it some-name bash
What could I be misunderstanding?
And honestly, I don't think this is specific to cozy-docker

A: You need to be sure that on the both sides you have the same inode values.
docker run -d --name some-name -v /myData/:/var/lib/couchdb -p 4001:443 cozy/full
stat -c %i /myData
docker exec -it some-name stat -c %i /var/lib/couchdb

So what are these values? They should be equal, but if they differ, the content of the dirs will be differing to obviously.
I tested this image on Ubuntu 14.10, Docker 1.5 and I cannot reproduce that.


text:
Q: str.startsWith() not working on android phone I am using javascript's function .startsWith() for check if string starts with /assets
Code is
 var str = '/assets/image';
 if(str.startsWith('/assets')){alert('done');}

This works fine on pc , But not working on android phone , is .startsWith() has any compatibility issues on different browser or devices,and if yes ,then please tell me if any alternative for startsWith()
Thanks

A: startsWith is a pretty new addition to JavaScript and is not broadly supported on mobile browsers.
As basic alternative you can use
str.indexOf(strToFind) === 0

Or a polyfill presented on Mozilla Developer Network

A: According to MDN, startsWith() is not supported at android. You can alternatively use RegExp.prototype.test()
var str = '/assets/image';
if(/^\/assets/.test(str)){alert('done');}

A: Try this, it works good for me and give the same result.
var str = '/assets/image';
if(str.indexOf('/assets') === 0){alert('done');}


text:
Q: Angular JS, multiple insert error I want to fetch data from SQL and display in HTML table using ng-repeat option then I need to edit some values in the table cell. My problem is that I only get initial values in the controller and the changes are not reflected in the controller. Here is my code:
app.controller('CRUD_EntryController', function ($scope, CRUD_InternalEntryService) {

GetStudentMarkDetails();

function GetStudentMarkDetails() {
    var PromiseGetMarks = CRUD_InternalEntryService.GetMarkDetails();
    PromiseGetMarks.then(function (res) {
        $scope.MarkList = res.data;
    })

}
$scope.mark = {};
$scope.save = function (MarkList) {

    var index = 0;
    $scope.MarkList.forEach(function (mark) {
        console.log('rows #' + (index++) + ': ' + JSON.stringify(mark));
        alert(mark.M1);
    }

}

View:

            Slno
            Name
            RegNo
            ClassNo
            M1
            M2
            M3

            #{{$index+1}}
            {{mark.Fname}}
            {{mark.RegNo}}
            {{mark.ClassNo}}
            <input type="number" value="{{mark.M1}}" ng-model="M1" class="form-control" />
            <input type="number" value="{{mark.M2}}" ng-model="M2" class="form-control" />
            <input type="number" value="{{mark.M3}}" ng-model="M3" class="form-control" />

            <button data-ng-click="save(MarkList)" class="btn btn-success">Save</button>

A: Don't think you need to define this: $scope.mark = {}; since mark is set in the scope of your ng-repeat. Remove it because this is somewhat confusing and might cause errors in the future.
Remove the value="{{mark.M1}}" and bind your model to ng-model="{{mark.M1}}". Asuming that you wand to bind to M1, M2 and M3 in your inputs.
Also see the angular docs for ngModel for more details and update your code accordingly.
By the way you don't have to pass MarkList as an argument for Save(..), you can do this:
<button data-ng-click="save()" class="btn btn-success">Save</button>, change the Save method signature to Save() and use $scope.MarkList instead of the argument MarkList.
Or change your method to only save the specific mark instead of the entire list every time.


text:
Q: Setting the title of a MKPointAnnotation on creation when using MapKit So, at the moment I can't seem to figure out how the user can enter a title on the Annotation pins. In my code a pin will appear after a long press on the map, but the title shown of the pin is "Pin".
The only thing I would like to be able to do is for the user of the app to be able to create unique titles of the pins on creation.
import Foundation
import UIKit
import MapKit
class MapsViewController: UIViewController, CLLocationManagerDelegate {
let locationManager:CLLocationManager = CLLocationManager()

@IBOutlet weak var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    for currentLocation in locations{
        print("\(index) : \(currentLocation)")
    }
}

@IBAction func addPin(_ sender: UILongPressGestureRecognizer) {

    let alert = UIAlertController(title: "Title", message: "Please enter location name", preferredStyle: .alert)

    //2. Add the text field. You can configure it however you need.
    alert.addTextField { (textField) in
        textField.text = "Location name"
    }
    // 3. Grab the value from the text field, and print it when the user clicks OK.
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
        let textField = alert?.textFields![0] // Force unwrapping because we know it exists.
        print("Text field: \(String(describing: textField?.text))")
        DispatchQueue.main.async { self.addPinWithTitle (sender , title : textField?.text ?? "") }
    }))
    self.present(alert, animated: true, completion: nil)}

func addPinWithTitle(_ sender: UILongPressGestureRecognizer , title : String) {
    let location = sender.location(in: self.mapView)
    let locCoordinates = self.mapView.convert(location, toCoordinateFrom: self.mapView)

    let annotation = MKPointAnnotation()

    annotation.coordinate = locCoordinates
    annotation.title = title

    self.mapView.addAnnotation(annotation)}

}

A: Please follow the final code
@IBAction func addPin(_ sender: UILongPressGestureRecognizer) {

let alert = UIAlertController(title: "Title", message: "Please enter location name", preferredStyle: .alert)

//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
    textField.placeholder = "Location name"
}

// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
    let textField = alert?.textFields![0] // Force unwrapping because we know it exists.
    print("Text field: \(textField?.text)")
    DispatchQueue.main.async {
            self.addPinWithTitle (sender , title : textField?.text ?? "")
        }
}))
self.present(alert, animated: true, completion: nil)}

func addPinWithTitle(_ sender: UILongPressGestureRecognizer , title : String) {
let location = sender.location(in: self.mapView)
let locCoordinates = self.mapView.convert(location, toCoordinateFrom: self.mapView)

let annotation = MKPointAnnotation()

annotation.coordinate = locCoordinates
annotation.title = title

self.mapView.addAnnotation(annotation)}


text:
Q: Unable to upload pictures to the server in the same application that captured them Initially on clicking the camera button the image is being captured, displays the save and discard buttons. On clicking save it gets saved in the the specified folder, but the saved image is not being uploaded into the server.
Here is my code:
public class FldrActivity extends Activity {
    private static final int CAPTURE_IMAGE = 0;
    InputStream inputStream;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        File folder = new File(Environment.getExternalStorageDirectory() + "/image");
        boolean success = false;
        if (!folder.exists()) {
            success = folder.mkdir();
        }
        String path = folder + "/example.jpg";

        //String path = Environment.getExternalStorageDirectory() + "/image/example2.jpg";
        File file = new File(path);
        Uri outputFileUri = Uri.fromFile( file );
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
        intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );

        startActivityForResult( intent, CAPTURE_IMAGE );

        String pathToOurFile = "/sdcard/image/example.jpg";

        Bitmap bitmap = BitmapFactory.decodeFile(pathToOurFile);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);

        //compress to which format you want.
        byte [] byte_arr = stream.toByteArray();
        String image_str = Base64.encodeToString(byte_arr, 0);
        ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();

        nameValuePairs.add(new BasicNameValuePair("file",image_str));

        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.xyz.com/image/connection.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            String the_string_response = convertResponseToString(response);
            Toast.makeText(getApplicationContext(), "Response " + the_string_response,
                                Toast.LENGTH_LONG).show();
        } catch(Exception {
            Toast.makeText(getApplicationContext(), "ERROR " + e.getMessage(),
                                                  Toast.LENGTH_LONG).show();
            System.out.println("Error in http connection "+e.toString());
        }
    }

    public String convertResponseToString(HttpResponse response) throws  IllegalStateException, IOException {
        String res = "";
        StringBuffer buffer = new StringBuffer();
        inputStream = response.getEntity().getContent();
        int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
        Toast.makeText(getApplicationContext(), "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
        if (contentLength < 0) {
        }
        else {
            byte[] data = new byte[512];
            int len = 0;

            try {
                while (-1 != (len = inputStream.read(data)) ) {
                    buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                inputStream.close(); // closing the stream…..
            } catch (IOException e) {
                e.printStackTrace();
            }

            res = buffer.toString();     // converting stringbuffer to string…..

            Toast.makeText(getApplicationContext(), "Result : " + res, Toast.LENGTH_LONG).show();
            //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
        }

        return res;
    }
}


text:
Q: How do you add enum labels using sequelize? I have a table called characters. Each character has an enum called "state", which can be "sad" or "happy". How do I add a new state "confused" to my column? I tried this migration but it failed:
migration.describeTable('characters').success(function (attributes) {
    migration.changeColumn('characters', 'state',
        {
            type: DataTypes.ENUM,
            values: ['sad', 'happy', 'confused']
        })
        .complete(done);
});

It complained that error: type "enum_characters_state" already exists.

A: With the latest version of Sequelize, you could achieve this by running a query (Postgres assumed):
module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.sequelize.query("ALTER TYPE enum_character_state ADD VALUE 'confused';");
  }
};

A: create a migration with following script:
module.exports = {
  up  : function (queryInterface) {
    return queryInterface
      .changeColumn(tableName, columnName, {
        values: arrayOfNewValues
      });
  },
  down: function (queryInterface) {
    return queryInterface
      .changeColumn(tableName, columnName, {
        values: arrayOfOldValues
      });
  }
};

A: Expanding on briangonzalez answer, you will also need a down function to undo the migration:
'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.sequelize.query("ALTER TYPE enum_type_name ADD VALUE 'new_value'");
  },

  down: (queryInterface, Sequelize) => {
    var query = 'DELETE FROM pg_enum ' +
      'WHERE enumlabel = \'new_value\' ' +
      'AND enumtypid = ( SELECT oid FROM pg_type WHERE typname = \'enum_type_name\')';
    return queryInterface.sequelize.query(query);
  }
};

change enum_type_name and new_value to fit your needs.

A: You need to remove the type, if you want to re-add it. Useful in down migrations if nothing else.
queryInterface.sequelize.query('DROP TYPE enum_characters_state;')

A: I hope I am not late to the party..
this works for me
module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.sequelize.query(`
      ALTER TYPE "enum_type_name" ADD VALUE 'confused';
    `);
  },

  down: async(queryInterface, Sequelize) => {
    await queryInterface.sequelize.query(`
      ALTER TYPE "enum_type_name" DROP VALUE 'confused';
    `);
  }
};


text:
Q: Compass Rails 3.0 working with 'compass watch' but not without I'm trying Compass with Rails 3.0.7, just trying to get started. Using gem compass-rails. If I put my sass file in app/assets/stylesheets and run 'compass watch', everything works ok: the compiled css is put into public/stylesheets.
However, if I stop 'watch' and rely on Rails to do the compilation, it does not work. Instead, the program looks at the public/stylesheets/sass folder for the input. Furthermore, if a file in that folder has the '@include "compass"' directive, I get an error that the file is not found. How do I force Rails to look in the right place -- app/assets/stylesheets?


text:
Q: Recently added data on mysql not showing up after I call inner join I have this issue, I add an information to the database and it doesn't show up when I do an inner join on two of my tables until like after two mins of after adding the data. I can't seem to really figure out why thus is happening. Any help is appreciated. Thank you.
Here is a sample of what I am doing using node mysql
var currentTime = Date.now();
var pastOneDay  = currentTime - config.justADay;

var query       = "SELECT * FROM ?? INNER JOIN ?? ON ??=?? WHERE ??=? AND ?? < ? ORDER BY ?? + 0 LIMIT ?";
var table       = ["following", "posts", "following.followed_username", "posts.username", "following.username", usersname, "posts.initial_time_posted", pastOneDay, "posts.initial_time_posted", config.noOfPostsToSend];

query           = mysql.format(query, table);

connection.query(query, function(err, postsReturned) {
    if(err) {
        callback(true, null);
    } else {
        callback(false, postsReturned);
    }
});


text:
Q: Cannot find symbol constructor Scanner(java.lang.String[]) error? The main aim of this this program is to be able to read a request line from a browser and to print out the first two words of that specific request line. However when it comes to compiling the program i am getting the same error again and again and i am not sure what the issue is. Here is the sample of the code that i wrote:
import java.io.*;
import java.net.*;
import java.util.*;

public class UselessHTTPServer05 {
    public static void main(String args[]) throws Exception {
        int port = Integer.parseInt(args[0]);
        ServerSocket serverSock = new ServerSocket(port);

        while (true) {
            Socket conn = serverSock.accept();
            Scanner scanin = new Scanner(conn.getInputStream());
            String line = null;
            int nlines=0;
            String[] stringArray = new String[32];

            while (true) {
                line = scanin.nextLine();
                if (line.length() == 0)
                    break;
                stringArray [nlines] = line;
                nlines = nlines + 1;
                //System.out.println("line "+nlines+": " + line);

                for (int i = 0; i < nlines; i++)
                    System.out.println("Line: " + i + " " + stringArray[i]);

                Scanner scans = new Scanner(stringArray);
                String command = scans.next();
                String resource = scans.next();
                System.out.println("Command: " + command);
                System.out.println("Resource " + resource);
            }

            String reply="HTTP/1.0 404 Not Found\r\n" +
               "Connection: close\r\n" +
               "Content-Type: text/html\r\n" +
               "\r\n" +
               "
Sorry, work in progress
\r\n";

            OutputStream outs = conn.getOutputStream();
            outs.write(reply.getBytes());
            conn.close();
        }
    }
}

The error is in regards to the Scanner part of the code where I have declared a Scanner called "Scans" and have written the code to carry out the task of scanning through the request line and prining out the first two words stored in "command" and "resource".

A: String[] stringArray = new String[32];
...
Scanner scans = new Scanner(stringArray);

stringArray is of type String[], visit the Scanner API to verify there's no such  constructor available.

A: as you can see on the Scanner site. there is no Constructor for String[]. You need to do it a different way, for example,
write your own scanner class where you write your own constructor of scanner and extend it with the Scanner class.
Or you change your String array to a other type (maybe Inputstream)
third way: you could do it, i don't know if this works in java or just in C, you could make an array out of scanners where you call the constructor for each string in the string array
PseudoCode

foreach String in StringArray
  ArrayofScanners[i] = new Scanner(String);
  i++;

A: Found a solution! I have created a String variable to store the first request line from the server. I also delclared a new Scanner to read through the request line, exaple is shown below:
String string = stringArray[0] //this will read the first request line
Scanner scans = new Scanner(string) //this will scan through the request line stored in string

The next step is to store the first two words of the request line into two String variables called Command and Resource:
String Command = scans.next();
String Resource = scans.next();

Finally, simply print out the two words:
System.out.println("Command: " + Command);
System.out.println("Resource: " + Resource);

Before the above code is implented here is what the request line consists of:
Line: 0 GET /file.html HTTP/1.1

After implementing the above code, the first two words are printed and stored into Command and Resource:
Command: GET
Resource: /file.html

Thank you for all those that replied to the post, really helped a lot!


text:
Q: Coloring Dual of Euler Planar Graphs We are given an euler planar graph $G$.
What is the number of colors required $G^{*}$ where $G^{*}$ denotes the dual of graph $G$? Please provide the answer in terms of the number of faces, vertices or edges in the graph.
I read here that "A planar bipartite graph is dual to a planar Eulerian graph and vice versa.". So is the answer to the above problem 2? If yes, how do we prove it.


text:
Q: Please correct my @font-face CSS I am practically wetting myself at the prospect of getting this working!
I have set the location of the .ttf file - but it doesn't seem to pick it up.
Am I setting the location up wrong?
Am I describing the font incorrectly?
<!DOCTYPE html>

This is written in ITC Baskerville

Please note, that this is not written in Baskerville, but the word Waterman here is.

Read this for the W3C specifications on the "@font face" declaration which I've used to do this.

A: http://www.fontsquirrel.com/tools/webfont-generator use this generator to generate your font face. it will also provide the right css for the font.
one of the mistakes I see in your code is that your font-family is defined as Baskerville and p has font-familly baskerville (capitalize this)


text:
Q: Multiples of X from 1 to N The program accepts two integers (N, X) and prints all the multiples of X from 1 to N.
My code:
    N, X = [int(val) for val in input().split()]
    for ctr in range(X,N+1):
         print(ctr, end=" ")

Expected output:
20 2

2 4 6 8 10 12 14 16 18 20

Actual output:
20 2

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

A: N, X = [int(val) for val in input().split()]
for ctr in range(X, N+1, X):
     print(ctr, end=" ")

Add the step parameter to the range function.

A: Because range(X,N+1) gives you all the numbers starting at X up to and including N, you never filter out for the numbers divisible by x.
Here's an approach where you generate all the multiples by finding the quotient of N / x:
>>> def foo(n, x):
...     quotient = n // x
...     return [i*x for i in range(1, quotient + 1)]
...
>>> foo(20, 2)
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
>>> foo(13, 3)
[3, 6, 9, 12]

Note, Python's range allows you to do this with a step parameter almost trivially:
>>> n,x = 20, 2
>>> list(range(x, n+ 1, x))
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
>>> n,x = 13, 3
>>> list(range(x, n+ 1, x))
[3, 6, 9, 12]

A: N, X = [int(val) for val in input().split()]
for ctr in range(X,N+1):
     if ctr % X == 0:
         print(ctr, end=" ")

You can use the % (modulo) operator.
Basically, when you have a multiple of X, then the rest of the division of ctr by X is equal to 0.
That is what % checks for.

A: you are printing all numbers but what you want is all the multiples of x:
N, X = [int(val) for val in input().split()]
for ctr in range(1,N+1):
     print(X*ctr, end=" ")