text:
Q: Realizar for en template literals JS Existe alguna manera de realizar un for dentro de un template literal en js?
Recupero de un JSON y accedo a ellos en un primer for y todo va bien pero, después la clave de Permisos tiene un valor del tipo arreglo, por eso quería saber si se puede realizar dígamos algo así:
for (let fila of r) {
        tablaNotas.appendChild(stringToRowNode(
            `

                        ${ fila["Email"].toString().toUpperCase()}

                      <button type="button" class="collpase-button collapsed" data-parent="#accordion" data-toggle="collapse" href="#${fila["IdUsuario"]}${fila["IdPermiso"]}"></button>

                            for(let ${p} of ${ fila["Permisos"] }) {

${ p["IdPermiso"] }

${ p["Nombre"] }

                            }

`
        ));
    }

Eso es lo que trato de hacer.
Es esto posible o existe alguna función que me permita realizar algo parecido?

A: No como quieres, pero en un string template puedes poner cualquier código entre ${ } que devuelva algo. Por tanto podrías crear lo siguiente:

let array = ['A','B','C']

let string =
`

  ${array.map(elem => `<li>${elem}</li>`).join('')}

`;

document.body.innerHTML+=string;

Por tanto, tu bucle for
for(let ${p} of ${ fila["Permisos"] }) {

${ p["IdPermiso"] }

${ p["Nombre"] }

}

se podría transformar en:
${fila.Permisos.map(p => `<p>${p.IdPermiso}</p> <p>${p.Nombre}</p>`).join('')}

A: Podrías hacerlo de esta forma.
Donde recorres primeramente el arreglo y sumas las filas correspondientes, después insertas el resultados a tu template.

let arreglo = [{"IdPermiso": 1, "Nombre": "Admin"}, {"IdPermiso": 2, "Nombre": "User"}];
let parrafos = '';
for(let p of arreglo) {
         parrafos += `<p>${ p["IdPermiso"] } / ${ p["Nombre"] }</p>`;
      }
let texto = `<div class="panel-body">${parrafos}</div>`;

document.getElementById("container").innerHTML = texto;


text:
Q: How do I save an in-memory sqlite3 database as a byte array instead of to file? I'm currently using an in-memory(https://www.sqlite.org/inmemorydb.html) database because I cannot guarantee write access.
But in order to save the database, how do I convert the in-memory database to a byte array and potentially save it to file later when I do have write access? Thanks!
The database is created like in the example:
rc = sqlite3_open("file::memory:", &db);

I want to take db and save into a byte array. Then, save the byte array to a file. Then load from the file like normal:
int sqlite3_open_v2(filename_of_saved_db, ppDb, flags, zVfs);

(using c++, but examples in any other language should work as well i assume)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't send descriptor to remote device I developed an BLE application on Android called A to work with my device deviceA.
It is working very well. Now I am stuck in the following case:
I start other BLE application called B and connect with its device called deviceB.
It is in foreground.
My application is running in background.
I start to connect deviceA to application A.
It runs to write descriptor to deviceA and receive onWriteDescriptor with status GATT_SUCCESS. However deviceA can't receive descriptor data.
In the log file, I see that application B start BLE scan/ stop BLE scan many times.
Are there any experts can explain me why deviceA can't receive data in this case?
Thanks you very much.

A: You need to also call setCharacteristicNotification which tells Android to forward the notifications to your app when Android receives the notification.


text:
Q: How to create a group of constants and check if a variable is or isn't included in that group? I want to create an if code to check if variable x is a member of a defined group of constant named a, for example a = { 1 , 2 , 3 , 4 }, then use something like if (x != a).
I only know to use it like this
if ( ( x != 1 ) || ( x != 2 ) || ( x != 3 ) || ( x != 4 ) )

A: You can use functions like this
bool exist_in_group(int value, const int* group,int group_size)
{
    bool res{false};
    for(int i=0;i<group_size;i++)
    {
        if(group[i] == value)
            res = true;
    }
    return res;
}

This function check if value exist in your array(group) or not


text:
Q: My android application crashes when I set a class instance I'm quite new in android programming. I am developping an application which opens well and works almost the way I want. But I have a problem and I don't have a clue about the way to solve it. This is the problem: I am filling in an EditText with a value and in my java code this value will initialize an object that I have created. But this never happens because any try to initialize the object makes my application crash.
The editText in which I input the value to initialize the object is the one called spotText.
Can anybody help?
this is the XML code:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    android:orientation="vertical"
    tools:context=".MainActivity" >

<ScrollView
android:id="@+id/scroll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none">

<HorizontalScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

<TableLayout
    android:id="@+id/TheTable"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="0,1,2,3,4,5,6,7,8,9,10,11,12" >

 <TableRow
     android:id="@+id/tbRow1"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" >

  <TextView
    android:id="@+id/spot"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingRight="10dp"
    android:text="@string/spot"
    android:textSize="10sp"
    android:gravity="center"
    android:textColor="@color/white" />

  <TextView
        android:id="@+id/div"
        android:text="@string/div"
        android:gravity="center"
        android:textColor="@color/white"
        android:textSize="10sp" />

    <TextView
        android:id="@+id/rate"
        android:text="@string/Rate"
        android:gravity="center"
        android:textColor="@color/white"
        android:textSize="10sp" />

    <CheckBox
        android:id="@+id/smile"
        android:text="@string/UseSmile"
        android:textColor="@color/white"
        android:textSize="10sp"/>

    <TextView
        android:id="@+id/ATM"
        android:text="@string/ATM"
        android:gravity="center"
        android:textColor="@color/white"
        android:textSize="10sp" />
</TableRow>

<TableRow
    android:id="@+id/tbRow2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <EditText
        android:id="@+id/spotText"
        android:hint="@string/Spot"
        android:gravity="center"
        android:inputType="numberSigned"
        android:textColor="@color/white"
        android:textSize="10sp" />

    <EditText
        android:id="@+id/divRate"
        android:hint="@string/divRate"
        android:gravity="center"
        android:inputType="numberDecimal"
        android:textColor="@color/white"
        android:textSize="10sp" />

    <EditText
        android:id="@+id/IR"
        android:hint="@string/IRate"
        android:gravity="center"
        android:inputType="numberDecimal"
        android:textColor="@color/white"
        android:textSize="10sp" />
    <EditText
        android:id="@+id/ATMVOL"
        android:hint="@string/ATM"
        android:layout_column="4"
        android:gravity="center"
        android:inputType="numberDecimal"
        android:textColor="@color/white"
        android:textSize="10sp" />

</TableRow>

            <TableRow
                android:id="@+id/tbRow3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/product"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingRight="10dp"
                    android:text="@string/product"
                    android:gravity="center"
                    android:textSize="10sp"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/strike"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingRight="10dp"
                    android:text="@string/strike"
                    android:textSize="10sp"
                    android:gravity="center"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/maturity"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingRight="10dp"
                    android:text="@string/maturity"
                    android:textSize="10sp"
                    android:gravity="center"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/vol"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingRight="10dp"
                    android:textSize="10sp"
                    android:gravity="center"
                    android:text="@string/volatility"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/Qty"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingRight="10dp"
                    android:textSize="10sp"
                    android:gravity="center"
                    android:text="@string/Quantity"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/price"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingRight="15dp"
                    android:textSize="10sp"
                    android:gravity="center"
                    android:text="@string/price"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/delta"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingRight="10dp"
                    android:text="@string/delta"
                    android:textSize="10sp"
                    android:gravity="center"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/gamma"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingRight="10dp"
                    android:text="@string/gamma"
                    android:textSize="10sp"
                    android:gravity="center"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/theta"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingRight="10dp"
                    android:text="@string/theta"
                    android:textSize="10sp"
                    android:gravity="center"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/vega"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingRight="10dp"
                    android:text="@string/vega"
                    android:textSize="10sp"
                    android:gravity="center"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/vanna"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingRight="10dp"
                    android:text="@string/vanna"
                    android:textSize="10sp"
                    android:gravity="center"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/vomma"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingRight="10dp"
                    android:text="@string/vomma"
                    android:textSize="10sp"
                    android:gravity="center"
                    android:textColor="@color/white" />
            </TableRow>
            <TableRow
                android:id="@+id/tbRow4" >
                <Spinner
                    android:id="@+id/spin1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:dropDownSelector="@string/Product"
                    android:prompt="@string/Product"
                    android:entries="@array/Array"
                    android:background="@color/SpinColor"
                    android:textSize="10sp"/>
                <EditText
                    android:id="@+id/K1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:hint="K"
                    android:gravity="center"
                    android:textSize="10sp"/>
                <EditText
                    android:id="@+id/T1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:hint="T"
                    android:gravity="center"
                    android:textSize="10sp"/>
                <EditText
                    android:id="@+id/Vol1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:hint="Vol"
                    android:gravity="center"
                    android:textSize="10sp"/>
                <EditText
                    android:id="@+id/Qty1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:hint="Qty"
                    android:gravity="center"
                    android:textSize="10sp"/>
                <TextView
                    android:id="@+id/Px1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:textSize="10sp"/>
                <TextView
                    android:id="@+id/delta1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:textSize="10sp"/>
                <TextView
                    android:id="@+id/gamma1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:textSize="10sp"/>
                <TextView
                    android:id="@+id/theta1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:textSize="10sp"/>
                <TextView
                    android:id="@+id/vega1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:textSize="10sp"/>
                <TextView
                    android:id="@+id/vanna1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:textSize="10sp"/>
                <TextView
                    android:id="@+id/vomma1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:textSize="10sp"/>
            </TableRow>

            <TableRow
                android:id="@+id/tbRow9">
                 <Button
                    android:id="@+id/delBtn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="10sp"
                    android:text="@string/delete"/>
                <Button
                    android:id="@+id/addBtn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="10sp"
                    android:text="@string/Add"/>

            </TableRow>
        </TableLayout>

   </HorizontalScrollView>
</ScrollView>

Here is the MainActivity class code
    package com.example.lilpricer;

    import android.app.Activity;
    import android.os.Bundle;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.CompoundButton.OnCheckedChangeListener;
    import android.widget.EditText;
    import android.widget.Spinner;
    import android.widget.TableRow;
    import android.widget.TextView;

    public class MainActivity extends Activity {

int nbRow = 1;

TableRow tb1 = null; TableRow tb2 = null; TableRow tb3 = null; TableRow tb4 = null;
TableRow tb5 = null; TableRow tb6 = null; TableRow tb7 = null; TableRow tb8 = null;
TableRow tb9 = null;
TextView tvVol = null; TextView tvSpot;
EditText etSpot = null; EditText etDiv = null; EditText etIR = null; EditText etVol = null;
EditText etK1= null; EditText etK2= null; EditText etK3 = null; EditText etK4= null;
EditText etMat1= null; EditText etMat2= null; EditText etMat3 = null; EditText etMat4= null;
EditText etVol1= null; EditText etVol2= null; EditText etVol3 = null; EditText etVol4= null;
EditText etQty1= null; EditText etQty2= null; EditText etQty3 = null; EditText etQty4= null;
Spinner spin1 = null; Spinner spin2 = null; Spinner spin3 = null; Spinner spin4 = null;
Button Del = null; Button Add = null; Button Price = null;
CheckBox cbSmile = null;
Stock S=null;
Future Fut1 = null; Future Fut2 = null; Future Fut3 = null; Future Fut4 = null;
Option Opt1 = null; Option Opt2 = null; Option Opt3 = null; Option Opt4 = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setWidgetRef();

    tb5.setVisibility(View.INVISIBLE); tb6.setVisibility(View.INVISIBLE); tb7.setVisibility(View.INVISIBLE);
    tvVol.setVisibility(View.INVISIBLE); etVol.setVisibility(View.INVISIBLE);

    etSpot.addTextChangedListener(new TextWatcher() {
        double TheSpot= 0;
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            TheSpot=Double.parseDouble(etSpot.getText().toString());
            S.SetStock(TheSpot);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

private void setWidgetRef()
    {
        tb1 = (TableRow) findViewById(R.id.tbRow1); tb2 = (TableRow) findViewById(R.id.tbRow2);
        tb3 = (TableRow) findViewById(R.id.tbRow3); tb4 = (TableRow) findViewById(R.id.tbRow4);
        tb5 = (TableRow) findViewById(R.id.tbRow5); tb6 = (TableRow) findViewById(R.id.tbRow6);
        tb7 = (TableRow) findViewById(R.id.tbRow7); tb8 = (TableRow) findViewById(R.id.tbRow8);
        tb9 = (TableRow) findViewById(R.id.tbRow9);

        etSpot = (EditText) findViewById(R.id.spotText); etDiv=(EditText) findViewById(R.id.divRate);
        etIR= (EditText) findViewById(R.id.IR); etVol = (EditText) findViewById(R.id.ATMVOL);
        etK1= (EditText) findViewById(R.id.K1); etK2= (EditText) findViewById(R.id.K2);
        etK3= (EditText) findViewById(R.id.K3); etK4= (EditText) findViewById(R.id.K4);
        etMat1 = (EditText) findViewById(R.id.T1);etMat2 = (EditText) findViewById(R.id.T2);
        etMat3 = (EditText) findViewById(R.id.T3);etMat4 = (EditText) findViewById(R.id.T4);
        etVol1 =(EditText) findViewById(R.id.Vol1);etVol2 =(EditText) findViewById(R.id.Vol2);
        etVol3 =(EditText) findViewById(R.id.Vol3);etVol4 =(EditText) findViewById(R.id.Vol4);
        etQty1=(EditText)  findViewById(R.id.Qty1); etQty2=(EditText)  findViewById(R.id.Qty2);
        etQty3=(EditText)  findViewById(R.id.Qty3); etQty4=(EditText)  findViewById(R.id.Qty4);

        tvVol = (TextView) findViewById(R.id.ATM); tvSpot = (TextView) findViewById(R.id.spot);

        Del = (Button) findViewById(R.id.delBtn); Add = (Button) findViewById(R.id.addBtn);
        Price = (Button) findViewById(R.id.priceBtn);

        cbSmile = (CheckBox) findViewById(R.id.smile);

        spin1 = (Spinner) findViewById(R.id.spin1);spin2 = (Spinner) findViewById(R.id.spin2);
        spin3 = (Spinner) findViewById(R.id.spin3);spin4 = (Spinner) findViewById(R.id.spin4);
    }
    }

Here is the classe that I try to initialize the instance
    package com.example.lilpricer;

public class Stock {
private double S;

Stock(double Price){
    S=Math.abs(Price);
}

Stock(){
    this.S=0;
}
public void SetStock(double price) {
    // TODO Auto-generated method stub
    S=Math.abs(price);
}
}

and here is the logcat when application crashes. As you can see, it seems to be a NullPointerException in the EditText in which I input the value to initialize my object Stock, but I dont understand why I have such error since I have define an EditText in java and I linked it with the EditText of my XML page, same thing with my object (named here S), it has been defined as a global variable, so it exists.
I am obviously missing something here, but I just can't seen what it is.
Many thanks in advance for any help.
01-06 02:06:24.770: E/AndroidRuntime(5721): FATAL EXCEPTION: main
01-06 02:06:24.770: E/AndroidRuntime(5721): java.lang.NullPointerException
01-06 02:06:24.770: E/AndroidRuntime(5721):     at com.example.lilpricer.MainActivity$1.onTextChanged(MainActivity.java:144)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.widget.TextView.sendOnTextChanged(TextView.java:7092)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.widget.TextView.handleTextChanged(TextView.java:7151)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:8794)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:962)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:496)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:435)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:30)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.text.method.NumberKeyListener.onKeyDown(NumberKeyListener.java:121)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.widget.TextView.doKeyDown(TextView.java:5246)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.widget.TextView.onKeyDown(TextView.java:5065)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.view.KeyEvent.dispatch(KeyEvent.java:2609)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.view.View.dispatchKeyEvent(View.java:7198)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1359)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1359)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1359)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.widget.HorizontalScrollView.dispatchKeyEvent(HorizontalScrollView.java:332)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1359)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.widget.ScrollView.dispatchKeyEvent(ScrollView.java:353)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1359)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1359)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1359)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1359)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1920)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1395)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.app.Activity.dispatchKeyEvent(Activity.java:2370)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1847)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3701)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.view.ViewRootImpl.handleImeFinishedEvent(ViewRootImpl.java:3651)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:2818)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.os.Looper.loop(Looper.java:137)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at android.app.ActivityThread.main(ActivityThread.java:5039)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at java.lang.reflect.Method.invokeNative(Native Method)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at java.lang.reflect.Method.invoke(Method.java:511)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-06 02:06:24.770: E/AndroidRuntime(5721):     at dalvik.system.NativeStart.main(Native Method)

A: You never instantiated the class. Add S=new Stock() or S=new Stock(price) before using S;


text:
Q: Gulp.js conventions for tasks names Are there any conventions for writing Gulpfiles, namespacing the tasks, structuring the config file etc?
Maybe there are some basic common-sense things that can be taken from Grunt world?
How do you deal with structuring the Gulpfile as if you were to quit your job and the next JS developer would come and intuitively understand how to build the project?

A: So we finished up with grouping the names by phase, nesting subtasks under the names of the main phases.
Essentially we used strategy to copy conventions from build libraries of other languages (e.g. gradle) that were already in place, so build commands for all parts of our process would be the same and everybody could figure out what to
This resulted in:
build
...
build:compile
build:compile:less
...
test
test:unit
...
test:e2e
...
verify
...
release
release:copy
release:copy:fonts


text:
Q: SELECT from database WHERE some parammeter is equal to a portion of a string var Im checking the "validity" (if is authorized to make something) of a domain trying to retrieve it from my database, the url came to my script over a GET var and then i just query the database:
$url = $_GET['url'];             // complete url of the site like: sub1.domain.com/page/1/some
$url = parse_url($_GET['url']);  // parsing the url http://php.net/manual/en/function.parse-url.php
$host = $url['host'];            // gives me sub1.domain.com

After parsing:
$query = "SELECT * FROM domains_table WHERE domain = '" . $host . "'";

This works great, the think is sometimes domain.com have many sub domains and I cant save in database all the variations. It seems to me a lost of space if lets say domain.com have 30 sub domains and then I need to save sub1.domain.com sub2.domain.com and so...
Instead I was thinking in a more smart way, like saving in data base just *.domain.com and then somehow (and this is where i need help) in the query or in the php script (better if is in the query, personal taste) create something that tells * could be any string. How can i do this?
EDIT:
There is some confusion in the answers so I try to explain better my self:
If i have in my table saved on the url field: *.domain1.com how can i make something like this:
SELECT * FROM domain WHERE url LIKE "sub1.domain.com"

To retrieve something.

A: You want to use MySQL's Like operator.
Example:
SELECT * FROM table WHERE value LIKE '%string%';

The % matches any string before or after the "string" part.

A: You can use % as an asterisk (matches anything before or after)
$query = "SELECT * FROM domains_table WHERE domain LIKE '%" . $host . "%'";

A: you can use:
WHERE domain LIKE '%" . $host . "'"

A: One possibility is using the Wildcard Selector:
$query = "SELECT * FROM domains_table WHERE domain LIKE '%" . $host . "'";

With this you match all subdomains. So with
$host = '.domain.com';

you also retrieve all subdomains.
But be careful, it's pretty slow.

A: Not sure you can use LIKE here, as your wildcard would be in the data stored on the table rather than something you are directly looking for
Rather more work, but possibly better would be to split the domain up into each section, and then have a parent and child relationship between each section.
So it you had shop.fred.com and news.fred.com you would have something like.
id  parent  section
1   NULL    com
2   1   fred
3   2   shop
4   2   news

Then drill down through that. Either the simple crude way with recursively executing queries, or uses the nested set methods.


text:
Q: "No releases available" error when installing pecl in Docker I am trying to install Xdebug or Redis package in a Docker container from pecl. Installation failed and returns an error:

There are no releases available for package "pecl.php.net/xdebug".

Example for Xdebug: https://pecl.php.net/package/xdebug/3.1.0
My docker-compose.yaml
version: '3'

networks:
  app-network:

services:
  site:
    build:
      context: .
      dockerfile: nginx.dockerfile
    container_name: my_nginx
    ports:
      - "8082:80"
      - "443:443"
    volumes:
      - ./src:/var/www/html
    depends_on:
      - php
      - db
      - redis
    networks:
      - app-network

  db:
    image: percona
    container_name: my_db
    restart: on-failure
    tty: true
    ports:
      - "3314:3306"
    volumes:
      - ./percona:/var/lib/percona
    environment:
      MYSQL_DATABASE: mydb
      MYSQL_USER: me
      MYSQL_PASSWORD: 123
      MYSQL_ROOT_PASSWORD: 456
      SERVICE_TAGS: dev
      SERVICE_NAME: db
    networks:
      - app-network

  php:
    build:
      context: .
      dockerfile: php.dockerfile
    container_name: my_php
    volumes:
      - ./src:/var/www/html
    ports:
      - "9000:9000"
    networks:
      - app-network

  composer:
    image: frojd/composer-php-7.4
    container_name: my_composer
    volumes:
      - ./src:/var/www/html
    working_dir: /var/www/html
    depends_on:
      - php
    networks:
      - app-network

  redis:
    image: redis:alpine
    container_name: my_redis
    volumes:
      - ./redis:/data
    restart: on-failure
    command: redis-server --appendonly yes --requirepass "${REDIS_PASSWORD}"
    ports:
      - 6380:6379
    networks:
      - app-network

  npm:
    image: node:14.18.0
    container_name: my_npm
    volumes:
      - ./src:/var/www/html
    working_dir: /var/www/html
    entrypoint: ['npm']

  artisan:
    build:
      context: .
      dockerfile: php.dockerfile
    container_name: my_artisan
    volumes:
      - ./src:/var/www/html
    depends_on:
      - db
    working_dir: /var/www/html
    entrypoint: ['php', '/var/www/html/artisan']
    networks:
      - app-network

  cron:
    build:
      context: .
      dockerfile: cron.dockerfile
    container_name: my_cron
    volumes:
      - ./src:/var/www/html
    networks:
      - app-network

My php.dockerfile
FROM php:7.4-fpm

WORKDIR /var/www/html

RUN apt-get update && \
    apt-get install ca-certificates && \
    apt-get clean

RUN docker-php-ext-install pdo pdo_mysql

RUN pecl install xdebug \
    && docker-php-ext-enable xdebug \
    && echo "xdebug.remote_enable=on" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
    && echo "xdebug.remote_host = host.docker.internal" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini

What is the cause of the error and how can I fix it?

A: You may be behind a proxy... I resolved this same problem by setting the proxy for PECL specifically (the environment variable alone $HTTP_PROXY won't work).
RUN pear config-set http_proxy ${http_proxy} &&\
    pear config-set php_ini $PHP_INI_DIR/php.ini

RUN pecl install xdebug-3.1.1 && docker-php-ext-enable xdebug

This answer helped me: https://stackoverflow.com/a/11195778/256762. Hope mine's help as well .


text:
Q: Vuejs component not registering with laravel I know this question is being asked several times, but I couldn't find any solution to my problem.
I have two vue components on my laravel project. The first one is the laravel default component called "ExampleComponent.vue" and the second one is my own new component called "multi.vue".
I use them in a section.blade.php file like below:
@extends('layouts.app')

@section('content')
<example-component></example-component>

<multi></multi>

@endsection

but only the "example-component" works and for the "multi" component, it gives me the following error:
Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the "name" option.
here is my app.js code:
require('./bootstrap');

window.Vue = require('vue');

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

Vue.component('multi', require('./components/multi.vue').default);

const app = new Vue({
    el: '#app',
});

Here is my components codes:
ExampleComponent.vue:
<template>

Example Component

                        I'm an example component.

</template>

And my multi.vue:
<template>

      I am multi component!

</template>

And the route is:
Route::get('/section',function(){
    return view('section');
});

A: For solving this problem, all you need to do is to run "run npm watch".
After running that command, it will recomplie your vue code whenever you make a change in your code and save it.
Keep it in a separate terminal, and run "php artisan serve" in another terminal.

A: From https://v2.vuejs.org/v2/style-guide/#Multi-word-component-names-essential:

Component names should always be multi-word, except for root App
components, and built-in components provided by Vue, such as
<transition> or <component>.
This prevents conflicts with existing and future HTML elements, since
all HTML elements are a single word.


text:
Q: graphite puppet error while installation Getting the below error while installing graphite server using puppet
The pupet module installed for graphite
puppet module install dwerder-graphite

This is the content of graphite.pp
cat graphite.pp

The output
class {'graphite':
}

This the Command
puppet apply graphite.pp

The error what i received:
warning: Scope(Class[Graphite::Params]): Could not look up qualified variable 'graphite::gr_web_group'; class graphite has not been evaluated at /etc/puppet/modules/graphite/manifests/params.pp:97
warning: Scope(Class[Graphite::Params]): Could not look up qualified variable 'graphite::gr_web_group'; class graphite has not been evaluated at /etc/puppet/modules/graphite/manifests/params.pp:97
warning: Scope(Class[Graphite::Params]): Could not look up qualified variable 'graphite::gr_web_user'; class graphite has not been evaluated at /etc/puppet/modules/graphite/manifests/params.pp:103
warning: Scope(Class[Graphite::Params]): Could not look up qualified variable 'graphite::gr_web_user'; class graphite has not been evaluated at /etc/puppet/modules/graphite/manifests/params.pp:103
Failed to parse template graphite/opt/graphite/conf/carbon.conf.erb:
  Filepath: /usr/lib/ruby/site_ruby/1.8/puppet/parser/scope.rb
  Line: 459
  Detail: undefined method `[]' for #<Puppet::Parser::Scope:0x7f82caef1e98>
 at /etc/puppet/modules/graphite/manifests/config.pp:171 on node test

I'm running on RHEL
 cat /etc/redhat-release
Red Hat Enterprise Linux Workstation release 6.4 (Santiago)

A: Where do you put file graphite.pp? Here is way to test the modules recommend by Puppetlabs.
If you puppet modules is /etc/puppet/modules, then create tests folder under it, and create graphite.pp, then add content in it:
include graphite

When you manually apply the change, run this command:
cd /etc/puppet/modules/tests
puppet apply --modulepath=/etc/puppet/modules graphite.pp


text:
Q: Updating/Setting relationships in Core Data when users enter data from different tableviews I have 3 entities in my core data app:  Criteria--->>Rank(has 1 attribute:criteriaRank)<<---Option
Let's a user enters a few options in a tableview and then goes to another tableview where they enter some number of criteria.  The way my app is suppose to behave is that for each criteria that the user enters, it should create a Rank object so that when a user goes back to the options tableview and select an option, it should allow them to rank each criteria they entered.
Right now, when I create a new criteria I set it the following way,
//Create new Criteria and set its context
Criteria *newCriteria = [NSEntityDescription insertNewObjectForEntityForName:@"Criteria" inManagedObjectContext:context];

for (Option *anOption in sortedOptions) {
    Rank *newCriteriaRank = [NSEntityDescription insertNewObjectForEntityForName:@"Rank" inManagedObjectContext:context];

    [newCriteria addRankingsObject:newCriteriaRank];
    [anOption addRankingsObject: newCriteriaRank];
}

But then what if I have to go back and add another option?
I guess what I am asking is what is a good way to set the relationships so that each side is updated when the other get changed.
I looked in KVO and Notifications, but I am not sure exactly where to start.
Thanks.

A: Select your .xcdatamodel, select one of the entities. Under relationship, select the relationship in question and then select an Inverse. This will help maintain your RFI.
This assumes that you have one relationship on each entity that points at the other. If you don't have relationships on both entities, then you'll have to add one in order to get inverse working properly.


text:
Q: Setting different path for installation in python packaging I am new to python packaging. My Command Line Interface (CLI) named virtdc modules has to be installed in /var/lib/virtdc. virtdc is the top folder structure
/var/lib/virtdc/
            framework/
            simulation/
            setup.py

So my setup.py file is under virtdc. When I package this and download and install, it is installing in the default location (site-packages) under python. But my CLI has to be installed under /var/lib. my setup.py file is here.
Is there any way to make it installable to /var/lib by default but not through prefix or target option.
You can find my python package here
How can I install the package under /var/lib/virtdc instead of default location?
Thanks


text:
Q: How to use External Authentication for ASP.NET Boilerplate? I want to use External Authentication for my project. Can anyone tell me how to use External Authentication for ASP.NET Boilerplate?

A: From the documentation on External Authentication:

UserManager defines an extension point named 'external authentication source'. We can create a class derived from IExternalAuthenticationSource and register to the configuration. There is DefaultExternalAuthenticationSource class to simplify implementation of IExternalAuthenticationSource. Let's see an example:

public class MyExternalAuthSource : DefaultExternalAuthenticationSource<Tenant, User>
{
    public override string Name => "MyCustomSource";

    public override Task<bool> TryAuthenticateAsync(string userNameOrEmailAddress, string plainPassword, Tenant tenant)
    {
        // Authenticate user and return true or false
    }
}


text:
Q: Python multithreading, How is it using multiple Cores? I am running a multithreaded application(Python2.7.3) in a Intel(R) Core(TM)2 Duo CPU     E7500  @ 2.93GHz. I thought it would be using only one core but using the "top" command I see that the python processes are constantly changing the core no. Enabling "SHOW THREADS" in the top command shows diffrent thread processes working on different cores.
Can anyone please explain this? It is bothering me as I know from theory that multithreading is executed on a single core.

A: First off, multithreading means the inverse, namely that multiple cores are being utilized (via threading) at the same time. CPython is indeed crippled when it comes to this, though whenever you call into C code (this includes parts of the standard library, but also extension modules like Numpy) the lock which prevents concurrent execution of Python code may be unlocked. You can still have multiple threads, they just won't be interpreting Python at the same time (instead, they'll take turns quite frequently). You also speak of "Python processes" -- are you confusing terminology, or is this "multithreaded" Python application in fact multiprocessing? Of course multiple Python processes can run concurrently.
However, from your wording I suspect another source of confusion. Even a single thread can run on multiple cores... just not at the same time. It is up to the operating system which thread is running on which CPU, and the OS scheduler does not necessarily re-assign a thread to the same CPU where it used to run before it was suspended (it's beneficial, as David Schwartz notes in the comments, but not vital). That is, it's perfectly normal for a single thread/process to jump from CPU to CPU.

A: Threads are designed to take advantage of multiple cores when they are available. If you only have one core, they'll run on one core too. :-)
There's nothing to be concerned about, what you observe is "working as intended".


text:
Q: Configuring per-item Windows Updates There are innumerable reasons why someone would not want Windows to automatically apply any and all updates blindly. Most rational people with a modicum of computer knowledge will opt to set Windows to automatically check for updates, but let them review the list before manually applying them.
The problem is that there are some updates that we may in fact want automatically applied such as Windows Defender/Security Essentials definitions. Most people will usually want to automatically update those.
The Windows Update configuration dialog seems to only let you turn everything on or off.
I don't suppose that there is any way to configure updates per-item so that some things like malware definitions are automatically updated?
I fear there may be no way to do this for two reasons:

*

*While the configuration dialog exposes a limited set of options, the registry settings don't seem to offer any more flexibility.

*Allowing this would require some sort of item-specific identifier to distinguish items which seems not to be the case per this question.

A: You can try to script updates on command line, on remote computers you can do that with psexec - there is a command line tool called wuinstall that can do that - gives you complete control over every update you install, you have to be a bit fit at shell scripting though.
If you check the documentation on the website (http://www.wuinstall.com), there are lot of options to select updates - simplest way would be to call
wuinstall /install /match "Internet Explorer"

to only instal IE updates - you can also filter by product, KB-Numer or regex


text:
Q: Login failed message does not appear on a website while using selenium I am trying to log in into a website using selenium.The end site provides a access denied message if i enter wrong credentials and submit the login form(without selenium).But when i do the same stuff using selenium,the access denied message does not appear. Any suggestions?
URL : https://oa.lombardfinance.com.au/
    ChromeOptions options = new ChromeOptions();
    options.addArguments("disable-infobars");
    WebDriver driver = new ChromeDriver(options);
    JavascriptExecutor js = (JavascriptExecutor)driver;
    driver.get("https://oa.lombardfinance.com.au/");
    driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtClientNumber")).sendKeys("Subrat");
    driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtPassword")).sendKeys("Subrat");
    driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtCaptcha")).sendKeys("Subrat");
    //WebElement loginForm = driver.findElement(By.id("aspnetForm"));
    //js.executeScript("arguments[0].submit();", loginForm);

    WebElement login = driver.findElement(By.id("ctl00_ContentPlaceHolder1_btnLogin2"));
    new Actions(driver).moveToElement(login).click().perform();

A: Just tried the same code you're using with a slight difference in driver initiation:
System.setProperty("webdriver.chrome.driver", "\path\to\chromedriver.exe");
WebDriver driver = new ChromeDriver();

I excluded the line:
    options.addArguments("disable-infobars");
and the Selenium test shows Access denied as well.

A: Try using the below code:
  System.setProperty("webdriver.chrome.driver", "\\path\\to\\chromedriver.exe");
  ChromeOptions options = new ChromeOptions();
  options.addArguments("--test-type");
  options.addArguments("--disable-extensions");
  WebDriver driver = new ChromeDriver(options);

The solution is more convenient one because some times browser shows developer mode issue.


text:
Q: Navigate without touching the mouse I hate touching the mouse, is there a way to navigate through Stack Overflow questions without doing so?  I'm thinking something akin to Google's search results (not sure how long this has been a feature of theirs).  Once your at the google homepage, you can type your query then navigate the results using up/down arrow to select which result, then hit enter to go to that link.  Something like that would be cool, IMO.

A: I've done some work on the userscript I promised in a comment on this question.

Install | Source

Please utilize the Github Repository Issues
page for reporting any feature requests or bugs.
It still needs a bit of polish (especially the help dialog), but it is functional, and I'd love to get some feedback.  You can access the list of commands via the help command:  ?.

A: Till this feature is not implemented, you can try mouseless plugins, for example I can suggest Vimium for Chrome. It will bind alternative key combination to each site link.

A:
... navigate the results using up/down arrow to select which result, then
  hit enter to go to that link. Something like that would be cool, IMO.

My answer is not related to StackOverflow, but anyway.
Today I released my personal mouse emulator where, in most cases, the user can navigate up/down over text lines, links, icons, whatever, with a single key press.
If you're a Windows user, check it out https://github.com/ndandoulakis/SlickCursor

Sample image of navigable areas detected by the app

A: You can use VimFx for firefox. This is a awesome tool who doesn't like using mouse and who wants to make browsing fast.


text:
Q: Why the float cannot give exactly 0 value? I have a question. Below is my code. I am wonder why, my output for "err3" cannot give a value of 0 ? is it because of the datatype is float?
The output are as below:
the value of err1 is -7.03125e-06
the value of err2 is 7.03125e-06
the value of err3 is -4.54747e-13
the operation between err1 and err2 is + and thus, the value for err3 should be 0.
can anyone help me to explain and solve this problem? I have google but still did not get the result.
Thanks in advance :)
void calnormal()
{
long numcal;
float indexNC0,indexNC1;
float error;

float aa0 = 0, ab0 = 0, ac0 = 0, ad0 = 0;
float          bb0 = 0, bc0 = 0, bd0 = 0;
float                   cc0 = 0, cd0 = 0;
float                            dd0 = 0;

float aa, ab, ac, ad;
float     bb, bc, bd;
float         cc, cd;
float             dd;

for(int i=0;i<noofvert;i++)
{
    numcal = vlist[i].returnsizef();
    for(int j=0;j<numcal;j=j+2)
    {
        indexNC0 = vlist[i].returnindexf(j);
        u.ax = vlist[i].returnx() - vlist[indexNC0].returnx();
        u.ay = vlist[i].returny() - vlist[indexNC0].returny();
        u.az = vlist[i].returnz() - vlist[indexNC0].returnz();
        if(j == 0){v0 = u;}

        indexNC1 = vlist[i].returnindexf(j+1);
        v.ax = vlist[i].returnx() - vlist[indexNC1].returnx();
        v.ay = vlist[i].returny() - vlist[indexNC1].returny();
        v.az = vlist[i].returnz() - vlist[indexNC1].returnz();

        normal.ax = u.ay * v.az - u.az * v.ay;
        normal.ay = u.az * v.ax - u.ax * v.az;
        normal.az = u.ax * v.ay - u.ay * v.ax;

        normal.D = - vlist[i].returnx() * normal.ax -    vlist[i].returny() * normal.ay - vlist[i].returnz() * normal.az;

        aa = normal.ax * normal.ax;
        ab = normal.ax * normal.ay;
        ac = normal.ax * normal.az;
        ad = normal.ax * normal.D;

        bb = normal.ay * normal.ay;
        bc = normal.ay * normal.az;
        bd = normal.ay * normal.D;

        cc = normal.az * normal.az;
        cd = normal.az * normal.D;

        dd = normal.D * normal.D;

        aa0 = aa0 + aa;
        ab0 = ab0 + ab;    bb0 = bb0 + bb;
        ac0 = ac0 + ac;    bc0 = bc0 + bc;    cc0 = cc0 + cc;
        ad0 = ad0 + ad;    bd0 = bd0 + bd;    cd0 = cd0 + cd;    dd0 = dd0 + dd;

    }

    double err1,err2,err3;

    **err1 = cd0 * vlist[i].returnz();
    err2 = dd0 ;

    err3 = err2 + err1;
    cout  <<  err1 << " " << err2 << " " << err3 << endl;**

    cout << endl;
}
cout << endl;

}

A: err3 is very close to zero, 13 zeros. err1 and err2 have 6 zeros.
A float can store about 7 decimal digits of precision.
If you had printed out more decimals of err1 and err2 you probably see they are not exactly the same. Because err1 and err2 is float they store 7 digits of precision. They probably differ a little bit in the last digit (0.5zeros+7digits) and substracting them give a result with 0.000..00x (13 zeros).
A double have roughly a maximum of 16 decimal digits of precision. When you do computations, you lose a little precision for every operation because every result is truncated to about 16 decimal digits. If you in the end end up with 13 digits of precision it is fully normal.


text:
Q: java Integer.MAX_VALUE, MIN_VALUE overflow Ok maybe I am just tired because of this but how can I accomplish this?
int x = Integer.MAX_VALUE+10;

// or perhaps
int x = Integer.MIN_VALUE-20;

I just want the if statement to catch if x is "within range" kinda like this:
if(x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE){ //throw exception}

But the problem is that if the value is as mentioned above, like MAX_VALUE + 10, the value ends up being neither higher than the MAX VALUE nor lower than the MIN_VALUE and the if-conditions aren't met...
Edit: To clarify what I meant:
I don't want to actually store any values bigger than the max/min value.
Imagine this:
A field, you write 10+10 and it says like "Ok, that's 20"
Next up, someone maybe will write 1000000100000 and it will respond with the answer as well
but then someone might write something that exceeds the max/min values like, 100000001000000*1000000 or someyhing like that and then the program should be all like "Hold up, that's way too high! here's a "0" for you instead"

A: This can be solved in 2 ways:
First way:
if(x + 10 <= x){ //Has wrapped arround so throw exception}
Second way (better):
long x = Integer.MAX_VALUE+10L;
Now the conditional works properly
if(x >= Integer.MAX_VALUE){ //throw exception}

A: If you need to represent integers which are larger or smaller than the limits, then use long instead of int variables. If, on the other hand, you're truly worrying about int variables that contain a value larger than Integer.MAX_VALUE, then stop worrying -- such a thing can't exist. By the time the value is stored in an int, any overflow or underflow has already occurred.

A: The problem with all of the previously provided solutions is that they all recommend upcasting to a primitive which is of a larger size to perform your calculation (such as using long instead of int).
This approach is a little heavy handed and fails when you're already using the largest primitive. Instead you can check to see if an operation, such as addition or subtraction, will overflow prior to performing the operation.
Here's a function from The CERT Oracle Secure Coding Standard for Java, which also provides equivalent functions for the other mathematical operators, such as subtraction.
static final int safeAdd(int left, int right) throws ArithmeticException {
  if (right > 0 ? left > Integer.MAX_VALUE - right
                : left < Integer.MIN_VALUE - right) {
    throw new ArithmeticException("Integer overflow");
  }
  return left + right;
}

A: Integer.MAX_VALUE and MIN_VALUE are the largest/smallest values representable with an int. That's the point: you can't have an int with lesser or greater values.
If you want to hold and test against lesser or greater values, you'll need to use a long.
When you try to add to e.g. Integer.MAX_VALUE and hold the result in an int, the variable will overflow, and the result will remain a value somewhere between MAX_VALUE and MIN_VALUE.


text:
Q: How can i use Google API in VUE? I'm linking Google's login API to a web project.
I'm trying one by one while looking at the official document.
The script is declared in index.html
I do not recognize the function(?) declared in Google
(like gapi... and initialized method)
How do I fix this?
    <template>

Login

    </template>

thank you!


text:
Q: Multiple SOAP services at same URL (different version of the same) I have a need to support multiple versions of SOAP endpoint with the same URL, is this possible?
Soap classes have been generated from a third party wsdl.
In web.xml I have:
<servlet>
  <servlet-name>soap</servlet-name>
  <servlet-class>com.sun.xml.ws.transport.http.servlet.WSSpringServlet</servlet-class>
  <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>soap</servlet-name>
  <url-pattern>/soap/*</url-pattern>
</servlet-mapping>

In my applicationContext.xml I have the following:
<wss:binding url="/soap/StuffService/">
    <wss:service>
        <ws:service bean="#stuffV1"/>
    </wss:service>
</wss:binding>

<bean id="stuffV1" class="package.soap.StuffSoapEndpointV1"/>

And I have a java class:
@WebService(
        portName = "BasicHttpBinding_IStuffService",
        serviceName = "StuffService",
        endpointInterface = "package.soap.stuff.IStuffService",
        targetNamespace = "http://stuff.example.org/Integration/Service/Outgoing/v1",
        wsdlLocation = "/WEB-INF/Integration.Service.Outgoing.v1.IStuff.wsdl")
@ApiOperation(value = "Stuff Service")
public class StuffSoapEndpointV1 implements IStuffService {

Is it possible to add a second version to the same url? Something in the lines of:
<wss:binding url="/soap/StuffService/">
    <wss:service>
        <ws:service bean="#stuffV1"/>
        <ws:service bean="#stuffV2"/>
    </wss:service>
</wss:binding>

<bean id="stuffV1" class="package.soap.StuffSoapEndpointV1"/>
<bean id="stuffV2" class="package.soap.StuffSoapEndpointV2"/>

@WebService(
        portName = "BasicHttpBinding_IStuffService",
        serviceName = "StuffService",
        endpointInterface = "package.soap.stuff.IStuffService",
        targetNamespace = "http://stuff.example.org/Integration/Service/Outgoing/v2",
        wsdlLocation = "/WEB-INF/Integration.Service.Outgoing.v2.IStuff.wsdl")
@ApiOperation(value = "Stuff Service")
public class StuffSoapEndpointV2 implements IStuffService {

That doesn't work. Multiple ws:service tags are not allowed, same for wss:service and wss:binding with same url. Also I think that portName and serviceName combo should be unique, but they need to be same as in the wsdl which doesn't come from us.


text:
Q: UIView flip animation In my game I have a grid of smaller UIViews hosted on my main UIView.  Randomly the boxes will turn a different colour, at this point a user can touch them to score a point.  When they touch the box I want to show some kind of animation, ideally something similar to the modal horizontal flip segue that XCode offers natively.  How can I do this animation without actually transitioning into another UIView?

A: For each box that should be flipped you can use a container UIView.
Add both sides into this container.
if (side1Visible) {
    UIViewAnimationOptions options = UIViewAnimationOptionBeginFromCurrentState |
    UIViewAnimationTransitionFlipFromRight;

    [UIView transitionWithView:containerView
                  duration:1.0
                   options:options
                animations:^{ side1.hidden = YES; side2.hidden = NO; }
                completion:NULL];
} else {
    UIViewAnimationOptions options = UIViewAnimationOptionBeginFromCurrentState |
    UIViewAnimationTransitionFlipFromLeft;

    [UIView transitionWithView:containerView
              duration:1.0
               options:options
            animations:^{ side1.hidden = NO; side2.hidden = YES; }
            completion:NULL];
}

A: You could simply try and animate the view transform like this (for a vertical flip):
[UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut
                 animations:^(void) {
                     view.transform = CGAffineTransformMakeScale(1, -1);
                 }
                 completion:nil];

or for better control you could have a look into iOS-Flip-Transform.
EDIT:
for the shadow thing, try this:
    view.layer.shadowColor = [UIColor blackColor].CGColor;
    view.layer.shadowOpacity = 0.75;
    view.layer.shadowRadius = 15.0;
    view.layer.shadowOffset = (CGSize){0.0,20.0};

[UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut
                 animations:^(void) {
                     view.transform = CGAffineTransformMakeScale(1, -1);
                 }
                 completion:^(BOOL b) {
    view.layer.shadowColor = [UIColor clearColor].CGColor;
    view.layer.shadowOpacity = 0.0;
    view.layer.shadowRadius = 0.0;
    view.layer.shadowOffset = (CGSize){0.0, 0.0};
                 }];

I hope this works fine for you. You can change the shadow settings as you like. Don't forget to import QuartzCore/QuartzCore.h.

A: UIView provides a method called
+ (void)transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion

The options include UIViewAnimationOptionTransitionFlipFromLeft and ...Right

A: You can do this with the following code for Swift 3.0:
    UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseInOut, animations: {
        self.view.transform = CGAffineTransform(scaleX: 1, y: -1)
    }, completion: nil)

Just keep in mind, that this action will occur on your main thread, so the app will be blocked during execution.
If you require a completion handler, there are several options for

A: This is what I ended up with (in Swift 3) based on Ilker Baltaci's answer:
@IBAction func flipViews() {

    // declare variables for transition
    let duration = 0.5
    var animationOptions: UIViewAnimationOptions
    var animations: () -> Void
    var completion: ((Bool) -> Void)?

    if view2.isHidden {
        animationOptions = [.beginFromCurrentState, .transitionFlipFromTop]
        animations = {
            self.view2.isHidden = false
            self.view1.isHidden = true
        }
        completion = { success in
            if success {
                self.updateSomeContentOfView2()
            }
        }
    } else {
        animationOptions = [.beginFromCurrentState, .transitionFlipFromBottom]
        animations = {
            self.view2.isHidden = true
            self.view1.isHidden = false
        }
    }

    UIView.transition(with: containerView,
                      duration: duration,
                      options: animationOptions,
                      animations: animations,
                      completion: completion)
}

My View hierarchy for containerView, view1 & view2 (which are all IBOutlets in my custom ViewController class) is as follows:

*

*containerView

*

*view1

*view2


text:
Q: Problems Installing Dukto? I can't seem to follow the tutorials for Dukto (A file transfer program, an alternative to Wi-fi Direct), as the command sudo apt install dukto returns E: Unable to locate package dukto
 Does this package still exist? Every tutorial on the subject seems to include an install command for this package. I'm using Kubuntu 17.04, so maybe this has something to do with it? I don't know if 17.04 is compatible with 16.04 packages, which I believe duckto is.

A: Dukto is not in the regular Ubuntu repositories.
Download it at the home page at http://www.msec.it/blog/?page_id=11
The direct Ubuntu download is at https://software.opensuse.org/download.html?project=home:colomboem&package=dukto
Update #1:
Did you follow these instructions?
sudo sh -c "echo 'deb http://download.opensuse.org/repositories/home:/colomboem/xUbuntu_16.04/ /' > /etc/apt/sources.list.d/dukto.list"
sudo apt-get update
sudo apt-get install dukto

If that didn't work, then do this...
Download the file here...
http://download.opensuse.org/repositories/home:/colomboem/xUbuntu_16.04/amd64/dukto_6.0-1_amd64.deb
And assuming that the .deb file went to your Downloads folder, install it with...
sudo dpkg -i ~/Downloads/dukto_6.0-1_amd64.deb

A: Maybe it's late but you can install it from snap
Install Dukto
Enable Snapd
sudo apt update
sudo apt install snapd

Install dukto
sudo snap install dukto


text:
Q: android - edittext lost focus to listview solved: android - edittext lost focus to listview
in my app i'm trying to insert data into database and retrieve them and show on listview
i have a relative layout and 2 edittext and one listview with custom adapter for showing two columns of data in listview
edittext are in top and listview is in bottom of screen
i override edittext onkey methods for check if user press enter key then if on edittext1 then edittext2 requestfocus and if on edittext2 then insert data to database retrieve data from database and fill the listview after that back focus to edittext2 and continue this loop
BUT, after insert one row when press enter key on edittext1 focus go to edittext2 and jump very fast to listview first item !!!! i can back focus with tap edittext2 but this shouldn't happen
i check my code i just pass request focus between two edittext no list view
what should i do ?
edit 1:
i use custom edit text extends class work on one activity but not work on all then the problem not solved
when i try to change focus from one edittext to another edittext the first item of listview capture the focus and highlight


text:
Q: No artifacts found. CircleCI and CodeClimate integration (Node,Mocha,Istanbul) Istanbul puts everything into coverage folder.
In circle.yaml I set the below ENV var as artifact folder.
CIRCLE_ARTIFACTS: ~/proj_name/coverage
CircleCI doesn't seem to find artifacts. Build says no atrifacts found.
Am I missing anything here?

A: CircleCI started to collect artifacts after setting this config:
general:
  artifacts:
    - "~proj_name/coverage"


text:
Q: Why is a `for` loop so much faster to count True values? I recently answered a question on a sister site which asked for a function that counts all even digits of a number. One of the other answers contained two functions (which turned out to be the fastest, so far):
def count_even_digits_spyr03_for(n):
    count = 0
    for c in str(n):
        if c in "02468":
            count += 1
    return count

def count_even_digits_spyr03_sum(n):
    return sum(c in "02468" for c in str(n))

In addition I looked at using a list comprehension and list.count:
def count_even_digits_spyr03_list(n):
    return [c in "02468" for c in str(n)].count(True)

The first two functions are essentially the same, except that the first one uses an explicit counting loop, while the second one uses the built-in sum. I would have expected the second one to be faster (based on e.g. this answer), and it is what I would have recommended turning the former into if asked for a review. But, it turns out it is the other way around. Testing it with some random numbers with increasing number of digits (so the chance that any single digit is even is about 50%) I get the following timings:

Why is the manual for loop so much faster? It's almost a factor two faster than using sum. And since the built-in sum should be about five times faster than manually summing a list (as per the linked answer), it means that it is actually ten times faster! Is the saving from only having to add one to the counter for half the values, because the other half gets discarded, enough to explain this difference?

Using an if as a filter like so:
def count_even_digits_spyr03_sum2(n):
    return sum(1 for c in str(n) if c in "02468")

Improves the timing only to the same level as the list comprehension.

When extending the timings to larger numbers, and normalizing to the for loop timing, they asymptotically converge for very large numbers (>10k digits), probably due to the time str(n) takes:

A: @MarkusMeskanen's answer has the right bits – function calls are slow, and both genexprs and listcomps are basically function calls.
Anyway, to be pragmatic:
Using str.count(c) is faster, and this related answer of mine about strpbrk() in Python could make things faster still.
def count_even_digits_spyr03_count(n):
    s = str(n)
    return sum(s.count(c) for c in "02468")

def count_even_digits_spyr03_count_unrolled(n):
    s = str(n)
    return s.count("0") + s.count("2") + s.count("4") + s.count("6") + s.count("8")

Results:
string length: 502
count_even_digits_spyr03_list 0.04157966522
count_even_digits_spyr03_sum 0.05678154459
count_even_digits_spyr03_for 0.036128606150000006
count_even_digits_spyr03_count 0.010441866129999991
count_even_digits_spyr03_count_unrolled 0.009662931009999999

A: There are a few differences that actually contribute to the observed performance differences. I aim to give a high-level overview of these differences but try not to go too much into the low-level details or possible improvements. For the benchmarks I use my own package simple_benchmark.
Generators vs. for loops
Generators and generator expressions are syntactic sugar that can be used instead of writing iterator classes.
When you write a generator like:
def count_even(num):
    s = str(num)
    for c in s:
        yield c in '02468'

Or a generator expression:
(c in '02468' for c in str(num))

That will be transformed (behind the scenes) into a state machine that is accessible through an iterator class. In the end it will be roughly equivalent to (although the actual code generated around a generator will be faster):
class Count:
    def __init__(self, num):
        self.str_num = iter(str(num))

    def __iter__(self):
        return self

    def __next__(self):
        c = next(self.str_num)
        return c in '02468'

So a generator will always have one additional layer of indirection. That means that advancing the generator (or generator expression or iterator) means that you call __next__ on the iterator that is generated by the generator which itself calls __next__ on the object you actually want to iterate over. But it also has some overhead because you actually need to create one additional "iterator instance". Typically these overheads are negligible if you do anything substantial in each iteration.
Just to provide an example how much overhead a generator imposes compared to a manual loop:
import matplotlib.pyplot as plt
from simple_benchmark import BenchmarkBuilder
%matplotlib notebook

bench = BenchmarkBuilder()

@bench.add_function()
def iteration(it):
    for i in it:
        pass

@bench.add_function()
def generator(it):
    it = (item for item in it)
    for i in it:
        pass

@bench.add_arguments()
def argument_provider():
    for i in range(2, 15):
        size = 2**i
        yield size, [1 for _ in range(size)]

plt.figure()
result = bench.run()
result.plot()

Generators vs. List comprehensions
Generators have the advantage that they don't create a list, they "produce" the values one-by-one. So while a generator has the overhead of the "iterator class" it can save the memory for creating an intermediate list. It's a trade-off between speed (list comprehension) and memory (generators). This has been discussed in various posts around StackOverflow so I don't want to go into much more detail here.
import matplotlib.pyplot as plt
from simple_benchmark import BenchmarkBuilder
%matplotlib notebook

bench = BenchmarkBuilder()

@bench.add_function()
def generator_expression(it):
    it = (item for item in it)
    for i in it:
        pass

@bench.add_function()
def list_comprehension(it):
    it = [item for item in it]
    for i in it:
        pass

@bench.add_arguments('size')
def argument_provider():
    for i in range(2, 15):
        size = 2**i
        yield size, list(range(size))

plt.figure()
result = bench.run()
result.plot()

sum should be faster than manual iteration
Yes, sum is indeed faster than an explicit for loop. Especially if you iterate over integers.
import matplotlib.pyplot as plt
from simple_benchmark import BenchmarkBuilder
%matplotlib notebook

bench = BenchmarkBuilder()

@bench.add_function()
def my_sum(it):
    sum_ = 0
    for i in it:
        sum_ += i
    return sum_

bench.add_function()(sum)

@bench.add_arguments()
def argument_provider():
    for i in range(2, 15):
        size = 2**i
        yield size, [1 for _ in range(size)]

plt.figure()
result = bench.run()
result.plot()

String methods vs. Any kind of Python loop
To understand the performance difference when using string methods like str.count compared to loops (explicit or implicit) is that strings in Python are actually stored as values in an (internal) array. That means a loop doesn't actually call any __next__ methods, it can use a loop directly over the array, this will be significantly faster. However it also imposes a method lookup and a method call on the string, that's why it's slower for very short numbers.
Just to provide a small comparison how long it takes to iterate a string vs. how long it takes Python to iterate over the internal array:
import matplotlib.pyplot as plt
from simple_benchmark import BenchmarkBuilder
%matplotlib notebook

bench = BenchmarkBuilder()

@bench.add_function()
def string_iteration(s):
    # there is no "a" in the string, so this iterates over the whole string
    return 'a' in s

@bench.add_function()
def python_iteration(s):
    for c in s:
        pass

@bench.add_arguments('string length')
def argument_provider():
    for i in range(2, 20):
        size = 2**i
        yield size, '1'*size

plt.figure()
result = bench.run()
result.plot()

In this benchmark it's ~200 times faster to let Python do the iteration over the string than to iterate over the string with a for loop.

Why do all of them converge for large numbers?
This is actually because the number to string conversion will be dominant there. So for really huge numbers you're essentially just measuring how long it takes to convert that number to a string.
You'll see the difference if you compare the versions that take a number and convert it to a string with the one that take the converted number (I use the functions from another answer here to illustrate that). Left is the number-benchmark and on the right is the benchmark that takes the strings - also the y-axis is the same for both plots:

As you can see the benchmarks for the functions that take the string are significantly faster for large numbers than the ones that take a number and convert them to a string inside. This indicates that the string-conversion is the "bottleneck" for large numbers. For convenience I also included a benchmark only doing the string conversion to the left plot (which becomes significant/dominant for large numbers).
%matplotlib notebook

from simple_benchmark import BenchmarkBuilder
import matplotlib.pyplot as plt
import random

bench1 = BenchmarkBuilder()

@bench1.add_function()
def f1(x):
    return sum(c in '02468' for c in str(x))

@bench1.add_function()
def f2(x):
    return sum([c in '02468' for c in str(x)])

@bench1.add_function()
def f3(x):
    return sum([True for c in str(x) if c in '02468'])

@bench1.add_function()
def f4(x):
    return sum([1 for c in str(x) if c in '02468'])

@bench1.add_function()
def explicit_loop(x):
    count = 0
    for c in str(x):
        if c in '02468':
            count += 1
    return count

@bench1.add_function()
def f5(x):
    s = str(x)
    return sum(s.count(c) for c in '02468')

bench1.add_function()(str)

@bench1.add_arguments(name='number length')
def arg_provider():
    for i in range(2, 15):
        size = 2 ** i
        yield (2**i, int(''.join(str(random.randint(0, 9)) for _ in range(size))))

bench2 = BenchmarkBuilder()

@bench2.add_function()
def f1(x):
    return sum(c in '02468' for c in x)

@bench2.add_function()
def f2(x):
    return sum([c in '02468' for c in x])

@bench2.add_function()
def f3(x):
    return sum([True for c in x if c in '02468'])

@bench2.add_function()
def f4(x):
    return sum([1 for c in x if c in '02468'])

@bench2.add_function()
def explicit_loop(x):
    count = 0
    for c in x:
        if c in '02468':
            count += 1
    return count

@bench2.add_function()
def f5(x):
    return sum(x.count(c) for c in '02468')

@bench2.add_arguments(name='number length')
def arg_provider():
    for i in range(2, 15):
        size = 2 ** i
        yield (2**i, ''.join(str(random.randint(0, 9)) for _ in range(size)))

f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
b1 = bench1.run()
b2 = bench2.run()
b1.plot(ax=ax1)
b2.plot(ax=ax2)
ax1.set_title('Number')
ax2.set_title('String')

A: sum is quite fast, but sum isn't the cause of the slowdown. Three primary factors contribute to the slowdown:

*

*The use of a generator expression causes overhead for constantly pausing and resuming the generator.

*Your generator version adds unconditionally instead of only when the digit is even. This is more expensive when the digit is odd.

*Adding booleans instead of ints prevents sum from using its integer fast path.

Generators offer two primary advantages over list comprehensions: they take a lot less memory, and they can terminate early if not all elements are needed. They are not designed to offer a time advantage in the case where all elements are needed. Suspending and resuming a generator once per element is pretty expensive.
If we replace the genexp with a list comprehension:
In [66]: def f1(x):
   ....:     return sum(c in '02468' for c in str(x))
   ....:
In [67]: def f2(x):
   ....:     return sum([c in '02468' for c in str(x)])
   ....:
In [68]: x = int('1234567890'*50)
In [69]: %timeit f1(x)
10000 loops, best of 5: 52.2 µs per loop
In [70]: %timeit f2(x)
10000 loops, best of 5: 40.5 µs per loop

we see an immediate speedup, at the cost of wasting a bunch of memory on a list.

If you look at your genexp version:
def count_even_digits_spyr03_sum(n):
    return sum(c in "02468" for c in str(n))

you'll see it has no if. It just throws booleans into sum. In constrast, your loop:
def count_even_digits_spyr03_for(n):
    count = 0
    for c in str(n):
        if c in "02468":
            count += 1
    return count

only adds anything if the digit is even.
If we change the f2 defined earlier to also incorporate an if, we see another speedup:
In [71]: def f3(x):
   ....:     return sum([True for c in str(x) if c in '02468'])
   ....:
In [72]: %timeit f3(x)
10000 loops, best of 5: 34.9 µs per loop

f1, identical to your original code, took 52.2 µs, and f2, with just the list comprehension change, took 40.5 µs.

It probably looked pretty awkward using True instead of 1 in f3. I wrote True there because changing it to 1 activates one final speedup. sum has a fast path for integers, but the fast path only activates for objects whose type is exactly int. bool doesn't count. This is the line that checks that items are of type int:
if (PyLong_CheckExact(item)) {

Once we make the final change, changing True to 1:
In [73]: def f4(x):
   ....:     return sum([1 for c in str(x) if c in '02468'])
   ....:
In [74]: %timeit f4(x)
10000 loops, best of 5: 33.3 µs per loop

we see one last small speedup.

So after all that, do we beat the explicit loop?
In [75]: def explicit_loop(x):
   ....:     count = 0
   ....:     for c in str(x):
   ....:         if c in '02468':
   ....:             count += 1
   ....:     return count
   ....:
In [76]: %timeit explicit_loop(x)
10000 loops, best of 5: 32.7 µs per loop

Nope. We've roughly broken even, but we're not beating it. The big remaining problem is the list. Building it is expensive, and sum has to go through the list iterator to retrieve elements, which has its own cost (though I think that part is pretty cheap). Unfortunately, as long as we're going through the test-digits-and-call-sum approach, we don't have any good way to get rid of the list. The explicit loop wins.
Can we go further anyway? Well, we've been trying to bring the sum closer to the explicit loop so far, but if we're stuck with this dumb list, we could diverge from the explicit loop and just call len instead of sum:
def f5(x):
    return len([1 for c in str(x) if c in '02468'])

Testing digits individually isn't the only way we can try to beat the loop, too. Diverging even further from the explicit loop, we can also try str.count. str.count iterates over a string's buffer directly in C, avoiding a lot of wrapper objects and indirection. We need to call it 5 times, making 5 passes over the string, but it still pays off:
def f6(x):
    s = str(x)
    return sum(s.count(c) for c in '02468')

Unfortunately, this is the point when the site I was using for timing stuck me in the "tarpit" for using too many resources, so I had to switch sites. The following timings are not directly comparable with the timings above:
>>> import timeit
>>> def f(x):
...     return sum([1 for c in str(x) if c in '02468'])
...
>>> def g(x):
...     return len([1 for c in str(x) if c in '02468'])
...
>>> def h(x):
...     s = str(x)
...     return sum(s.count(c) for c in '02468')
...
>>> x = int('1234567890'*50)
>>> timeit.timeit(lambda: f(x), number=10000)
0.331528635986615
>>> timeit.timeit(lambda: g(x), number=10000)
0.30292080697836354
>>> timeit.timeit(lambda: h(x), number=10000)
0.15950968803372234
>>> def explicit_loop(x):
...     count = 0
...     for c in str(x):
...         if c in '02468':
...             count += 1
...     return count
...
>>> timeit.timeit(lambda: explicit_loop(x), number=10000)
0.3305045129964128

A: If we use dis.dis(), we can see how the functions actually behave.
count_even_digits_spyr03_for():
  7           0 LOAD_CONST               1 (0)
              3 STORE_FAST               0 (count)

  8           6 SETUP_LOOP              42 (to 51)
              9 LOAD_GLOBAL              0 (str)
             12 LOAD_GLOBAL              1 (n)
             15 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             18 GET_ITER
        >>   19 FOR_ITER                28 (to 50)
             22 STORE_FAST               1 (c)

  9          25 LOAD_FAST                1 (c)
             28 LOAD_CONST               2 ('02468')
             31 COMPARE_OP               6 (in)
             34 POP_JUMP_IF_FALSE       19

 10          37 LOAD_FAST                0 (count)
             40 LOAD_CONST               3 (1)
             43 INPLACE_ADD
             44 STORE_FAST               0 (count)
             47 JUMP_ABSOLUTE           19
        >>   50 POP_BLOCK

 11     >>   51 LOAD_FAST                0 (count)
             54 RETURN_VALUE

We can see that there's only one function call, that's to str() at the beginning:
9 LOAD_GLOBAL              0 (str)
...
15 CALL_FUNCTION            1 (1 positional, 0 keyword pair)

Rest of it is highly optimized code, using jumps, stores, and inplace adding.
What comes to count_even_digits_spyr03_sum():
 14           0 LOAD_GLOBAL              0 (sum)
              3 LOAD_CONST               1 (<code object <genexpr> at 0x10dcc8c90, file "test.py", line 14>)
              6 LOAD_CONST               2 ('count2.<locals>.<genexpr>')
              9 MAKE_FUNCTION            0
             12 LOAD_GLOBAL              1 (str)
             15 LOAD_GLOBAL              2 (n)
             18 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             21 GET_ITER
             22 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             25 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             28 RETURN_VALUE

While I can't perfectly explain the differences, we can clearly see that there are more function calls (probably sum() and in(?)), which make the code run much slower than executing the machine instructions directly.

A: All your functions contain equal number of calls to str(n) (one call) and c in "02468" (for every c in n). Since then I would like to simplify:
import timeit

num = ''.join(str(i % 10) for i in range(1, 10000001))

def count_simple_sum():
    return sum(1 for c in num)

def count_simple_for():
    count = 0
    for c in num:
        count += 1
    return count

print('For Loop Sum:', timeit.timeit(count_simple_for, number=10))
print('Built-in Sum:', timeit.timeit(count_simple_sum, number=10))

sum is still slower:
For Loop Sum: 2.8987821330083534
Built-in Sum: 3.245505138998851

The key difference between these two functions is that in count_simple_for you are iterating only throw num with pure for loop for c in num, but in count_simple_sum your are creating a generator object here (from @Markus Meskanen answer with dis.dis):
  3 LOAD_CONST               1 (<code object <genexpr> at 0x10dcc8c90, file "test.py", line 14>)
  6 LOAD_CONST               2 ('count2.<locals>.<genexpr>')

sum is iterating over this generator object to sum the elements produced, and this generator is iterating over elements in num to produce 1 on each element. Having one more iteration step is expensive because it requires to call generator.__next__() on each element and these calls are placed into try: ... except StopIteration: block which also adds some overhead.


text:
Q: Update observable when array in NGRX store changes I have a need to update an observable when an arry kept in the NGRX store changes. Currently, I use a selector to select the array list, but I'm not sure if this is very efficient code, since I want it to call the next function only any time the selector returns a different array object.
This is my code:
 this.store.select<any[]>(getConnections(Id))
                .takeUntil(this.onDestroy$).subscribe(connections => {
                    this.selectDataStream.next(connections);
                });

Selector:
export const getConnections = (id) => createSelector(selectFinderResults, entities => {
    return entities[id].connections;
});

Reducer:
 case LOAD_INTEGRATOR_CONNECTIONS_SUCCESS: {
          let payload = (action as LoadConnectionsSuccessAction).payload;
          let integratorId = (action as LoadConnectionsSuccessAction).integratorId;

          if (payload) {

              const integratorModel = state.connectorresults[integratorId];

              const updatedstate = {
                  ...state,
                  connectorresults: {
                      ...state.connectorresults,
                      [integratorId]: {
                          ...integratorModel,
                          connections: payload
                      }
                  },
                  searchconnectorresults: {
                      ...state.searchconnectorresults,
                      [integratorId]: {
                          ...integratorModel,
                          connections: payload
                      }
                  }
              };

              return {
                  ...updatedstate
              };
          }

      }

Is this the best way to trigger the next function on the Subject when the connections list changes? I want it to trigger multiple times,  but only when the list changes but it doesn't seem to do that.


text:
Q: Where does mysql register to start itself at boot time? I've got a Macbook Air that is starting mysql on boot.  I've looked in LaunchAgents, LaunchDaemons, .bash_profile and .profile and login items.  It's also not in /etc/rc.local.
Where else can I look?

A: It's in /Library/StartupItems.


text:
Q: RemoteNotifications not registering/not doing anything I have followed this tutorial: http://www.raywenderlich.com/3443/apple-push-notification-services-tutorial-part-12
fully, and after seing that I had issues with my app I even created the same app as he did, the simplest possible but still no luck.
My problem: I do
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
in applicationDidfinishLau... and write the two methods didRegister and didFail but I never get a response back from neither of them (having written some stuff in NSLog in both of them).
I am running of iPhone 4 with wifi only activated and internet's fine... however my internet is very slow here in france but even after waiting a long time still nothing... not even didFail..
thanks for your help

A: I fixed it, because I am in France I have no cellular network enabled and push notifcations do not seem to work, at least for the first time, when cellular data and 3G are disabled in the phone.


text:
Q: How do I paginate specific blog posts on Prismic and Nuxt? I am trying to paginate specific posts on my blog page with two  tags.
According to the Prismic Pagination API, accomplishing that would be as easy as passing the parameter link ?page=1, such as example.com/blog/?page=1, but nothing changes.
How can I query the page option if I cannot use a component instance to change it, which is inside the async function asyncData()?
pages/blog/index.vue:
<template>

{{ title }}

{{ content }}

        <nuxt-link :to="`/blog/${post.uid}`">

{{ Dom.RichText.asText(post.data.title) }}

        </nuxt-link>

      <
      >

</template>

A: In order to get this to work, you're going to need to set up a watchQuery to react to changes.  From the docs:

Watch query strings and execute component methods on change (asyncData, fetch, validate, layout, ...)

// inside page.vue
export default {
  // Watch for $route.query.page to call Component methods (asyncData, fetch, validate, layout, etc.)
  watchQuery: ['page']
}

Now that the page is being watched, you can use NuxtLink to update the query string param.
<nuxt-link :to="`/blog?page=${page_num}`"

And while you do not have access to the component while inside asyncData, you do have access to the context object
export default {
  asyncData (context) {
    return axios.get(`https://my-api/posts?page=${context.query.page}`)
    .then((res) => {
      return { title: res.data.title }
    })
  }
}


text:
Q: Hapi.js with Socket.io -- Where is socket.io.js? I'm trying to hook in socket.io to a Hapi.js server. I've tested the socket.io implementation in vanilla Node.js and everything works great; the server side of the Hapi implementation seems to work fine, but the "/socket.io/socket.io.js" resource is not served to the client.
I've checked the Hapi example, but they only show what to do on the server, and their documentation on the client handshake seems odd: they have a server on port 8000 but say to post for the socket.io handshake to 8080--I've even tried this (which seems wonky and inconsistent with every other socket.io implementation) with no luck.
Thanks!

A: Hapi 8 has introduced some new intricacies so if anyone if revisiting this issue...
On the client, you don't have to use /socket.io/socket.io.js, instead use

*

*a cdn (https://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js)

*or serve the file more specifically (http://yoursite.io/js/socket.io/socket.io.js)

*Better yet, use something like npm/browserify and (https://www.npmjs.com/package/socket.io-client):
var socket = require('socket.io-client')('http://localhost:8080');
Which ever way you choose to include the client side code above
Hapi 8 will allow you to do something cool on your server with chat like this:
server.js
server.connection({ port: 8000, labels: 'app' });
server.connection({ port: 8080, labels: 'chat' });
server.register({
    register: require('./server/plugins/socketIO')
},
function(err) {
    if (err) throw err;
});

/plugins/socketIO/index.js
exports.register = function(server, options, next) {
    var io = require('socket.io').listen(server.select('chat').listener,{log:false});
    io.sockets.on('connection', function (socket) {
        socket.on('someAction', function(name, cb) {
           ...
        });
        ...
   });
}

A: Answer: Load the Client Script from CDN
To answer your specific question: we decided to load the socket.io.js script from the CDN (e.g: http://cdnjs.com/libraries/socket.io ) to make our app load faster. see: index.html#L23
Working Offline ...? (Or Prefer Not to use CDN?)
If loading the client script form CDN is not an option because you are on dial-up or working offline, then use inert and expose the file to your app. e.g:
var Hapi = require('hapi');
var server = new Hapi.Server();

server.connection({
    host: '0.0.0.0',
    port: Number(process.env.PORT || 3000)
});
// uses https://github.com/hapijs/inert to serve static files
server.register(require('inert'), function () {

    server.route([
      { method: 'GET', path: '/', handler: { file: "index.html" } },
      { method: 'GET', path: '/socket.io.js', handler: { file: './node_modules/socket.io-client/socket.io.js' }
    ]);

    server.start(function () {
      console.log('Visit: http://127.0.0.1:'+server.info.port);
    });

});
module.exports = server;

The client file is located in: your_project/node_modules/socket.io-client/socket.io.js
Up-to-Date Solution/Example with End-to-End Tests
If you are still looking for an example of how to use Socket.io in a Hapi.js app we created a complete one (with documentation/comments & end-to-end tests).

see: https://github.com/dwyl/hapi-socketio-redis-chat-example

Its up-to-date with the latest versions of Hapi & Socket.io and uses Redis Pub-Sub to persist and distribute chat messages.

A: You can try to copy the socket.io.js file out from the node.js directory to a well-known directory.

A: I would first confirm that you don't have any firewall issues interfering with the serving of the request.
If a firewall isn't responsible for blocking the request make sure that the src for the javascript file is pointing to the same server and port number, as indicated on the Hapi.createServer line, that you have configured.
If the request reaches the server it will output a debug line in the terminal indicating that it served the file.