text:
Q: RxJS 5 Timed Cache I am trying to get time expiry cache to work for an observable that abstracts a "request-response", using postMessage and message events on the window.
The remote window expects a message getItemList and replies to it with a message of type {type: 'itemList', data: []}.
I would like to model the itemList$ observable in such a way that it caches the last result for 3 seconds, so that no new requests are made during that time, however, I cannot think of a way to achieve that in an elegant (read, one observable – no subjects) and succint manner.
Here is the example in code:
const remote = someIframe.contentWindow;
const getPayload = message => message.data;
const ofType = type => message => message.type === type;

// all messages coming in from the remote iframe
const messages$ = Observable.fromEvent(window, 'message')
  .map(getPayload)
  .map(JSON.parse);

// the observable of (cached) items
const itemList$ = Observable.defer(() => {
    console.log('sending request');

    // sending a request here, should happen once every 3 seconds at most
    remote.postMessage('getItemList');

    // listening to remote messages with the type `itemList`
    return messages$
      .filter(ofType('itemList'))
      .map(getPayload);
  })
  .cache(1, 3000);

/**
 * Always returns a promise of the list of items
 * @returns {Promise<T>}
 */
function getItemList() {
  return itemList$
    .first()
    .toPromise();
}

// poll every second
setInterval(() => {
  getItemList()
    .then(response => console.log('got response', response));
}, 1000);

I am aware of the (very similar) question, but I am wondering if anyone can come up with a solution without explicit subjects.
Thank you in advance!

A: I believe you are looking for the rxjs operator throttle:
Documentation on rxjs github repo

Returns an Observable that emits only the first item emitted by the
  source Observable during sequential time windows of a specified
  duration.

Basically, if you would like to wait until the inputs have quieted for a certain period of time before taking action, you want to debounce.
If you do not want to wait at all, but do not wish to make more than 1 query within a specific amount of time, you will want to throttle. From your use case, I think you want to throttle


text:
Q: How to add image to navigation back button I have a backbutton image (backButton). How can I add it to the back button of the navigation bar?
UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"backButton"]
                                                                 style:UIBarButtonItemStylePlain target:nil action:nil];

viewController.navigationItem.backBarButtonItem = newBackButton;

[newBackButton release];

However, I am getting a weird looking button as seen below.

How can I replace the backbutton with the full black back button image?

A: You'll have to modify the black image's pixel size. Open up the image in any image editor, go to the adjust image size (it may be called something else in a different photo editor) find out the size and pixels. It looks like you'll have to make the thing 1 pixel taller and like 2 pixels wider, but I'm not sure. You can probably find some documentation on the exactly pixel size of the navigation button and work with that. Goodluck

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error in addWorksheet I'm trying to save data in an existing Excel sheet:
library(openxlsx)

wb <- createWorkbook("MyLink")
addWorksheet(wb, "Results 2018")

and I keep getting this error:

Error in createWorkbook("MyLink") :
  Unknown format MyLink

Friend of mine run the same thing on his computer and it works for him just fine.


text:
Q: C# Frozen ListBox (Windows Forms App) I'm making a simple BankingApp that keeps customers and their accounts in two separate list-boxes. When Selecting one customer in a list-box related accounts will be shown in the second list-box and the user should be able to add,remove, update customer and accounts. Whenever I try to add, remove or update a customer to the List-box it keeps locking to just one Item in the customer List-Box. The app doesn't  crash just freezes on that certain item. But I'm still able to choose another customer and see its information even if its already locked on another customer item.??
Any Ideas of what I am doing wrong in my code?
My butto for deleting customers: private void buttonTaBort_Click(object sender, EventArgs e) is not working and my button: private void buttonOkUppdatera_Click(object sender, EventArgs e) for updating customers is not working?
I know my code is a bit messy, I just started learning a couple of weeks ago :)Trying my best to get the hang of things.
[Serializable]
public partial class BankenAppen : Form
{
    List<Kund> KundLista = new List<Kund>();

    Kund aktuellKund = new Kund();

    Konto aktuelltKonto = new Konto();

    List<Konto> KontoLista = new List<Konto>();

    public BankenAppen()
    {

        InitializeComponent();

        FileStream fs = new FileStream("BankenAppenLista.bin", FileMode.OpenOrCreate, FileAccess.Read);
        BinaryFormatter bf = new BinaryFormatter();
        try
        {
            KundLista = (List<Kund>)bf.Deserialize(fs);
        }
        catch
        {
            MessageBox.Show("Tomt");
        }
        fs.Close();
        fs.Dispose();

        textBoxKontoNr.Enabled = false;
        textBoxSaldo.Enabled = false;
        textBoxRänta.Enabled = false;
        listBoxKunder.DataSource = KundLista;

    }

    public void EnableMetod()
    {
        textBoxFörNamn.Enabled = true;
        textBoxEfternamn.Enabled = true;
        textBoxPersonnummer.Enabled = true;
        textBoxGatuAdress.Enabled = true;
        textBoxTelefon.Enabled = true;
        textBoxMobil.Enabled = true;
    }

    public void DisableMetod()
    {
        textBoxFörNamn.Enabled = false;
        textBoxEfternamn.Enabled = false;
        textBoxPersonnummer.Enabled = false;
        textBoxGatuAdress.Enabled = false;
        textBoxTelefon.Enabled = false;
        textBoxMobil.Enabled = false;
    }

    public void ClearMetod()
    {
        textBoxFörNamn.Clear();
        textBoxEfternamn.Clear();
        textBoxPersonnummer.Clear();
        textBoxGatuAdress.Clear();
        textBoxTelefon.Clear();
        textBoxMobil.Clear();
    }

    public void SparaMetod()
    {
        FileStream fs = new FileStream("BankenAppenLista.bin", FileMode.OpenOrCreate, FileAccess.Write);
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(fs, KundLista);
        fs.Close();
    }
    private void Kunderna()
    {
        listBoxKunder.DataSource = null;
        listBoxKunder.Items.Clear();

            foreach (Kund kunder in KundLista)
        {
            listBoxKunder.Items.Add(kunder);
        }
    }
    private void Konton()
    {
        listBoxKonto.Items.Clear();

            foreach (Konto konton in aktuellKund.kontolista)
            {
                listBoxKonto.Items.Add(konton);
            }
    }
    private void Form1_Load(object sender, EventArgs e)
    {
    }

    private void buttonOkLäggTill_Click(object sender, EventArgs e)
    {
        listBoxKunder.DataSource = null;

        Kund Kunder = new Kund
        {
            Förnamn = textBoxFörNamn.Text,
            Efternamn = textBoxEfternamn.Text,
            Personnummer = textBoxPersonnummer.Text,
            GatuAdress = textBoxGatuAdress.Text,
            Telefon = textBoxTelefon.Text,
            Mobil = textBoxMobil.Text
        };

        KundLista.Add(Kunder);
        listBoxKunder.Items.Add(Kunder);

        listBoxKunder.DataSource = KundLista;

        SparaMetod();

        DisableMetod();
        ClearMetod();

    }
    private void buttonLäggTill_Click(object sender, EventArgs e)
    {
        EnableMetod();
        ClearMetod();
    }

    private void listBoxKunder_SelectedIndexChanged(object sender, EventArgs e)
    {
        aktuellKund = (Kund)listBoxKunder.SelectedItem;
        listBoxKunder.DataSource = KundLista;

        listBoxKonto.Items.Clear();

        foreach (Konto item in aktuellKund.kontolista)
        {
            listBoxKonto.Items.Add(item);
        }
        if(aktuellKund!= null)
        {
            textBoxFörNamn.Text = aktuellKund.Förnamn;
            textBoxEfternamn.Text = aktuellKund.Efternamn;
            textBoxPersonnummer.Text = aktuellKund.Personnummer;
            textBoxGatuAdress.Text = aktuellKund.GatuAdress;
            textBoxTelefon.Text = aktuellKund.Telefon;
            textBoxMobil.Text = aktuellKund.Mobil;
        }
     }

    private void buttonTaBort_Click(object sender, EventArgs e)
    {
        listBoxKunder.DataSource = null;
        listBoxKunder.Items.Clear();

        KundLista.Remove(aktuellKund);
        SparaMetod();

        Kunderna();
        ClearMetod();
        listBoxKunder.DataSource = KundLista;
    }

    private void buttonUppdatera_Click(object sender, EventArgs e)
    {
        EnableMetod();
        textBoxPersonnummer.Enabled = false;
    }

    private void buttonOkUppdatera_Click(object sender, EventArgs e)
    {
        aktuellKund.BytaAdress(textBoxFörNamn.Text, textBoxEfternamn.Text, textBoxGatuAdress.Text, textBoxTelefon.Text, textBoxMobil.Text);
        SparaMetod();
        Kunderna();
        DisableMetod();
    }

    private void buttonLäggTillKonto_Click(object sender, EventArgs e)
    {
        textBoxKontoNr.Enabled = true;
        textBoxSaldo.Enabled = true;
        textBoxRänta.Enabled = true;

        textBoxKontoNr.Clear();
        textBoxSaldo.Clear();
        textBoxRänta.Clear();

    }

    private void buttonOkÖppnaKonto_Click(object sender, EventArgs e)
    {
        listBoxKonto.DataSource = null;
        if (String.IsNullOrEmpty(textBoxKontoNr.Text) && String.IsNullOrEmpty(textBoxSaldo.Text) && String.IsNullOrEmpty(textBoxRänta.Text))
        {
            MessageBox.Show("Fyll i Kontouppgifter Tack!");
        }
        else
        {
            Konto nyttkonto;

            if (radioButtonPrivat.Checked)
            {
                Privat Pkonto = new Privat
                {
                    KontoNummer = textBoxKontoNr.Text,
                    Saldo = int.Parse(textBoxSaldo.Text),
                    Ränta = double.Parse(textBoxRänta.Text)
                };
                nyttkonto = Pkonto;
                textBoxKontoNr.Text = "";
                textBoxSaldo.Text = "";
                textBoxRänta.Text = "";

            }
            else if (radioButtonFramtid.Checked)
            {
                Framtid Fkonto = new Framtid
                {
                    KontoNummer = textBoxKontoNr.Text,
                    Saldo = int.Parse(textBoxSaldo.Text),
                    Ränta = double.Parse(textBoxRänta.Text)
                };
                nyttkonto = Fkonto;
            }
            else
            {
                Service Skonto = new Service
                {
                    KontoNummer = textBoxKontoNr.Text,
                    Saldo = int.Parse(textBoxSaldo.Text),
                    Ränta = double.Parse(textBoxRänta.Text)
                };
                nyttkonto = Skonto;
            }
            aktuellKund.ÖppnaKonto(nyttkonto);
            SparaMetod();
            Konton();
            textBoxKontoNr.Enabled = false;
            textBoxSaldo.Enabled = false;
            textBoxRänta.Enabled = false;
        }
    }

    private void listBoxKonto_SelectedIndexChanged(object sender, EventArgs e)
    {
        aktuelltKonto = (Konto)listBoxKonto.SelectedItem;
        if (aktuelltKonto != null)
        {
            textBoxKontoNr.Text = aktuelltKonto.KontoNummer;
            textBoxSaldo.Text = aktuelltKonto.Saldo.ToString();
            textBoxRänta.Text = aktuelltKonto.Ränta.ToString();
        }
    }
    private void buttonInUt_Click(object sender, EventArgs e)
    {
        int insättning = int.Parse(textBoxInsättning.Text);

        aktuelltKonto.Saldo = aktuelltKonto.Saldo + insättning;

        aktuelltKonto.Insättning(aktuelltKonto.Saldo);
        textBoxKontoNr.Text = aktuelltKonto.KontoNummer;
        textBoxSaldo.Text = aktuelltKonto.Saldo.ToString();
        textBoxRänta.Text = aktuelltKonto.Ränta.ToString();
        SparaMetod();
        textBoxInsättning.Clear();
    }

    private void buttonUttag_Click(object sender, EventArgs e)
    {
        int uttag = int.Parse(textBoxUttag.Text);
        aktuelltKonto.Saldo = aktuelltKonto.Saldo - uttag;
        aktuelltKonto.Insättning(aktuelltKonto.Saldo);
        textBoxKontoNr.Text = aktuelltKonto.KontoNummer;
        textBoxSaldo.Text = aktuelltKonto.Saldo.ToString();
        textBoxRänta.Text = aktuelltKonto.Ränta.ToString();
        SparaMetod();
        textBoxUttag.Clear();
    }

    private void buttonAvslutaKonto_Click(object sender, EventArgs e)
    {
        //listBoxKonto.DataSource = null;
        aktuelltKonto = (Konto)listBoxKonto.SelectedItem;

        KontoLista.Remove(aktuelltKonto);

       // listBoxKonto.DataSource = KontoLista;
        SparaMetod();
        Konton();
        textBoxKontoNr.Clear();
        textBoxRänta.Clear();
        textBoxSaldo.Clear();
    }
}

And my Customer Class
[Serializable]
class Kund
{
    //Properties

    public string Förnamn { get; set; }
    public string Efternamn { get; set; }
    public string Personnummer { get; set; }
    public string GatuAdress { get; set; }
    public string PostAdress { get; set; }
    public string Telefon { get; set; }
    public string Mobil { get; set; }

    public List<Konto> kontolista
    {
        get; set;
    }

    public Kund()
    {
        kontolista = new List<Konto>();
    }

    // Metoder

    public void BytaAdress(string nyttFörnamn, string nyttEfternamn, string nyGatuAdress, string nyTelefon, string nyMobil)
    {
        Förnamn = nyttFörnamn;
        Efternamn = nyttEfternamn;
        GatuAdress = nyGatuAdress;
        Telefon = nyTelefon;
        Mobil = nyMobil;
    }

    public void ÖppnaKonto(Konto nyttKonto)
    {
        kontolista.Add(nyttKonto);
    }

    public override string ToString()
    {
        return Förnamn + " " + Efternamn;
    }
}

A: See inline comments
 // assuming by the name this is only for the listBoxKunder
 // and every time the selected index changes, this method is invoked
 private void listBoxKunder_SelectedIndexChanged(object sender, EventArgs e)
{
    aktuellKund = (Kund)listBoxKunder.SelectedItem;

    // here you are changing the data source of the list box and this should/may cause
    // the selected index to change! This in turn calls this method again
    // To fix this, to not modify the DataSource property in respnse to a SelectedIndexChanged event
    listBoxKunder.DataSource = KundLista;

    listBoxKonto.Items.Clear();

    foreach (Konto item in aktuellKund.kontolista)
    {
        listBoxKonto.Items.Add(item);
    }
    if(aktuellKund!= null)
    {
        textBoxFörNamn.Text = aktuellKund.Förnamn;
        textBoxEfternamn.Text = aktuellKund.Efternamn;
        textBoxPersonnummer.Text = aktuellKund.Personnummer;
        textBoxGatuAdress.Text = aktuellKund.GatuAdress;
        textBoxTelefon.Text = aktuellKund.Telefon;
        textBoxMobil.Text = aktuellKund.Mobil;
    }
 }


text:
Q: Ckeditor set value to null after clear form ckeEditorCommonConfig: any
ckeEditorCommonCongiguration(): void {
this.ckeEditorCommonConfig = {
height: "100%",
extraPlugins: 'codeTag,kbdTag',
removePlugins: "exportpdf",
toolbar: [
{ name: 'styles', items: ['Styles', 'Format'] },
{
name: 'basicstyles', groups: ['basicstyles', 'cleanup'],
items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', 'RemoveFormat', 'Code']
},
{
name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi'],
items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote']
},
{ name: 'document', groups: ['mode', 'document', 'doctools'], items: ['Source'] },
],
toolbarGroups: [
{ name: 'styles' },
{ name: 'basicstyles', groups: ['basicstyles', 'cleanup'] },
{ name: 'document', groups: ['mode', 'document', 'doctools'] },
{ name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi'] },
],
removeButtons: "",
language: 'en',
forcePasteAsPlainText: false,
allowedContent: true,
extraAllowedContent: 'img',
}
}
In html file :
<ckeditor #ckeEditors [config]="ckeEditorCommonConfig" formControlName="comment" appEmptyToNull>

When I reset the form the value of ckediotr not set to null (this.commentForm.reset())
inside commentForm there is field called comment which is used to store ckeditor value.

A: You would probably have to "bind" a variable to the 'data' property:
<ckeditor [editor]="Editor" data="
Hello, world!
"></ckeditor>

In this example above, you would bind a variable like this:
<ckeditor [editor]="Editor" data="{{ myVariable }}"></ckeditor>

Then in the .ts file you declare a public myVariable and set it to null
public myVariable: string = null;


text:
Q: Merge and sum values and put them in an array I'm retrieving values from an external source and apply a foreach loop to the results, with the code below.
angular.forEach(data, function(value, key) {
    if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) {
        console.log(value.firstname + ' - ' + value.distance);
    } else {
        //do nothing
    }
});

The result is console for example can be:
kees - 103,4
marco - 44,1
jared - 89,8
kees - 66,2
jef - 23,3
marco - 69,4
I would like to combine all duplicate names and sum the numbers of the duplicates and put them in an array. So the result will be like this for example:
kees - 169,6
marco - 113,5
jared - 89.8
jef - 23.3
What is the best/easiest way to accomplish this?

A: You cannot store key-value pair in array.
Use object to store key-value pair.
See comments inline in the code.
var obj = {}; // Initialize the object

angular.forEach(data, function(value, key) {
    if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) {
        if (obj[value.firstname]) { // If already exists
            obj[value.firstname] += value.distance; // Add value to previous value
        } else {
            obj[firstname] = value.distance; // Add in object
        }
    } else {
        //do nothing
    }
});
console.log(obj); // Result

Shorter Version
var obj = {}; // Initialize the object

angular.forEach(data, function(value, key) {
    if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) {
        obj[value.firstname] = obj[value.firstname] ? obj[value.firstname] + value.distance : obj[value.firstname];
    } else {
        //do nothing
    }
});

A: Alternative way is to use Underscore:
 var data = [ {key: "kees", value:103.4},
             {key: "marco", value:44.1},
             {key: "jared", value:89.8},
             {key: "kees", value:66.2},
              {key: "marco", value:69.4},];

var groups = _(data).groupBy('key');

$scope.out = _(groups).map(function(gr, key) {
  return {
     type: key,
     val: _(gr).reduce(function(m,x) {
       return m + x.value;
     }, 0)
  };
});

Output:
[
  {
    "type": "kees",
    "val": 169.60000000000002
  },
  {
    "type": "marco",
    "val": 113.5
  },
  {
    "type": "jared",
    "val": 89.8
  }
]

demo in Fiddle


text:
Q: Breeze/Angular: TypeError: Converting circular structure to JSON First off, I'm new to breeze/angular...after reading some blogs and watching some pluralsight videos, I (like everybody else I guess) was so excited, but after a few weeks of trying, I started hating it because I'm running from one problem to the other. Is this technology still too early to learn and use?
Here is my data structure:
public class TshirtOrder
{
    public int Id { get; set; }
    public virtual Student Student { get; set; }
    public virtual ICollection<OrderItem> OrderItems { get; set; }
}

public class OrderItem
{
    public int Id { get; set; }
    [ForeignKey("Type")]
    public int TshirtTypeId { get; set; }
    public virtual TshirtType Type { get; set; }
    [ForeignKey("Size")]
    public int TshirtSizeId { get; set; }
    public virtual TshirtSize Size { get; set; }
    public double UnitPrice { get; set; }
    public int Quantity { get; set; }

    [ForeignKey("TshirtOrder")]
    public int TshirtOrderId { get; set; }
    public TshirtOrder TshirtOrder { get; set; }
}

This is related breeze datacontext.js:
function _createTshirtOrder() {
    var order = manager.createEntity("TshirtOrder");
    order.tshirtItems = [];
    order.tshirtItems.push(createOrderItem(lookups.tshirtTypes[0], lookups.tshirtSizes[0], 10));
    common.saveEntity(order);
    return order;

    function createOrderItem(type, size, unitPrice) {
        var item = manager.createEntity("OrderItem");
        item.type = type;
        item.size = size;
        item.unitPrice = unitPrice;
        item.quantity = 0;
        return item;
    }
}

When trying to save it at common.saveEntity(order), I got the error
Error: Error while interpolating: {{tshirtOrder.orderItems[0]}}
TypeError: Converting circular structure to JSON

The error complains about the circular structure, but I don't have any circular structure at all. In fact, the structure is very standard one and I had the almost same structure working a couple weeks earlier in another trial project. I'm not sure if the new libraries I'm using now has introduced some new defects.
I know this question has been asked, but I checked all answers and couldn't find my solution. The most relevant one is here, and this is the accepted solution:
var cache = [];
JSON.stringify(o, function(key, value) {
    if (typeof value === 'object' && value !== null) {
        if (cache.indexOf(value) !== -1) {
            // Circular reference found, discard key
            return;
        }
        // Store value in our collection
        cache.push(value);
    }
    return value;
});
cache = null; // Enable garbage collection

However, it doesn't work for me. As I debug through it, I realize (cache.indexOf(value) !== -1) is never true in my case.
Your help is much appreciated.
Update:
This is my saveEntity() method:
function _saveEntity(masterEntity) {
    // if nothing to save, return a resolved promise
    if (!manager.hasChanges()) { return $q(); }

    var description = describeSaveOperation(masterEntity);

    return manager.saveChanges().then(saveSucceeded).fail(saveFailed);

    function describeSaveOperation(entity) {
        var statename = entity.entityAspect.entityState.name.toLowerCase();
        var typeName = entity.entityType.shortName;
        var title = entity.title;
        title = title ? (" '" + title + "'") : "";
        return statename + " " + typeName + title;
    }

    function saveSucceeded() {
        logger.logInfo("saved " + description);
    }

    function saveFailed(error) {
        var msg = "Error saving " + description + ": " + getErrorMessage(error);

        masterEntity.errorMessage = msg;
        logger.logError(msg);
        // Let user see invalid value briefly before reverting
        $timeout(function () { manager.rejectChanges(); }, 1000);
        throw error; // so caller can see failure
    }

    function getErrorMessage(error) {
        var reason = error.message;
        if (reason.match(/validation error/i)) {
            reason = getValidationErrorMessage(error);
        }
        return reason;
    }

    function getValidationErrorMessage(error) {
        try { // return the first error message
            var firstItem = error.entitiesWithErrors[0];
            var firstError = firstItem.entityAspect.getValidationErrors()[0];
            return firstError.errorMessage;
        } catch (e) { // ignore problem extracting error message
            return "validation error";
        }
    }
}

Where manager is
var manager = new breeze.EntityManager("api/Breeze");

A: What is the code behind common.saveEntity(order)? Are you going thru the EntityManager.saveChanges method?


text:
Q: How to get URL hit by browser in C# application Actually, my requirement is, when a user type a URL in any browser like example.com?q=123 and hit go then my C# application will verify request and fetch the value of q.
any solution for this???

A: You will have to hook your application to somehow track all outgoing requests over port 80 and 443


text:
Q: Execute bash script via Node.js and include command line parameters I'm trying to execute a bash script from a Node application, which I have previously done successfully via:
var spawn = require('child_process').spawn;
spawn('bash', [pathToScript], {
    stdio: 'ignore',
    detached: true
}).unref();

It's important that I do it this way, because the script needs to continue to execute, even if/when the application is stopped.
Now, the script I need to execute requires an input value to be provided on the command line, ie.
./myScript.sh hello

But I cannot figure out how to pass this into the spawn call. I have tried the following, with no luck
var spawn = require('child_process').spawn;
spawn('bash', [pathToScript + '' + params], {
    stdio: 'ignore',
    detached: true
}).unref();

A: The second parameter in spawn is an array of arguments to pass to the command. So I think you almost have it but instead of concating the params to the path pass them in as an array:
var spawn = require('child_process').spawn;
var params = ['pathToScript','run', '-silent'];
spawn('bash', params, {
    stdio: 'ignore',
    detached: true
}).unref();


text:
Q: NetworkX: structuring a simple flow study on a graph If you consider the following graph:
from __future__ import division
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
from numpy.linalg import inv

G = nx.Graph()

pos={1:(2,3),2:(0,0),3:(6,0)}
G.add_nodes_from(pos.keys())
nx.set_node_attributes(G, 'coord', pos)

PE={1:0,2:60,3:40}
nx.set_node_attributes(G,'PE',PE)
q={1:100,2:0,3:0}
nx.set_node_attributes(G,'q',q)

G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(2,3)

import math
lengths={}
inv_lengths={}
for edge in G.edges():
    startnode=edge[0]
    endnode=edge[1]
    lengths[edge]=round(math.sqrt(((pos[endnode][1]-pos[startnode][1])**2)+
                                      ((pos[endnode][0]-pos[startnode][0])**2)),2)
    inv_lengths[edge]=round(1/lengths[edge],3)
nx.set_edge_attributes(G, 'length', lengths)
nx.set_edge_attributes(G, 'inv_length', inv_lengths)
nx.draw(G,pos,node_size=1000,node_color='r',with_labels=True)
nx.draw_networkx_edge_labels(G,pos)
plt.show()

And the following flow problem:

where 1 is a supply-only node and 2 and 3 are demand-only, how come that the following solution yields weird values of flow through each edge? It seems like q1=100 is not even considered, and I expect L2 to have flow=0.
m=nx.laplacian_matrix(G,weight='inv_length')
a=m.todense()

flow={}
res2=np.dot(a,b) #No inverse is required: x=ab
res2=[round(item,3) for sublist in res2.tolist() for item in sublist]
print res2
for i,e in enumerate(G.edges()):
   flow[e]=res2[i]

b=[]
for i,v in enumerate(PE.values()):
    b.append(v)
res2=np.dot(a,b) #No inverse is required: x=ab
res2=[round(item,3) for sublist in res2.tolist() for item in sublist]
print res2

#res2=[-24.62, 19.96, 4.66]

A: I have taken the liberty to compute edge lengths in a simpler way:
from scipy.spatial.distance import euclidean
lengths = {}
inv_lengths = {}
for edge in G.edges():
    startnode = edge[0]
    endnode = edge[1]
    d = euclidean(pos[startnode], pos[endnode])
    lengths[edge] = d
    inv_lengths[edge] = 1/d

And this is how I implemented the matrix equation   :
E = np.array([[0],
              [60],
              [40]], dtype=np.float64)

L1 = lengths[(1, 2)]
L2 = lengths[(2, 3)]
L3 = lengths[(1, 3)]

L = np.array([[1/L1 + 1/L3,       -1/L1,       -1/L3],
              [      -1/L1, 1/L1 + 1/L2,       -1/L2],
              [      -1/L3,       -1/L2, 1/L2 + 1/L3]], dtype=np.float64)

qLE = np.dot(L, E)

The code above yields the same result (approximately) than yours:
In [55]: np.set_printoptions(precision=2)

In [56]: qLE
Out[56]:
array([[-24.64],
       [ 19.97],
       [  4.67]])

In summary, I think this is not a programming issue. Perhaps you should revise the flow model...


text:
Q: How to get softKeyboard up on focus method in Android :PhoneGap? I am having one Html Page inside which I am having one textarea with id="txtMessage", Now on DOM ready method, I have put
$("#txtMessage").focus();
but the issue is when the page gets load, I do get the cursor on textarea, but keyboard doesn't showed up. But if again I tap on the textarea field, keyboard appears.
Can anybody please help me out?

A: Yes, it's know. You can work around this in android by writeing native java code as plugin to programaticaly show softkeyboard.  Here are few hints


text:
Q: Is there is way to importhtml table and skip repeat column headers? I am trying to import data from ESPN that is in a table format but the table repeats headers throughout the table and I want to skip them if possible.
http://www.espn.com/nhl/statistics/team/_/stat/scoring/year/2019/seasontype/2
I want it to just import this row once at the very top and not repeat! Is this possible?
RK  TEAM    GP  G   GA  GF/G    GA/G    DIFF    SF/G    SA/G    DIFF    SVPCT   PIM PIMA    DIFF

A: try:
=UNIQUE(IMPORTHTML("http://www.espn.com/nhl/statistics/team/_/stat/scoring/year/2019/seasontype/2",
 "table", 1))


text:
Q: How to pronounce "locale"? In computing, a locale is an identifier for a user's language or region.
As a non-native speaker, I somehow came to pronounce it low-kale, while it seems it's rather enunciated lo-kaal (avowing its French origin).
Unfortunately, I don't understand IPA differences, like between /ləʊˈkɑːl/ and /loʊˈkæl/; it looks like leu-kal and lou-kel to me.
Is lo-kaal how to exclusively pronounce "locale"? Is it rather British?
Is it entirely wrong to say low-kale? Or is this how it's used in the US?
Maybe there are distinctions in vocalization depending on meaning (computing, geography).

A: Oxford Dictionaries lists locale as /ləʊˈkɑːl/. You can click on the recording there. It sounds like "low karl", which is presumably the standard British pronunciation. That's how I pronounce it as a speaker of Australian English, which typically follows British pronunciation.
The American pronunciation of /loʊˈkæl/ is closer to the French pronunciation of /lɔkal/. That is, it's like "low cal" as in "low cal(orie) yogurt".

A: There is a tendancy for English speakers to pronounce foreign loan-words with unusual vowel or consonant sounds, in order to emphasis the exotic origin.
So many people will pronounce locale as "lo-KAAL", when lo-KAL" is arguably more correct as being closer to the original French.
My personal perception is that American English speakers make this error with French loanwords more often than British English speakers, while the opposite is true with Spanish, though this is may be confirmation bias on my part.

A: Just check out Youglish site. They have US/UK accent, as well as tags support.
Generic:
http://youglish.com/search/local
US version:
http://youglish.com/search/local/us
UK version:
http://youglish.com/search/local/uk
software related:
http://youglish.com/search/local%20%23software
Obama says it:
http://youglish.com/search/local%20%23obama
etc.

A: You have the right idea about the pronunciation for the most part. Any time you aren't sure about the pronunciation, you can go to YouTube and type in: How to pronounce WORD. It's quite often what I do when I'm sitting in the recording booth and I'm faced with a unfamiliar name or word.
For 'local' and 'locale', you can reference the following two YouTube links:
local
locale


text:
Q: Is a mongodb query with 1 indexed field faster than multiple indexed fields? In the following model a product is owned by a customer. and cannot be ordered by other customers. So I know that in an order by customer 1 there can only be products owned by customer one.
To give you an idea here is a simple version of the data model:
Orders:
{
  'customer' : 1
  'products' : [
  {'productId' : 'a'},
  {'productId' : 'b'}
  ]
}

Products:
{
  'id' : 'a'
  'name' : 'somename'
  'customer' : 1
}

I need to find orders that contain certain products. I know the product id and customer id. I'm free to add/change indexes on my database.
Now my question is. Is it faster to just add a single field index on the product id's and query only using that ID. Or should I go for a compound index with customer and product id?
I'm not sure if this matters, but in my real model the list of products is actually a list of objects which have an amount and a dbref to the product. And the customer is also a dbref.
Here is a full order object:
{
    "_id" : 0,
    "_class" : "nl.pfa.myprintforce.models.Order",
    "orderNumber" : "e35f1fa8-b4c4-4d53-89c9-66abe94a3553",
    "status" : "ERROR",
    "created" : ISODate("2017-03-30T11:50:50.292Z"),
    "finished" : false,
    "orderTime" : ISODate("2017-01-12T12:50:50.292Z"),
    "expectedDelivery" : ISODate("2017-03-30T11:50:50.292Z"),
    "totalItems" : 19,
    "orderItems" : [
        {
            "amount" : 4,
            "product" : {
                "$ref" : "product",
                "$id" : NumberLong(16)
            }
        },
        {
            "amount" : 7,
            "product" : {
                "$ref" : "product",
                "$id" : NumberLong(26)
            }
        },
        {
            "amount" : 8,
            "product" : {
                "$ref" : "product",
                "$id" : NumberLong(7)
            }
        }
    ],
    "stateList" : [
        {
            "timestamp" : ISODate("2017-03-28T11:50:50.074Z"),
            "status" : "NEW",
            "message" : ""
        },
        {
            "timestamp" : ISODate("2017-03-29T11:50:50.075Z"),
            "status" : "IN_PRODUCTION",
            "message" : ""
        },
        {
            "timestamp" : ISODate("2017-03-30T11:50:50.075Z"),
            "status" : "ERROR",
            "message" : "Something went wrong"
        }
    ],
    "customer" : {
        "$ref" : "customer",
        "$id" : ObjectId("58dcf11a71571a24c475c044")
    }
}

A: When I have the following indexes:
1: {"customer" : 1, "orderItems.product" : 1}
2: {"orderItems.product" : 1}

both count queries (I use count to forcefully find all documents without the network transfer):
a: db.getCollection('order').find({
'orderItems.product' : DBRef('product',113)
}).count()

b: db.getCollection('order').find({
'customer' : DBRef('customer',ObjectId("58de009671571a07540a51d5")),
'orderItems.product' : DBRef('product',113)
}).count()

Run with the same time of ~0.007 seconds on a set of 200k.
When I add 1000k record for a different customer (and different products) it does not effect the time at all.
an extended explain shows that:
query 1 just uses index 2.
query 2 uses index 2 but also considered index 1. Perhaps index intersection is used here?
Because if I drop index 1 the results are:
Query a: 0.007 seconds
Query b: 0.035 seconds (5x as long!)
So my conclusion is that with the right indexing both methods work about as fast. However, if you do not need the compound index for anything else it's just a waste of space & write speed.
So: single field index is better in my case.


text:
Q: Programming attiny45 chip and ir remote library I'm using the IR Remote library with an attiny45 chip. The codes works fine with an Arduino but getting error message when uploading to attiny45 chip.
#include <IRremote.h>

int RECV_PIN = 2;
int led = 1;
int relay = 0;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  irrecv.enableIRIn(); // Start the receiver
  pinMode (led, OUTPUT);
  pinMode (relay, OUTPUT);
}

void loop() {
  if (irrecv.decode(&results)) {

    switch (results.value) {
      case 0xff02fd :
        digitalWrite(led, HIGH);
        digitalWrite(relay, LOW);
        break;

        case 0x1FC42BD :
        digitalWrite(led, HIGH);
        digitalWrite(relay, LOW);
        break;

      default :
        digitalWrite(led, LOW);
        digitalWrite(relay, HIGH);
        break;
    }

    irrecv.resume(); // Receive the next value
  }
}

When uploading, i'm getting the following error messages :
    Arduino: 1.8.1 (Windows 7), Board: "ATtiny25/45/85, ATtiny45, Internal 8 MHz"
C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp: In member function 'void IRsend::mark(int)':

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:176:3: error: 'TCCR2A' was not declared in this scope

   TCCR2A |= _BV(COM2B1); // Enable pin 3 PWM output

   ^

In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\io.h:99:0,

                 from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\pgmspace.h:90,

                 from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:28,

                 from C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremoteInt.h:15,

                 from C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:13:

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:176:17: error: 'COM2B1' was not declared in this scope

   TCCR2A |= _BV(COM2B1); // Enable pin 3 PWM output

                 ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp: In member function 'void IRsend::space(int)':

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:188:3: error: 'TCCR2A' was not declared in this scope

   TCCR2A &= ~(_BV(COM2B1)); // Disable pin 3 PWM output

   ^

In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\io.h:99:0,

                 from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\pgmspace.h:90,

                 from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:28,

                 from C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremoteInt.h:15,

                 from C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:13:

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:188:19: error: 'COM2B1' was not declared in this scope

   TCCR2A &= ~(_BV(COM2B1)); // Disable pin 3 PWM output

                   ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp: In member function 'void IRsend::enableIROut(int)':

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:210:3: error: 'TIMSK2' was not declared in this scope

   TIMSK2 &= ~_BV(TOIE2); //Timer2 Overflow Interrupt

   ^

In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\io.h:99:0,

                 from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\pgmspace.h:90,

                 from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:28,

                 from C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremoteInt.h:15,

                 from C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:13:

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:210:18: error: 'TOIE2' was not declared in this scope

   TIMSK2 &= ~_BV(TOIE2); //Timer2 Overflow Interrupt

                  ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:228:3: error: 'TCCR2A' was not declared in this scope

   TCCR2A = _BV(WGM20);

   ^

In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\io.h:99:0,

                 from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\pgmspace.h:90,

                 from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:28,

                 from C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremoteInt.h:15,

                 from C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:13:

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:228:16: error: 'WGM20' was not declared in this scope

   TCCR2A = _BV(WGM20);

                ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:229:3: error: 'TCCR2B' was not declared in this scope

   TCCR2B = _BV(WGM22) | _BV(CS20);

   ^

In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\io.h:99:0,

                 from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\pgmspace.h:90,

                 from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:28,

                 from C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremoteInt.h:15,

                 from C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:13:

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:229:16: error: 'WGM22' was not declared in this scope

   TCCR2B = _BV(WGM22) | _BV(CS20);

                ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:229:29: error: 'CS20' was not declared in this scope

   TCCR2B = _BV(WGM22) | _BV(CS20);

                             ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:232:3: error: 'OCR2A' was not declared in this scope

   OCR2A = SYSCLOCK / 2 / khz / 1000;

   ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:233:3: error: 'OCR2B' was not declared in this scope

   OCR2B = OCR2A / 3; // 33% duty cycle

   ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp: In member function 'void IRrecv::enableIRIn()':

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:262:3: error: 'TCCR2A' was not declared in this scope

   TCCR2A = 0;  // normal mode

   ^

In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\io.h:99:0,

                 from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\pgmspace.h:90,

                 from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:28,

                 from C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremoteInt.h:15,

                 from C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:13:

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:267:7: error: 'TCCR2B' was not declared in this scope

   cbi(TCCR2B,CS22);

       ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:267:3: note: in expansion of macro 'cbi'

   cbi(TCCR2B,CS22);

   ^

Multiple libraries were found for "IRremote.h"
C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:267:14: error: 'CS22' was not declared in this scope

 Used: C:\Users\Acer\Documents\Arduino\libraries\IRremote
   cbi(TCCR2B,CS22);

 Not used: C:\Users\Acer\Documents\Arduino\libraries\IRremote1
              ^

 Not used: C:\Users\Acer\Documents\Arduino\libraries\Arduino-IRremote-master
C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:267:3: note: in expansion of macro 'cbi'

   cbi(TCCR2B,CS22);

   ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:268:14: error: 'CS21' was not declared in this scope

   sbi(TCCR2B,CS21);

              ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:268:3: note: in expansion of macro 'sbi'

   sbi(TCCR2B,CS21);

   ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:269:14: error: 'CS20' was not declared in this scope

   cbi(TCCR2B,CS20);

              ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:269:3: note: in expansion of macro 'cbi'

   cbi(TCCR2B,CS20);

   ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:272:7: error: 'TIMSK2' was not declared in this scope

   sbi(TIMSK2,TOIE2);

       ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:272:3: note: in expansion of macro 'sbi'

   sbi(TIMSK2,TOIE2);

   ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:272:14: error: 'TOIE2' was not declared in this scope

   sbi(TIMSK2,TOIE2);

              ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:272:3: note: in expansion of macro 'sbi'

   sbi(TIMSK2,TOIE2);

   ^

In file included from C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:13:0:

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremoteInt.h:46:24: error: 'TCNT2' was not declared in this scope

   #define RESET_TIMER2 TCNT2 = INIT_TIMER_COUNT2

                        ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:278:3: note: in expansion of macro 'RESET_TIMER2'

   RESET_TIMER2;

   ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp: In function 'void __vector_5()':

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremoteInt.h:46:24: error: 'TCNT2' was not declared in this scope

   #define RESET_TIMER2 TCNT2 = INIT_TIMER_COUNT2

                        ^

C:\Users\Acer\Documents\Arduino\libraries\IRremote\IRremote.cpp:308:3: note: in expansion of macro 'RESET_TIMER2'

   RESET_TIMER2;

   ^

exit status 1
Error compiling for board ATtiny25/45/85.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

This is the version of Arduino that i'm using :
    Arduino: 1.8.1 (Windows 7), Board: "ATtiny25/45/85, ATtiny45, Internal 8 MHz"

A: I am pretty sure this has problem has to be the fact when downloading to an attiny45 or any Arduino-like-chip you need to reset the chip as code is being downloaded. The reset pin is pin 1. To reset it you should ground the pin. Here is the pinout diagram for reference.


text:
Q: Spring boot build error after adding jpa depencency I am using parent dependency as
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

with JPA dependency I am getting following error:

ationConfigEmbeddedWebApplicationContext : Exception encountered
  during context initialization - cancelling refresh attempt:
  org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name 'dataSource' defined in class path
  resource
  [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]:
  Unsatisfied dependency expressed through method 'dataSource' parameter
  0; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name
  'spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties':
  Instantiation of bean failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate
  [org.springframework.boot.autoconfigure.jdbc.DataSourceProperties]:
  Constructor threw exception; nested exception is
  java.lang.NoClassDefFoundError:
  org/springframework/dao/DataAccessException

The error vanishes after I remove spring-boot-starter-data-jpa dependency the project builds from pom.xml the project compiles.
The project was working until today, but after a Java update I am getting this error.
UPDATE: I have only one hello restcontroller in the app which returns simple string
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>demo</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.apache.derby</groupId>
        <artifactId>derby</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

and error while starting app
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-01-15 11:28:36.148 ERROR 8764 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Unsatisfied dependency expressed through method 'dataSource' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.jdbc.DataSourceProperties]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/dao/DataAccessException
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1134) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1028) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at com.example.DemoApplication.main(DemoApplication.java:10) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.jdbc.DataSourceProperties]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/dao/DataAccessException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1116) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1060) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1136) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1064) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    ... 19 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.jdbc.DataSourceProperties]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/dao/DataAccessException
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1108) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    ... 31 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/springframework/dao/DataAccessException
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.<init>(DataSourceProperties.java:153) ~[spring-boot-autoconfigure-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_111]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_111]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_111]
    at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[na:1.8.0_111]
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    ... 33 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.springframework.dao.DataAccessException
    at java.net.URLClassLoader.findClass(Unknown Source) ~[na:1.8.0_111]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_111]
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[na:1.8.0_111]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_111]
    ... 39 common frames omitted

A: When you add spring-boot-starter-data-jpa, Spring Boot looks for datasource properties, so that it can connect to the database.
You need to add the following properties to application.properties (change values as per the DB configuration on your machine)
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

In case you want to test (or play around with) spring-data-jpa, use following in-memory database dependency in your pom.xml. In this case, you dont need to add any properties, Spring Boot will auto-configure it for you.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <scope>runtime</scope>
</dependency>

Documentation link

A: I solved the issue.
I deleted all repository from .m2 folder (c:/users/{USER}/.m2/repository)
then rebuild workspace... it works


text:
Q: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings] if (ser.find("Error")){ I am trying to use Arduino IDE to detect temperature and pulse rate using LM35 sensor and pulse sensor.
This is the code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#include <SoftwareSerial.h>
float pulse = 0;
float temp = 0;
SoftwareSerial ser(9,10);
String apiKey = "MVLG8S8L6138FCR4";

// Variables
int pulsePin = A0; // Pulse Sensor purple wire connected to analog pin 0
int blinkPin = 7 ; // pin to blink led at each beat
int fadePin = 13; // pin to do fancy classy fading blink at each beat
int fadeRate = 0; // used to fade LED on with PWM on fadePin

// Volatile Variables, used in the interrupt service routine!

volatile int BPM; // int that holds raw Analog in 0. updated every 2mS
volatile int Signal; // holds the incoming raw data
volatile int IBI = 600; // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false; // "True" when User's live heartbeat is detected. "False" when nota "live beat".
volatile boolean QS = false; // becomes true when Arduoino finds a beat.

// Regards Serial OutPut -- Set This Up to your needs
static boolean serialVisual = true; // Set to 'false' by Default. Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse
volatile int rate[10]; // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0; // used to determine pulse timing
volatile unsigned long lastBeatTime = 0; // used to find IBI
volatile int P = 512; // used to find peak in pulse wave, seeded
volatile int T = 512; // used to find trough in pulse wave, seeded
volatile int thresh = 525; // used to find instant moment of heart beat, seeded
volatile int amp = 100; // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true; // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false; // used to seed rate array so we startup with reasonable BPM

void setup()
{
lcd.begin(16, 2);
pinMode(blinkPin,OUTPUT); // pin that will blink to your heartbeat!
pinMode(fadePin,OUTPUT); // pin that will fade to your heartbeat!
Serial.begin(115200); // we agree to talk fast!
interruptSetup(); // sets up to read Pulse Sensor signal every 2mS

// IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,

// UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN

// analogReference(EXTERNAL);

lcd.clear();
lcd.setCursor(0,0);
lcd.print(" Patient Health");
lcd.setCursor(0,1);
lcd.print(" Monitoring ");
delay(4000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Initializing....");
delay(5000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Getting Data....");
ser.begin(9600);
ser.println("AT");
delay(1000);
ser.println("AT+GMR");
delay(1000);
ser.println("AT+CWMODE=3");
delay(1000);
ser.println("AT+RST");
delay(5000);
ser.println("AT+CIPMUX=1");
delay(1000);

String cmd="AT+CWJAP=\"Alexahome\",\"98765432\"";
ser.println(cmd);
delay(1000);
ser.println("AT+CIFSR");
delay(1000);
}

// Where the Magic Happens
void loop()
{
serialOutput();
if (QS == true) // A Heartbeat Was Found
{

// BPM and IBI have been Determined
// Quantified Self "QS" true when arduino finds a heartbeat
fadeRate = 255; // Makes the LED Fade Effect Happen, Set 'fadeRate' Variable to 255 to fade LED with pulse
serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.
QS = false; // reset the Quantified Self flag for next time
}
ledFadeToBeat(); // Makes the LED Fade Effect Happen
delay(20); // take a break
read_temp();
esp_8266();
}
void ledFadeToBeat()
{
fadeRate -= 15; // set LED fade value
fadeRate = constrain(fadeRate,0,255); // keep LED fade value from going into negative numbers!
analogWrite(fadePin,fadeRate); // fade LED
}
void interruptSetup()
{
// Initializes Timer2 to throw an interrupt every 2mS.
TCCR2A = 0x02; // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
TCCR2B = 0x06; // DON'T FORCE COMPARE, 256 PRESCALER
OCR2A = 0X7C; // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
TIMSK2 = 0x02; // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
sei(); // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}
void serialOutput()
{ // Decide How To Output Serial.
if (serialVisual == true)
{
arduinoSerialMonitorVisual('-', Signal); // goes to function that makes Serial Monitor Visualizer
}
else
{
sendDataToSerial('S', Signal); // goes to sendDataToSerial function
}
}
void serialOutputWhenBeatHappens()
{
if (serialVisual == true) // Code to Make the Serial Monitor Visualizer Work
{
Serial.print("*** Heart-Beat Happened *** "); //ASCII Art Madness
Serial.print("BPM: ");
Serial.println(BPM);
}
else
{
sendDataToSerial('B',BPM); // send heart rate with a 'B' prefix
sendDataToSerial('Q',IBI); // send time between beats with a 'Q' prefix
}
}
void arduinoSerialMonitorVisual(char symbol, int data )
{
const int sensorMin = 0; // sensor minimum, discovered through experiment
const int sensorMax = 1024; // sensor maximum, discovered through experiment
int sensorReading = data; // map the sensor range to a range of 12 options:
int range = map(sensorReading, sensorMin, sensorMax, 0, 11);
// do something different depending on the
// range value:
switch (range)
{
case 0:
Serial.println(""); /////ASCII Art Madness
break;
case 1:
Serial.println("---");
break;
case 2:
Serial.println("------");
break;
case 3:
Serial.println("---------");
break;
case 4:
Serial.println("------------");
break;
case 5:
Serial.println("--------------|-");
break;
case 6:
Serial.println("--------------|---");
break;
case 7:
Serial.println("--------------|-------");
break;
case 8:
Serial.println("--------------|----------");
break;
case 9:
Serial.println("--------------|----------------");
break;
case 10:
Serial.println("--------------|-------------------");
break;
case 11:
Serial.println("--------------|-----------------------");
break;
}
}

void sendDataToSerial(char symbol, int data )
{
Serial.print(symbol);
Serial.println(data);
}
ISR(TIMER2_COMPA_vect) //triggered when Timer2 counts to 124
{
cli(); // disable interrupts while we do this
Signal = analogRead(pulsePin); // read the Pulse Sensor
sampleCounter += 2; // keep track of the time in mS with this variable
int N = sampleCounter - lastBeatTime; // monitor the time since the last beat to avoid noise
// find the peak and trough of the pulse wave

if(Signal < thresh && N > (IBI/5)*3) // avoid dichrotic noise by waiting 3/5 of last IBI
{
if (Signal < T) // T is the trough
{
T = Signal; // keep track of lowest point in pulse wave
}
}
if(Signal > thresh && Signal > P)
{ // thresh condition helps avoid noise
P = Signal; // P is the peak
} // keep track of highest point in pulse wave
// NOW IT'S TIME TO LOOK FOR THE HEART BEAT
// signal surges up in value every time there is a pulse
if (N > 250)
{ // avoid high frequency noise
if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) )
{
Pulse = true; // set the Pulse flag when we think there is a pulse
digitalWrite(blinkPin,HIGH); // turn on pin 13 LED
IBI = sampleCounter - lastBeatTime; // measure time between beats in mS
lastBeatTime = sampleCounter; // keep track of time for next pulse

if(secondBeat)
{ // if this is the second beat, if secondBeat == TRUE
secondBeat = false; // clear secondBeat flag
for(int i=0; i<=9; i++) // seed the running total to get a realisitic BPM at startup
{
rate[i] = IBI;
}
}
if(firstBeat) // if it's the first time we found a beat, if firstBeat == TRUE
{
firstBeat = false; // clear firstBeat flag
secondBeat = true; // set the second beat flag
sei(); // enable interrupts again
return; // IBI value is unreliable so discard it
}
// keep a running total of the last 10 IBI values
word runningTotal = 0; // clear the runningTotal variable
for(int i=0; i<=8; i++)
{ // shift data in the rate array
rate[i] = rate[i+1]; // and drop the oldest IBI value
runningTotal += rate[i]; // add up the 9 oldest IBI values
}
rate[9] = IBI; // add the latest IBI to the rate array
runningTotal += rate[9]; // add the latest IBI to runningTotal
runningTotal /= 10; // average the last 10 IBI values
BPM = 60000/runningTotal; // how many beats can fit into a minute? that's BPM!
QS = true; // set Quantified Self flag
// QS FLAG IS NOT CLEARED INSIDE THIS ISR
pulse = BPM;
}
}
if (Signal < thresh && Pulse == true)
{ // when the values are going down, the beat is over
digitalWrite(blinkPin,LOW); // turn off pin 13 LED
Pulse = false; // reset the Pulse flag so we can do it again
amp = P - T; // get amplitude of the pulse wave
thresh = amp/2 + T; // set thresh at 50% of the amplitude
P = thresh; // reset these for next time
T = thresh;
}
if (N > 2500)
{ // if 2.5 seconds go by without a beat
thresh = 512; // set thresh default
P = 512; // set P default
T = 512; // set T default
lastBeatTime = sampleCounter; // bring the lastBeatTime up to date
firstBeat = true; // set these to avoid noise
secondBeat = false; // when we get the heartbeat back
}
sei(); // enable interrupts when youre done!
}// end isr
void esp_8266()
{
// TCP connection AT+CIPSTART=4,"TCP","184.106.153.149",80
String cmd = "AT+CIPSTART=4,\"TCP\",\"";
cmd += "184.106.153.149"; // api.thingspeak.com
cmd += "\",80";
ser.println(cmd);
Serial.println(cmd);
if (ser.find("Error")){
  Serial.println("AT+CIPSTART error");
  return;
}
String getStr = "GET /update?api_key=";
getStr += apiKey;
getStr +="&field1=";
getStr +=String(pulse);
getStr +="&field2=";
getStr +=String(temp);
getStr += "\r\n\r\n";
// send data length
cmd = "AT+CIPSEND=4,";
cmd += String(getStr.length());
ser.println(cmd);
Serial.println(cmd);
delay(1000);
ser.print(getStr);
Serial.println(getStr); //thingspeak needs 15 sec delay between updates
delay(3000);
}
void read_temp()
{
int temp_val = analogRead(A1);
float mv = (temp_val/1024.0)*5000;
float cel = mv/10;
temp = (cel*9)/5 + 32;
Serial.print("Temperature:");
Serial.println(temp);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("BPM :");
lcd.setCursor(7,0);
lcd.print(BPM);
lcd.setCursor(0,1);
lcd.print("Temp.:");
lcd.setCursor(7,1);
lcd.print(temp);
lcd.setCursor(13,1);
lcd.print("F");
}

This is the error:
C:\Users\vaadh\OneDrive\Documents\Arduino\testing_LED_blinking\testing_LED_blinking.ino: In function 'void esp_8266()':
C:\Users\vaadh\OneDrive\Documents\Arduino\testing_LED_blinking\testing_LED_blinking.ino:282:21: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
 if (ser.find("Error")){

A: It is a problem of the Arduino core Stream class's find method. The type of the parameter should be const char* but it is char*.
Cast the parameter to char* to indicate to the compiler that it is OK.
ser.find((char*) "Error")


text:
Q: Existentialism today My friend asked me, "What is an existential threat? How is the word "existential" being used? Can't be the way it was used back when everybody was reading Camus and quoting Sartre. I wonder if the word could just be omitted? Isn't a threat a threat?"
I'm curious about this and the possible ways the meaning of existentialism has changed over the decades.
I am new to this group so I hope I haven't broken any rules. I looked at the "Similar Questions" and didn't see one that is similar.

A: "Existential" means "of or relating to existence," so an "existential threat" is one that threatens the very existence of an entity. For instance, one might say:

the proliferation of nuclear weapons poses an existential threat to the human race [because it threatens their very existence].

"Existentialism" is a branch of philosophy that is concerned with the "analysis of human existence," to quote from the OED.

A philosophical movement or approach which focuses on the analysis of human existence and on individual human beings as agents freely determining by their choices what they will become. Also sometimes applied to other philosophies which lay particular stress on existence as distinct from essence.

So while they share the same root, the two words here might not be as related as you're assuming.
It's worth noting that the adjectival form of "existentialism" is actually "existentialist," not "existential."  So the phrase,

An existentialist threat

...would mean a threat related to the philosophy or practice of existentialism, and it would indeed be a strange turn of phrase.

Source: Oxford English Dictionary


text:
Q: Converting index of one dimensional array into two dimensional array i. e. row and column I have one application of WinForms which inside list box I am inserting name and price..name and price are stored in two dimensional array respectively. Now when I select one record from the listbox it gives me only one index from which I can get the string name and price to update that record I have to change name and price at that index for this I want to update both two dimensional array name and price. but the selected index is only one dimensional. I want to convert that index into row and column. How to do that?
But I'm inserting record in list box like this.
int row = 6, column = 10;
for(int i=0;i<row;i++)
{
    for(int j=0;j<column;j++)
    {
        value= row+" \t "+ column +" \t "+ name[i, j]+" \t " +price[i, j];
        listbox.items.add(value);
    }
}

A: While I didn't fully understand the exact scenario, the common way to translate between 1D and 2D coordinates is:
From 2D to 1D:
index = x + (y * width)

or
index = y + (x * height)

depending on whether you read from left to right or top to bottom.
From 1D to 2D:
x = index % width
y = index / width

or
x = index / height
y = index % height

A: Try this,
int i = OneDimensionIndex%NbColumn
int j = OneDimensionIndex/NbRow //Care here you have to take the integer part

A: Well, if I understand you correctly, in your case, obviously the index of the ListBox entry's array entry is the index in the ListBox. The name and price are then at index 0 and index 1 of that array element.
Example:
string[][] namesAndPrices = ...;

// To fill the list with entries like "Name: 123.45"
foreach (string[] nameAndPrice in namesAndPrices)
   listBox1.Items.Add(String.Format("{0}: {1}", nameAndPrice[0], nameAndPrice[1]));

// To get the array and the name and price, it's enough to use the index
string[] selectedArray = namesAndPrices[listBox1.SelectedIndex];
string theName = selectedArray[0];
string thePrice = selectedArray[1];

If you have an array like that:
string[] namesAndPrices = new string[] { "Hello", "123", "World", "234" };

Things are different. In that case, the indices are
int indexOfName = listBox1.SelectedIndex * 2;
int indexOfPrice = listBox1.SelectedIndex * 2 + 1;


text:
Q: Get All Custom Taxonomy Images of Terms I have a custom taxonomy with 500+ terms is "dtcast"
I using this plugin for custom taxonomy images terms : Advanced Category and Custom Taxonomy Image
Now, I use this script to get list of all terms
<?php
$tax = 'dtcast'; // your taxonomy name

// get the terms of taxonomy
$terms = get_terms( $tax, [
    'hide_empty' => false, // do not hide empty terms
]);

// loop through all terms
foreach( $terms as $term ) {
    // display link to the term archive
    echo ''. $term->name .'';
}
?>

It's work ok !
But i want to get images of terms.
Please help me to get it.

A: Can you try:
$image = get_taxonomy_image( $term->term_id );


text:
Q: i try if statement javascript for form values but dosn't work? i need make if statement for form values to showing red notifications message if no or green message if yes
all form fields combobox except 2 fileds textbox
i need calculate this 2 textbox values = 12
so if all no + total values for text boxs = 12
showing green txt notifcation
else showing red txt notifcation
    <form name="ACV" method="post" action="mailto:yourname@mail.com?subject=ACV" enctype="multipart/form-data" id="Form1" onsubmit="return submitACV()">
<select name="Combobox1" size="1" id="Combobox1" style="position:absolute;left:33px;top:115px;width:200px;height:28px;z-index:0;">
<option value="No">NO</option>
<option value="yes">YES</option>
</select>
<select name="Combobox2" size="1" id="Combobox2" style="position:absolute;left:33px;top:148px;width:200px;height:28px;z-index:1;">
<option value="No">NO</option>
<option value="yes">YES</option>
</select>
<input type="text" id="Editbox1" style="position:absolute;left:47px;top:248px;width:62px;height:16px;z-index:4;" name="Editbox1" value="" spellcheck="false">
<input type="text" id="Editbox2" style="position:absolute;left:161px;top:248px;width:62px;height:16px;z-index:5;" name="Editbox1" value="" spellcheck="false">
<input type="submit" id="Button1" name="" value="Submit" style="position:absolute;left:97px;top:310px;width:126px;height:21px;z-index:19;">
</form>

<script>
    function Button1 () {

        var text001;
        var answer1 = Combobox1.value
        var answer2 = Combobox2.value
        var answer3 = Combobox3.value
        var answer4 = Combobox4.value
        if (answer1 == "no");
if (answer2 == "no");
if (answer3 == "no");
if (answer4 == "no");
{

            text001 ="right !!";
            else
                text001 ="try again !!";
        }

    }

    </script>


text:
Q: Find the equation of circle with given equation of chords and its length Question: Line $l_1:2x-3y+2=0$ and $l_2:3x-2y+3=0$ is the chord of circle with length $26$ and $24$ units respectively. Find the equation of circle.
Is the solution unique? If not unique, what is the general form of the solution?
My attempt so far: Let circle to have radius $r$ and center $C(h,k)$ and apply Pythagoras theorem. So I have two equations $\sqrt{r^2-13^2}=\frac{|2h-3k+2|}{\sqrt{2^2+(-3)^2}}$ and $\sqrt{r^2-12^2}=\frac{|3h-2k+3|}{\sqrt{3^2+(-2)^2}}$. Eliminating the $r$ and I obtain the locus of $C$ which is a hyperbola $(h+1)^2-k^2=65$.


text:
Q: Spectral radius inequality for normal matrices. I've read in several places now that $\rho(AB) \leq \rho(A)\rho(B)$ holds if the matrices are normal. I've scoured the web for a proof since I can't seem to get there myself. How would one go about to prove this statement? Links to proof is also welcome.

A: Note that for any matrix, the induced 2-norm of that matrix is defined as $$\|A\|_2:=\sup_{x\neq0}\frac{\|Ax\|_2}{\|x\|_2},$$ and thus by the spectral theorem for normal matrices, there exists a basis of eigenvectors of $A$ for $\mathbb{C}^{n\times n}$, and thus $\|A\|_2=\rho(A)$. Similarly $\|B\|_2=\rho(B)$. For $AB$, which is not necessarily normal, we hace $\|AB\|_2=\sigma_{\mathrm{max}}(AB)$, the maximal singular value of $AB$, see also this post.
Now using this, we can see directly that $$\rho(AB)\leq\sigma_{\mathrm{max}}(AB)=\|AB\|_2\leq\|A\|_2\|B\|_2=\rho(A)\rho(B),$$ where the second inequality holds because the induced $2$-norm $\|\cdot\|$ is indeed a norm.
For the first inequality, observe that for any induced matrix $p$-norm, we have  for any $v\in\mathbb{C}^n$, and therefore also for $v$ the eigenvector with norm $1$ corresponding to $|\lambda|=\rho(A)$: $$\|A\|_p:=\sup_{x\neq0}\frac{\|Ax\|_p}{\|x\|_p}=\sup_{\|x\|_p=1}\|Ax\|_p\geq\|Av\|_p=\|\lambda v\|_p=\rho(A)\|v\|_p=\rho(A).$$


text:
Q: Some CSS Class selectors don't work in React I'm working on some basic styling for my personal project, and for some reason, most of the class selectors in my css file Header.css works, except headerOptionCount. Earlier, some other classes weren't working, but putting Header.css in a styles directory seemed to help, but now it is happening again. When changing margin-left and margin-right of headerOptionCount, nothing changes. When inspecting the element in dev tools, the styles dont show up at all.
Header.css:
.header {
    height: 60px;
    display: flex;
    align-items: center;
    background-color: #131921;
    position: sticky;
    top: 0;
    z-index: 100;
}

.headerLogo {
    width: 60px;
    object-fit: contain;
    margin: 0 10px;
}

.headerSearch {
    display: flex;
    flex: 1;
    align-items: center;
    border-radius: 24px;
}

.headerSearchInput {
    width: 100%;
    height: 12px;
    padding: 10px;
    border: none;
}

.headerSearchIcon {
    padding: 5px;
    height: 22px !important;
    background-color: tomato;
}

.headerOptionLineOne {
    font-size: 10px;
}

.headerOptionLineTwo {
    font-size: 13px;
    font-weight: 800;
}

.headerOptionBasket {
    display: flex;
    align-items: center;
    color: white;
}

.headerOptionCount {
    margin-left: 10px;
    margin-right: 10px;
}

.headerNav {
    display: flex;
    justify-content: space-evenly;
}

.headerOption {
    display: flex;
    flex-direction: column;
    margin-left: 10px;
    margin-right: 10px;
    color: white;
}

Here is my Header component that imports this css file.
Header.js:
import React from "react";
import logo from "../zipshopIcon.png";
import { Search, ShoppingCart } from "@material-ui/icons";
import "../styles/Header.css";

const Header = () => {
    return (

                <input className="headerSearchInput" type="text" />
                {/* Logo */}
                <Search className="headerSearchIcon" />

                    Hello Guest
                    Sign In

                    Returns
                    & Orders

                    Your
                    Prime

                    <ShoppingCart />
                    0

    );
};

export default Header;

The import directory is definitely correct since the other styles work. I've tried using css modules, but it didnt fix anything. Should i try using scss? it just baffles me why class selectors cant even work when imported as css files. Any advice would be appreciated, thanks!

A: None of your elements in the js have the classname headerOptionCount, you need to give the element you want to have those styles the classname for it to work.


text:
Q: Which Unicode symbols are allowed as operators in PureScript? I'm trying to define ¡¡ (two inverted exclamation marks) as an operator in PureScript, but the compiler complains about an unexpected '¡' character. My definition looks like so:
infixl 8 functionName as ¡¡

The equivalent definition works fine in Haskell, so PureScript's rules about which Unicode characters are allowed must be different, but I can't find them specified anywhere. I thought it might depend on the Unicode category, but '¡' falls in Other Punctuation, which is a mix of allowed and disallowed characters.


text:
Q: How to include Jars and aars in Android.bp file? Java In the Aosp module there we can see some prebuilt jars like annotations.jar.
I need to import them in my project using BP file.
Please help me to do that.....
Thanks in advance!!

A: Use java_import for jar and android_library_import for aar in .bp files.
Example
android_app {
  static_libs :[
    "lib1"
    "lib2"
  ],
}
android_library_import {
 name: "lib1"
 aars: ["libs/lib1.aar"],
}
java_import {
  name: "lib2"
  jars: [libs/lib2.jar",
}


text:
Q: MySQL Seperator Error I've been trying to use the SEPERATOR function on a SQL query but it gives me a syntax error, why?
SELECT e.*, GROUP_CONCAT(mgl.genre_title, mgl.genre_id SEPERATOR "-") AS genres FROM events e
LEFT JOIN music_genres_link mgl ON e.id = mgl.event_id
WHERE e.id = 1
GROUP BY e.id

I simply wish for it to do:
55-Electronic, 23-Trance
Instead of:
55Electronic, 23Trance

A: I suspect the syntax error is because you have misspelled it. You need SEPARATOR.

A: Group concat don't need comma between columns ..
if you need  group_concat for concat values the you should use concat inside the grou_concat function for join the columns
  SELECT e.*, GROUP_CONCAT(concat(mgl.genre_title, mgl.genre_id)  SEPARATOR "-") AS genres
  FROM events e
  LEFT JOIN music_genres_link mgl ON e.id = mgl.event_id
  WHERE e.id = 1
  GROUP BY e.id

and SEPARATOR  .. Too

A: I believe you want:
SELECT e.*,
       GROUP_CONCAT(mgl.genre_title, '-', mgl.genre_id) as genres
FROM events e LEFT JOIN
     music_genres_link mgl
     ON e.id = mgl.event_id
WHERE e.id = 1
GROUP BY e.id;

Notes:

*

*SEPARATOR, not SEPERATOR.

*The separator is for the values for different rows.  For the values within a row, you need to add it manually in the GROUP_CONCAT().

*As you seem to know, GROUP_CONCAT() takes multiple arguments.

*If you are selecting one event, then the GROUP BY is unnecessary.


text:
Q: How do I make everything centered when page is zoomed out? I've just made the switch from Bootstrap to Semantic UI and having some problems with the grid system.
Using Bootstrap I could set a max-width of 1600px so that the content wouldn't disappear to the sides when someone zooms out to ridiculous levels (no one really would and still expect the page to work but I still want to cover my bases). With Semantic, there are two outcomes:
1) With a max-width the entire page is left-aligned and cut off at 1600px.
2) Without a max-width things are are spaced out waaay too much (always connected to the edges), and the header content disappears to the left.
If you visit Semantic UI's home page and zoom out, you can see that the page is centered along with the header content (not the header background), and I suppose that they use their own framework for their page so it has to be possible somehow.
How do I achieve this?

A: Add margin: 0 auto;. Example:
.container {
  width: 100%;
  max-width: 1600px;
  margin: 0 auto;
}


text:
Q: RegExp to find and replace all the spaces between two separate delimiters I want to find all the white space between two separate delimiters and replace to effectively remove it.
For instance:
{First Value} where {Second Available Value} is greater than {Value}

I want the string to become:
{FirstValue} where {SecondAvailableValue} is greater than {Value}

I have little experience in regexp but this what I tried on a regex builder:
/{([^}]*)}/g

This however matches the sub strings (words in between the curl braces) including the delimiter
How can I match just the spaces inside the curly braces?

A: We can try doing a regex replace with a callback function, targeting the following pattern:
\{.*?\}

That is, we will try to match every term contained in curly braces.  This callback function can then remove all spaces.

var input = "{First Value} where {Second Available Value} is greater than {Value}";
console.log(input);
input = input.replace(/\{.*?\}/g, function(match, contents, offset, input_string) {
    return match.replace(/ /g, '');
});

console.log(input);


text:
Q: is there any quick function to do looking-back calculating in pandas dataframe? I wanna implement a calculate method like a simple scenario:

value computed as the sum of daily data during the previous N days (set N = 3 in the following example)

Dataframe df:  (df.index is 'date')
date  value
20140718  1
20140721  2
20140722  3
20140723  4
20140724  5
20140725  6
20140728  7
......

to do calculating like:
date  value  new
20140718  1  0
20140721  2  0
20140722  3  0
20140723  4  6 (3+2+1)
20140724  5  9 (4+3+2)
20140725  6  12 (5+4+3)
20140728  7  15 (6+5+4)
......

Now I have done this using for cycle like:
df['value']=[0]*len(df)
for idx in df.index
    loc=df.index.get_loc(idx)
    if((loc-N)>=0):
        tmp=df.ix[df.index[loc-3]:df.index[loc-1]]
        sum=tmp['value'].sum()
    else:
        sum=0
    df['new'].ix(idx)=sum

But, when the length of dataframe or the value of N is very long / big, these calculating will be very slow....How I can implement this faster using a function or by other ways?
Besides, if the scenario is more complex? how ? Thanks.

A: Since you want the sum of the previous three excluding the current one, you can use rolling_apply  over the a window of four and sum up all but the last value.
new = rolling_apply(df, 4, lambda x:sum(x[:-1]), min_periods=4)

This is the same as shifting afterwards with a window of three:
new = rolling_apply(df, 3, sum, min_periods=3).shift()

Then
df["new"] = new["value"].fillna(0)


text:
Q: with nvidia optimus + xorg 1.19.3 + kernel 4.10.0-15 and still having screentearing I updated my ubuntu to zesty zapus beta 2 now, I have a laptop ASUS N552VW with optimus (NVIDIA GTX 960m + intel gpus) but I was expecting the screen tearing issue to dissapear with the latest xorg + nvidia drivers + kernel 4.10+
Actually I have only the NVIDIA card set via NVIDIA prime.
Any idea on how can I solve my screen tearing issue?
This has been driving me crazy for a while now.
My xorg.conf (by default, I haven't touched it yet)
Section "ServerLayout"
    Identifier "layout"
    Screen 0 "nvidia"
    Inactive "intel"
EndSection

Section "Device"
    Identifier "intel"
    Driver "modesetting"
    BusID "PCI:0@0:2:0"
    Option "AccelMethod" "None"
EndSection

Section "Screen"
    Identifier "intel"
    Device "intel"
EndSection

Section "Device"
    Identifier "nvidia"
    Driver "nvidia"
    BusID "PCI:1@0:0:0"
    Option "ConstrainCursor" "off"
EndSection

Section "Screen"
    Identifier "nvidia"
    Device "nvidia"
    Option "AllowEmptyInitialConfiguration" "on"
    Option "IgnoreDisplayDevices" "CRT"
EndSection

Thanks

A: Have you tried the following? https://freedompenguin.com/articles/quick-tips/nvidia-linux-video-game-tearing-fix/

A: Write this line:
options nvidia_381_drm modeset=1

In this file as root:
sudo nano /etc/modprobe.d/zz-nvidia-modeset.conf

Replace '381' by your driver version that you will install.
Now uninstall and reinstall the driver.
Wait a few minutes after login. If it works, this command should return 'Y'
sudo cat /sys/module/nvidia_drm/parameters/modeset

Although I would not recommend using it now because it have some significant bugs. To turn on or off:
#on
xrandr --output eDP-1-1 --set 'PRIME Synchronization' '1'
#off
xrandr --output eDP-1-1 --set 'PRIME Synchronization' '0'

Reference


text:
Q: C++ Serial Port Question Problem:
I have a hand held device that scans those graphic color barcodes on all packaging. There is a track device that I can use that will slide the device automatically. This track device functions by taking ascii code through a serial port. I need to get this thing to work in FileMaker on a Mac. So no terminal programs, etc...
What I've got so far:
I bought a Keyspan USB/Serial adapter. Using a program called ZTerm I was successful in sending commands to the device.
Example:
"C,7^M^J"
I was also able to do the same thing in Terminal using this command: screen /dev/tty.KeySerial1 57600
and then type in the same command above(but when I typed in I just hit Control-M and Control-J for the carriage return and line feed)
Now I'm writing a plug-in for FileMaker(in C++ of course). I want to get what I did above happen in C++ so when I install that plug-in in FileMaker I can just call one of those functions and have the whole process take place right there.
I'm able to connect to the device, but I can't talk to it. It is not responding to anything.
I've tried connecting to the device(successfully) using these:
FILE *comport;
if ((comport = fopen("/dev/tty.KeySerial1", "w")) == NULL){...}

and
int fd;
fd = open("/dev/tty.KeySerial1", O_RDWR | O_NOCTTY | O_NDELAY);

This is what I've tried so far in way of talking to the device:
fputs ("C,7^M^J",comport);

or
fprintf(comport,"C,7^M^J");

or
char buffer[] = { 'C' , ',' , '7' , '^' , 'M' , '^' , 'J' };
fwrite (buffer , 1 , sizeof(buffer) , comport );

or
fwrite('C,7^M^J', 1, 1, comport);

Questions:
When I connected to the device from Terminal and using ZTerm, I was able to set my baud rate of 57600. I think that may be why it isn't responding here. But I don't know how to do it here.... Does any one know how to do that? I tried this, but it didn't work:
comport->BaudRate = 57600;

There are a lot of class solutions out there but they all call these include files like termios.h and stdio.h. I don't have these and, for whatever reason, I can't find them to download. I've downloaded a few examples but there are like 20 files in them and they're all calling other files I can't find(like the ones listed above). Do I need to find these and if so where? I just don't know enough about C++ Is there a website where I can download libraries??
Another solution might be to put those terminal commands in C++. Is there a way to do that?
So this has been driving me crazy. I'm not a C++ guy, I only know basic programming concepts. Is anyone out there a C++ expert? I ideally I'd like this to just work using functions I already have, like those fwrite, fputs stuff.
Thanks!

A: Sending a ^ and then a M doesn't send control-M, thats just the way you write it,
to send a control character the easiest way is to just use the ascii control code.
ps.  ^M is carriage return ie "\r" and ^J is linefeed "\n"
edit: Probably more than you will (hopefully) ever need to know - but read The Serial Port Howto before going any further.

A: This isn't a C++ question.  You're asking how to interact with the TTY driver to set teh baud rate.  The fact that you're opening the file under /dev tells me that you're on a unix derivative, so the relevant man page to read on a linux system is "man 3 termios".
Basically, you use the open() variant above, and pass the file descriptor to tcsetattr/tcgetattr.

A: Are you sure you've installed all the compiler tools properly?  On my OS X 10.5.8 Mac,
termios.h and stdio.h are right there under /usr/include, just as I'd expect.  The
code you've already found for serial port programming on other Unix variants should
only require minor changes (if any) to work on a Mac.  Can you tell us a bit more about
what you've tried, and what went wrong?
mgb also has a good point about how the control characters need to be represented.

A: You can set the baud rate with ioctl. Here's a link to an example.

A: You don't specify which Unix you are using, so below I'm posting some Linux production code I use.
Pleae note below code is a class method so ignore any external (ie undeclared) references.
Steps are as follows -
Configure your termio structure, this is where you set any needed flags etc (ie the step you accomplished using zterm. The termio settings below configure the port to 8 databits, 1 stopbit and no parity (8-n-1). Also the port will be in "raw" (as opposed to cooked) mode so its a character stream, text isn't framed into lines etc The baud constants match the actual value, ie for 56700 baud you use "57600".
The timing parameters mean that characters are returned from the device as soon as they are available.
Once you have your termainal parameters set, you open the device (using POSIX open()), and then can use tcgetattr/tcsetattr to configure the device via the fd.
At this point you can read/write to the device using the read()/write() system calls.
Note that in the below example read() will block if no data is available so you may want to use select()/poll() if blocking is undesirable.
Hope that helps.
termios termio
tcflag_t baud_specifier;

    //reset device state...
    memset (&termio, 0, sizeof (termios));
    read_buffer.clear();

    //get our boad rate...
    if (!(baud_specifier = baud_constant (baud))) {
        ostringstream txt;
        txt << "invalid baud - " << baud;
        device_status_msg = txt.str();
        status = false;

        return (true);
    }

    //configure device state...
    termio.c_cflag = baud_specifier | CS8 | CLOCAL | CREAD;

    //do we want handshaking?
    if (rtscts) {
        termio.c_cflag |= CRTSCTS;
    }

    termio.c_iflag = IGNPAR;
    termio.c_oflag = 0;
    termio.c_lflag = 0;

    //com port timing, no wait between characters and read unblocks as soon as there is a character
    termio.c_cc[VTIME]    = 0;
    termio.c_cc[VMIN]     = 0;

    //open device...
    if ((fd = open (device.c_str(), O_RDWR | O_NOCTTY)) == -1) {

        ostringstream txt;
        txt << "open(\"" << device << "\") failed with " << errno << " - "
            << std_error_msg (errno);
        device_status_msg = txt.str();
        status = false;

        return (true);
    }

    //keep a copy of curret device state...
    if (tcgetattr (fd, &old_termio) == -1) {

        ostringstream txt;
        txt << "tcgetattr() failed with " << errno << " - " << std_error_msg (errno);
        device_status_msg = txt.str();
        status = false;

        return (true);
    }

    //flush any unwanted bytes
    if (tcflush (fd, TCIOFLUSH) == -1) {

        ostringstream txt;
        txt << "tcflush() failed with " << errno << " - " << std_error_msg (errno);
        device_status_msg = txt.str();
        status = false;

        return (true);
    }

    //apply our device config...
    if (tcsetattr (fd, TCSANOW, &termio) == -1) {

        ostringstream txt;
        txt << "tcsetattr() failed with " << errno << " - " << std_error_msg (errno);
        device_status_msg = txt.str();
        status = false;

        return (true);
    }

    node_log_f ("successfully initialised device %s at %i baud", "open_device()",
                device.c_str(), baud);

    status = true;
    return (true);
}