问:
Using frontmatter in a markdownfile to query for images in a page query
I'm using GraphQL from within a Gatsby project. I have a set of markdown files for a blog-like section of the site. In the frontmatter of each markdown file, there's an image property.

What I'd like to do is use Gatsby's fine image api to load the image in the frontmatter. When viewing an individual post (the ones created via createPage api), this works just fine because I can provide the frontmatter.image in the context. Here's what that query looks like.

export const pageQuery = graphql`
  query($slug: String!, $image: String) {
    markdownRemark(frontmatter: { slug: { eq: $slug } }) {
      html
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
        slug
        title
        image
      }
    }
    coverImage: file(relativePath: { eq: $image }) {
        childImageSharp {
          fluid(maxWidth: 1440) {
            ...GatsbyImageSharpFluid
          }
        }
      }
  }
`
```

<p>On my index page where I'm displaying all these posts though, I want to display a smaller version of this image. I can get the <code>image</code> from the front matter easy enough, but I'm not sure how to integrate that into the query.</p>

<pre class="lang-js prettyprint-override"><code>export const pageQuery = graphql`
  query {
    allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) {
      edges {
        node {
          id
          excerpt(pruneLength: 250)
          frontmatter {
            date(formatString: "MMMM DD, YYYY")
            slug
            title
            image # <--- want to use this in a file query
          }
        }
      }
    }
  }
`
</code>```

As far as I understand, I can't use string interpolation in a static query in the component where the image is actually used, so I need to get it here in the page query. Is what I'm trying to do possible? Is there a better way to handle this?

答:
This "link" between your frontmatter's image string and an actual image file node (processed with Sharp) is called a foreign-key relationship.

Creating foreign-key relationships in Gatsby

There are two ways of doing this:

Using mappings in gatsby-config.js

Using a GraphQL @link directive through Gatsby's schema customization (from v2.2)

I recommend the second option, since it's a more GraphQL way of doing things, and happens in gatsby-node.js where most node operations are taking place. However, if you're starting out with Gatsby and GraphQL, the first option might be easier to set up.

Implementing the @link directive in gatsby-node.js

In your case, using the @link GraphQL directive, you would probably end up with something like this in your gatsby-node.js:

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions
  const typeDefs = [
    `type MarkdownRemark implements Node { frontmatter: Frontmatter }`,
    `type Frontmatter {
      # you may need to adapt this line depending on the node type and key
      # that you want to create the relationship for
      image: File @link(by: "relativePath")
    }`
  ]
  createTypes(typeDefs)
}
```

<p>If you want to see an example in the wild, check out <code>gatsby-node.js</code> in <code>robinmetral/eaudepoisson.com</code>.</p>

<h1>Query processed images via your frontmatter</h1>

<p>Finally, you'll be able to query like this:</p>

```{
  allMarkdownRemark {
    edges {
      node {
        frontmatter {
          date
          slug
          title
          # image now points to the image file node
          image {
            childImageSharp {
              fluid(maxWidth: 1024) {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
    }
  }
}
```

Body:
I'm using GraphQL from within a Gatsby project. I have a set of markdown files for a blog-like section of the site. In the frontmatter of each markdown file, there's an image property.

What I'd like to do is use Gatsby's fine image api to load the image in the frontmatter. When viewing an individual post (the ones created via createPage api), this works just fine because I can provide the frontmatter.image in the context. Here's what that query looks like.

export const pageQuery = graphql`
  query($slug: String!, $image: String) {
    markdownRemark(frontmatter: { slug: { eq: $slug } }) {
      html
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
        slug
        title
        image
      }
    }
    coverImage: file(relativePath: { eq: $image }) {
        childImageSharp {
          fluid(maxWidth: 1440) {
            ...GatsbyImageSharpFluid
          }
        }
      }
  }
`

On my index page where I'm displaying all these posts though, I want to display a smaller version of this image. I can get the image from the front matter easy enough, but I'm not sure how to integrate that into the query.

export const pageQuery = graphql`
  query {
    allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) {
      edges {
        node {
          id
          excerpt(pruneLength: 250)
          frontmatter {
            date(formatString: "MMMM DD, YYYY")
            slug
            title
            image # <--- want to use this in a file query
          }
        }
      }
    }
  }
`

As far as I understand, I can't use string interpolation in a static query in the component where the image is actually used, so I need to get it here in the page query. Is what I'm trying to do possible? Is there a better way to handle this?

Body:
This "link" between your frontmatter's image string and an actual image file node (processed with Sharp) is called a foreign-key relationship.

Creating foreign-key relationships in Gatsby

There are two ways of doing this:

Using mappings in gatsby-config.js

Using a GraphQL @link directive through Gatsby's schema customization (from v2.2)

I recommend the second option, since it's a more GraphQL way of doing things, and happens in gatsby-node.js where most node operations are taking place. However, if you're starting out with Gatsby and GraphQL, the first option might be easier to set up.

Implementing the @link directive in gatsby-node.js

In your case, using the @link GraphQL directive, you would probably end up with something like this in your gatsby-node.js:

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions
  const typeDefs = [
    `type MarkdownRemark implements Node { frontmatter: Frontmatter }`,
    `type Frontmatter {
      # you may need to adapt this line depending on the node type and key
      # that you want to create the relationship for
      image: File @link(by: "relativePath")
    }`
  ]
  createTypes(typeDefs)
}

If you want to see an example in the wild, check out gatsby-node.js in robinmetral/eaudepoisson.com.

Query processed images via your frontmatter

Finally, you'll be able to query like this:

{
  allMarkdownRemark {
    edges {
      node {
        frontmatter {
          date
          slug
          title
          # image now points to the image file node
          image {
            childImageSharp {
              fluid(maxWidth: 1024) {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
    }
  }
}


来源: stackexchange

问:
SQL database in android , Index -1 requested with size 0
I have been working on an android app which requires to retrieve some information from the SQL database. Initially I was trying to do that form a function named getRemainingAmount() in databaseHelper1 class but that caused an error

```<code>FATAL EXCEPTION: main Process: com.carrot.wallet, PID: 30591 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.carrot.wallet/com.carrot.wallet.MainActivity}: android.view.InflateException: Binary XML file line #10 in com.carrot.wallet:layout/activity_main: Binary XML file line #10 in com.carrot.wallet:layout/activity_main: Error inflating class fragment at
</code>```

After that when I tried to ritrive data from the addTransaction class then I started getting the folowing error:

```<code>2020-05-30 09:25:12.946 11239-11239/com.carrot.wallet E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.carrot.wallet, PID: 11239
    android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
        at android.database.AbstractCursor.checkPosition(AbstractCursor.java:468)
        at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
        at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
        at com.carrot.wallet.AddTransaction$4.onClick(AddTransaction.java:102)
        at android.view.View.performClick(View.java:6294)
        at android.view.View$PerformClick.run(View.java:24770)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
</code>```

This is my databaseHeleper1 class which contains the function getRemainingAmount()

```<code>
package com.carrot.wallet.Database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import androidx.annotation.Nullable;

public class DatabaseHelper1 extends SQLiteOpenHelper {

    private static final int version = 3;
    private static final String name = "YEAR_DETAILS";
    private static final String COL0 = "YEAR";
    private static final String COL1 = "MONTH";
    private static final String COL2 = "SPENT";
    private static final String COL3 = "REMAINING";
    private static final String TAG = "Database Helper 1";

    public DatabaseHelper1(@Nullable Context context) {
        super(context, name, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(TAG , "Database 1 is being created");
        String create_table = "CREATE TABLE "+name+"("+
                COL0+" INTEGER, "+
                COL1+" TEXT, "+
                COL2+" DOUBLE, "+
                COL3+" DOUBLE);";
        db.execSQL(create_table);
    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+name);
        onCreate(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    private boolean createMonth(String month , String year){
        Log.d(TAG , "month row is being created");
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL0 , year);
        contentValues.put(COL1 , month);
        contentValues.put(COL2 , 0.0);
        contentValues.put(COL3 , 0.0);
        long result = db.insert(name,null , contentValues);
        return result != -1;
    }

    public boolean spentChange(String month , String year , Double newAmount){
        Log.d(TAG , "spent amount is being changed");
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COL2 , newAmount);
        long result = db.update(name, values , "MONTH = ? AND YEAR = ?", new String[]{month , year});
        return  result != -1;
    }

    public boolean remainingChange(String month ,String year, Double newAmount){
        Log.d(TAG , "Remaining amount is being changed");
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues =new ContentValues();
        contentValues.put(COL3 , newAmount);
        long result = db.update(name , contentValues , "MONTH = ? AND YEAR = ?" , new String[]{month , year});
        return result != -1;
    }

    public void checkExistance(String month, String year){
        Log.d(TAG , "Checking if month already exits");
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cur =  database.query(name , null , "MONTH = ? AND YEAR = ?" , new String[]{month , year} , null , null , null);
        System.out.println(cur);
        if(cur.getCount() <= 0) {
            boolean b = createMonth(month , year);
            if(b)
                Log.d(TAG , "checkExistance: failed to create month");
            else
                Log.d(TAG, "checkExistance: month created successfully");
        }
    }

    public Cursor getdata(){
        SQLiteDatabase db = this.getReadableDatabase();
        String query = "SELECT * FROM YEAR_DETAILS;";
        return db.rawQuery(query , null);
    }

    public Cursor getSpentAmount(String month , String year){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM YEAR_DETAILS WHERE MONTH = " + month+ " AND YEAR = "+year;
        return db.rawQuery(query , null);
    }

    public Cursor getRemainingAmount(String month , String year){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cur =  db.query(name , new String[]{COL3} , "MONTH = ? AND YEAR = ?" , new String[]{month , year} , null , null , null);
        return cur;
    }

}
</code>```

AddTransaction class (where i am retrieving the data)

```<code>
package com.carrot.wallet;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.carrot.wallet.ArrayListClasses.add_transaction_data;
import com.carrot.wallet.Database.DatabaseHelper1;
import com.carrot.wallet.Database.DatabaseHelper2;
import com.carrot.wallet.recyclerview.at_btn_adapter;

import java.util.ArrayList;
import java.util.Calendar;

import com.carrot.wallet.recyclerview.onClickRecyclerButtion;

public class AddTransaction extends AppCompatActivity {

    int type1 ;
    int type2;
    double amount;
    ArrayList<add_transaction_data> data;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_transaction);
        ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.hide();
        populateList();

        final ImageButton cancel = findViewById(R.id.at_btn_cancel);
        final EditText EditAmount = findViewById(R.id.at_enter_amount);
        ImageButton save = findViewById(R.id.at_btn_save);
        ImageButton income = findViewById(R.id.at_btn_income);
        ImageButton loan = findViewById(R.id.at_btn_loan);
        RecyclerView recyclerView = findViewById(R.id.at_btn_recyclerview);

        recyclerView.setLayoutManager(new GridLayoutManager(this , 5));
        recyclerView.setAdapter(new at_btn_adapter(data, new onClickRecyclerButtion() {
            @Override
            public void onPositionClicked(int position) {
                type1 = 2;
                type2 = position;

            }
        }));

        income.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type1 = 1;
                type2 = -1;
            }
        });

        loan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type1 = 1;
                type2 = -2;
            }
        });

        context = this;
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("it is  all cool here");
                DatabaseHelper1 databaseHelper1 = new DatabaseHelper1(getBaseContext());
                DatabaseHelper2 databaseHelper2 = new DatabaseHelper2(getBaseContext());
                double amount = Double.parseDouble(EditAmount.getText().toString());
                System.out.println(amount);
                Calendar c = Calendar.getInstance();
                int year = c.get(Calendar.YEAR);
                int month = c.get(Calendar.MONTH);
                String m = changeString(month);
                System.out.println(type1);
                String mRamount = "ds";
                if(type1 == 1){

                    SQLiteDatabase database = databaseHelper1.getReadableDatabase();
                    String ca = "SELECT * FROM YEAR_DETAILS WHERE MONTH = " + month+ " AND YEAR = "+year;
                    Cursor cursor = database.rawQuery(ca , null);
                    mRamount = cursor.getString(1);
                    System.out.println(mRamount);//printing amount.
                }
                startActivity(new Intent(AddTransaction.this , MainActivity.class));
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(AddTransaction.this , MainActivity.class));
            }
        });

    }

    void populateList(){
        data = new ArrayList<>();
        data.add(new add_transaction_data("Add" , R.drawable.ic_add_black_24dp));
        data.add(new add_transaction_data("Shopping" , R.drawable.at_ic_shopping));
        data.add(new add_transaction_data("Food" , R.drawable.at_ic_food));
        data.add(new add_transaction_data("Traveling" , R.drawable.at_ic_travel));
        data.add(new add_transaction_data("Education" , R.drawable.at_ic_education));
        data.add(new add_transaction_data("Energy" , R.drawable.at_ic_energy));
        data.add(new add_transaction_data("House" , R.drawable.at_ic_home));
        data.add(new add_transaction_data("Fitness" , R.drawable.at_ic_sports));
        data.add(new add_transaction_data("Personal" , R.drawable.at_ic_personal));
        data.add(new add_transaction_data("Other" , R.drawable.at_ic_other));
    }

    String changeString(int month){
        String m;
        switch (month){
            case 0:
                m = "January";
                break;
            case 1:
                m = "Feburary";
                break;
            case 2:
                m = "March";
                break;
            case 3:
                m = "April";
                break;
            case 4:
                m = "May";
                break;
            case 5:
                m = "June";
                break;
            case 6:
                m = "July";
                break;
            case 7:
                m = "August";
                break;
            case 8:
                m = "September";
                break;
            case 9:
                m = "October";
                break;
            case 10:
                m = "November";
                break;
            case 11:
                m = "December";
                break;
            default:
                m = " ";

        }
        return m;
    }

}

</code>```

activity_main xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/fragNavHost"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/mobile_navigation" />

    <me.ibrahimsn.lib.SmoothBottomBar
        android:elevation="30dp"
        android:id="@+id/bottom_nav"
        android:layout_width="match_parent"
        app:iconTint="@color/colorPrimary"
        app:indicatorColor="#EFEFEF"
        app:iconTintActive="@color/colorPrimaryDark"
        app:textColor="@color/colorPrimaryDark"
        android:layout_height="70dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_navigation_bar"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Can someone help me understand what is causing these two errrors.

答:
in your getData() method you have double semicolon

```<code>String query = "SELECT * FROM YEAR_DETAILS;";
</code>```

try changing it to

```<code>String query = "SELECT * FROM YEAR_DETAILS"
</code>```

and I suggest you migrate to Room library

ContentLicense: CC BY-SA 4.0

Body:
I have been working on an android app which requires to retrieve some information from the SQL database. Initially I was trying to do that form a function named getRemainingAmount() in databaseHelper1 class but that caused an error

FATAL EXCEPTION: main Process: com.carrot.wallet, PID: 30591 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.carrot.wallet/com.carrot.wallet.MainActivity}: android.view.InflateException: Binary XML file line #10 in com.carrot.wallet:layout/activity_main: Binary XML file line #10 in com.carrot.wallet:layout/activity_main: Error inflating class fragment at

After that when I tried to ritrive data from the addTransaction class then I started getting the folowing error:

2020-05-30 09:25:12.946 11239-11239/com.carrot.wallet E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.carrot.wallet, PID: 11239
    android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
        at android.database.AbstractCursor.checkPosition(AbstractCursor.java:468)
        at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
        at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
        at com.carrot.wallet.AddTransaction$4.onClick(AddTransaction.java:102)
        at android.view.View.performClick(View.java:6294)
        at android.view.View$PerformClick.run(View.java:24770)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

This is my databaseHeleper1 class which contains the function getRemainingAmount()

package com.carrot.wallet.Database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import androidx.annotation.Nullable;

public class DatabaseHelper1 extends SQLiteOpenHelper {

    private static final int version = 3;
    private static final String name = "YEAR_DETAILS";
    private static final String COL0 = "YEAR";
    private static final String COL1 = "MONTH";
    private static final String COL2 = "SPENT";
    private static final String COL3 = "REMAINING";
    private static final String TAG = "Database Helper 1";

    public DatabaseHelper1(@Nullable Context context) {
        super(context, name, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(TAG , "Database 1 is being created");
        String create_table = "CREATE TABLE "+name+"("+
                COL0+" INTEGER, "+
                COL1+" TEXT, "+
                COL2+" DOUBLE, "+
                COL3+" DOUBLE);";
        db.execSQL(create_table);
    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+name);
        onCreate(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    private boolean createMonth(String month , String year){
        Log.d(TAG , "month row is being created");
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL0 , year);
        contentValues.put(COL1 , month);
        contentValues.put(COL2 , 0.0);
        contentValues.put(COL3 , 0.0);
        long result = db.insert(name,null , contentValues);
        return result != -1;
    }

    public boolean spentChange(String month , String year , Double newAmount){
        Log.d(TAG , "spent amount is being changed");
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COL2 , newAmount);
        long result = db.update(name, values , "MONTH = ? AND YEAR = ?", new String[]{month , year});
        return  result != -1;
    }

    public boolean remainingChange(String month ,String year, Double newAmount){
        Log.d(TAG , "Remaining amount is being changed");
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues =new ContentValues();
        contentValues.put(COL3 , newAmount);
        long result = db.update(name , contentValues , "MONTH = ? AND YEAR = ?" , new String[]{month , year});
        return result != -1;
    }

    public void checkExistance(String month, String year){
        Log.d(TAG , "Checking if month already exits");
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cur =  database.query(name , null , "MONTH = ? AND YEAR = ?" , new String[]{month , year} , null , null , null);
        System.out.println(cur);
        if(cur.getCount() <= 0) {
            boolean b = createMonth(month , year);
            if(b)
                Log.d(TAG , "checkExistance: failed to create month");
            else
                Log.d(TAG, "checkExistance: month created successfully");
        }
    }

    public Cursor getdata(){
        SQLiteDatabase db = this.getReadableDatabase();
        String query = "SELECT * FROM YEAR_DETAILS;";
        return db.rawQuery(query , null);
    }

    public Cursor getSpentAmount(String month , String year){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM YEAR_DETAILS WHERE MONTH = " + month+ " AND YEAR = "+year;
        return db.rawQuery(query , null);
    }

    public Cursor getRemainingAmount(String month , String year){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cur =  db.query(name , new String[]{COL3} , "MONTH = ? AND YEAR = ?" , new String[]{month , year} , null , null , null);
        return cur;
    }

}

AddTransaction class (where i am retrieving the data)

package com.carrot.wallet;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.carrot.wallet.ArrayListClasses.add_transaction_data;
import com.carrot.wallet.Database.DatabaseHelper1;
import com.carrot.wallet.Database.DatabaseHelper2;
import com.carrot.wallet.recyclerview.at_btn_adapter;

import java.util.ArrayList;
import java.util.Calendar;

import com.carrot.wallet.recyclerview.onClickRecyclerButtion;

public class AddTransaction extends AppCompatActivity {

    int type1 ;
    int type2;
    double amount;
    ArrayList<add_transaction_data> data;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_transaction);
        ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.hide();
        populateList();

        final ImageButton cancel = findViewById(R.id.at_btn_cancel);
        final EditText EditAmount = findViewById(R.id.at_enter_amount);
        ImageButton save = findViewById(R.id.at_btn_save);
        ImageButton income = findViewById(R.id.at_btn_income);
        ImageButton loan = findViewById(R.id.at_btn_loan);
        RecyclerView recyclerView = findViewById(R.id.at_btn_recyclerview);

        recyclerView.setLayoutManager(new GridLayoutManager(this , 5));
        recyclerView.setAdapter(new at_btn_adapter(data, new onClickRecyclerButtion() {
            @Override
            public void onPositionClicked(int position) {
                type1 = 2;
                type2 = position;

            }
        }));

        income.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type1 = 1;
                type2 = -1;
            }
        });

        loan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type1 = 1;
                type2 = -2;
            }
        });

        context = this;
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("it is  all cool here");
                DatabaseHelper1 databaseHelper1 = new DatabaseHelper1(getBaseContext());
                DatabaseHelper2 databaseHelper2 = new DatabaseHelper2(getBaseContext());
                double amount = Double.parseDouble(EditAmount.getText().toString());
                System.out.println(amount);
                Calendar c = Calendar.getInstance();
                int year = c.get(Calendar.YEAR);
                int month = c.get(Calendar.MONTH);
                String m = changeString(month);
                System.out.println(type1);
                String mRamount = "ds";
                if(type1 == 1){

                    SQLiteDatabase database = databaseHelper1.getReadableDatabase();
                    String ca = "SELECT * FROM YEAR_DETAILS WHERE MONTH = " + month+ " AND YEAR = "+year;
                    Cursor cursor = database.rawQuery(ca , null);
                    mRamount = cursor.getString(1);
                    System.out.println(mRamount);//printing amount.
                }
                startActivity(new Intent(AddTransaction.this , MainActivity.class));
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(AddTransaction.this , MainActivity.class));
            }
        });

    }

    void populateList(){
        data = new ArrayList<>();
        data.add(new add_transaction_data("Add" , R.drawable.ic_add_black_24dp));
        data.add(new add_transaction_data("Shopping" , R.drawable.at_ic_shopping));
        data.add(new add_transaction_data("Food" , R.drawable.at_ic_food));
        data.add(new add_transaction_data("Traveling" , R.drawable.at_ic_travel));
        data.add(new add_transaction_data("Education" , R.drawable.at_ic_education));
        data.add(new add_transaction_data("Energy" , R.drawable.at_ic_energy));
        data.add(new add_transaction_data("House" , R.drawable.at_ic_home));
        data.add(new add_transaction_data("Fitness" , R.drawable.at_ic_sports));
        data.add(new add_transaction_data("Personal" , R.drawable.at_ic_personal));
        data.add(new add_transaction_data("Other" , R.drawable.at_ic_other));
    }

    String changeString(int month){
        String m;
        switch (month){
            case 0:
                m = "January";
                break;
            case 1:
                m = "Feburary";
                break;
            case 2:
                m = "March";
                break;
            case 3:
                m = "April";
                break;
            case 4:
                m = "May";
                break;
            case 5:
                m = "June";
                break;
            case 6:
                m = "July";
                break;
            case 7:
                m = "August";
                break;
            case 8:
                m = "September";
                break;
            case 9:
                m = "October";
                break;
            case 10:
                m = "November";
                break;
            case 11:
                m = "December";
                break;
            default:
                m = " ";

        }
        return m;
    }

}

activity_main xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/fragNavHost"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/mobile_navigation" />

    <me.ibrahimsn.lib.SmoothBottomBar
        android:elevation="30dp"
        android:id="@+id/bottom_nav"
        android:layout_width="match_parent"
        app:iconTint="@color/colorPrimary"
        app:indicatorColor="#EFEFEF"
        app:iconTintActive="@color/colorPrimaryDark"
        app:textColor="@color/colorPrimaryDark"
        android:layout_height="70dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_navigation_bar"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Can someone help me understand what is causing these two errrors.

Body:
in your getData() method you have double semicolon

String query = "SELECT * FROM YEAR_DETAILS;";

try changing it to

String query = "SELECT * FROM YEAR_DETAILS"

and I suggest you migrate to Room library


问:
assigning the returning function
I'm new to javascript, and I saw code like this.

```<code><button onclick="this.onClickDoSmth">Click me</button>

onClickDoSmth = () => {
let a = this.clicked();
a();
}

clicked = () => {
console.log("test");
}
</code>```

What's the difference of replacing the expression for "a" to

```<code>onClickDoSmth = () => {
this.clicked();
}
</code>```

答:
First a correction is required. It should be let a = this.clicked; instead of let a = this.clicked(). The former means you're assigning the returning function to the variable a and executing it later with a(). So if you do this way, there's no difference.

```<code>onClickDoSmth = () => {
    let a = this.clicked; //This has to be corrected
    a();
    }

    clicked = () => {
    console.log("test");
    }
</code>```

Title: assigning the returning function

Body:
I'm new to javascript, and I saw code like this.

<button onclick="this.onClickDoSmth">Click me</button>

onClickDoSmth = () => {
let a = this.clicked();
a();
}

clicked = () => {
console.log("test");
}

What's the difference of replacing the expression for "a" to

onClickDoSmth = () => {
this.clicked();
}

Body:
First a correction is required. It should be let a = this.clicked; instead of let a = this.clicked(). The former means you're assigning the returning function to the variable a and executing it later with a(). So if you do this way, there's no difference.

onClickDoSmth = () => {
    let a = this.clicked; //This has to be corrected
    a();
    }

    clicked = () => {
    console.log("test");
    }


问:
Validation failed for query for method public, spring jpa?
I am creating an api to query from the DB and return the result.

This is the request

```<code>@RequestMapping(value = "/config", params = { "appCode", "appVersion" }, method = RequestMethod.GET)
public List<AppConfig> getConfig(@RequestParam(value = "appCode", required = true) String appCode,
        @RequestParam(value = "appVersion", required = true) String appVersion) {
    return configRepository.findByCodeAndVersion(appCode, appCode);
}
</code>```

The table class

```<code>@Entity
@Table(name = "app_config")
@EntityListeners(AuditingEntityListener.class)
public class AppConfig {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(columnDefinition = "serial")
private long id;
@Column(name = "app_code", nullable = false)
private String appCode;
@Column(name = "app_name", nullable = false)
private String appName;
@Column(name = "api_url", nullable = true)
private String apiUrl;
@Column(name = "db_name", nullable = true)
private String dbName;
@Column(name = "app_version", nullable = false)
private String appVersion;
}
</code>```

The repository where I am having custom query

```<code>@Repository
public interface AppConfigRepository extends CrudRepository<AppConfig, Long> {

@Query("SELECT n FROM AppConfig WHERE n.appCode = ?1 and n.appVersion = ?2")
List<AppConfig> findByCodeAndVersion(String appCode, String appVersion);
}
</code>```

On running the application I get the exception

```<code>Validation failed for query for method public abstract java.util.List com.api.repository.AppConfigRepository.findByCodeAndVersion(java.lang.String,java.lang.String)!
</code>```

答:
You have to add the alias n after the entity name AppConfig in the query, it should be like:

```<code>@Query("SELECT n FROM AppConfig n WHERE n.appCode = ?1 and n.appVersion = ?2")
List<AppConfig> findByCodeAndVersion(String appCode, String appVersion);

</code>```

You can also use named parameter inside the query string like this:

```<code>@Query("SELECT n FROM AppConfig n WHERE n.appCode = :appCode and n.appVersion = :appVersion")
List<AppConfig> findByCodeAndVersion(String appCode, String appVersion);
</code>```

And a query like this can be handled by Spring data query methods, just make sure to rename the method to use the field names of the entity:

```<code>List<AppConfig> findByAppCodeAndAppVersion(String appCode, String appVersion);
</code>```

Body:
I am creating an api to query from the DB and return the result.

This is the request

@RequestMapping(value = "/config", params = { "appCode", "appVersion" }, method = RequestMethod.GET)
public List<AppConfig> getConfig(@RequestParam(value = "appCode", required = true) String appCode,
        @RequestParam(value = "appVersion", required = true) String appVersion) {
    return configRepository.findByCodeAndVersion(appCode, appCode);
}

The table class

@Entity
@Table(name = "app_config")
@EntityListeners(AuditingEntityListener.class)
public class AppConfig {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(columnDefinition = "serial")
private long id;
@Column(name = "app_code", nullable = false)
private String appCode;
@Column(name = "app_name", nullable = false)
private String appName;
@Column(name = "api_url", nullable = true)
private String apiUrl;
@Column(name = "db_name", nullable = true)
private String dbName;
@Column(name = "app_version", nullable = false)
private String appVersion;
}

The repository where I am having custom query

@Repository
public interface AppConfigRepository extends CrudRepository<AppConfig, Long> {

@Query("SELECT n FROM AppConfig WHERE n.appCode = ?1 and n.appVersion = ?2")
List<AppConfig> findByCodeAndVersion(String appCode, String appVersion);
}

On running the application I get the exception

Validation failed for query for method public abstract java.util.List com.api.repository.AppConfigRepository.findByCodeAndVersion(java.lang.String,java.lang.String)!

Body:
You have to add the alias n after the entity name AppConfig in the query, it should be like:

@Query("SELECT n FROM AppConfig n WHERE n.appCode = ?1 and n.appVersion = ?2")
List<AppConfig> findByCodeAndVersion(String appCode, String appVersion);

You can also use named parameter inside the query string like this:

@Query("SELECT n FROM AppConfig n WHERE n.appCode = :appCode and n.appVersion = :appVersion")
List<AppConfig> findByCodeAndVersion(String appCode, String appVersion);

And a query like this can be handled by Spring data query methods, just make sure to rename the method to use the field names of the entity:

List<AppConfig> findByAppCodeAndAppVersion(String appCode, String appVersion);


问:
How can I use an excel file for data testing on a mac
I am trying to use an excel file that has data such as first name, last name, hire date, department, etc. to populate fields in a web browser. Is there something on a mac that can do this.

I have seen something like:

```<code>require 'win32ole'
require 'excel'
</code>```

The 'win32ole' gem only seems to work on Windows.
And I can't find the 'excel' gem anywhere.
Anything known would be great.

答:
You're looking for the spreadsheet gem:

http://spreadsheet.rubyforge.org/

That can read Excel files.

Alternatively, you could convert your spreadsheets to CSV and then use the standard CSV libraries.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use an excel file that has data such as first name, last name, hire date, department, etc. to populate fields in a web browser. Is there something on a mac that can do this.

I have seen something like:

require 'win32ole'
require 'excel'

The 'win32ole' gem only seems to work on Windows.
And I can't find the 'excel' gem anywhere.
Anything known would be great.


问:
Asp.net core mvc view Razor issue with return result on cascading dropdownlist Ajax
I have small projetc asp.net core mvc when i created view Razor with dropdownlist cascading i used Jquer Ajax to get the result of first dropdownlist by call the action of controller i have nothing on the second dropdownlist i test the action of the controller  I Get JsonResult: result such as

```<code>[{"id_local":1,"metrage":150.0,"prix_vente":950000.0,"numAct":1,"activite":null,"type_local":"Commerce","num_Centre":1,"centre_Commercial":null},{"id_local":4,"metrage":190.0,"prix_vente":850000.0,"numAct":1,"activite":null,"type_local":"Commerce","num_Centre":1,"centre_Commercial":null}]
</code>```

view Razor in below my code:

```<code>@{
    ViewBag.Title =
        "Vue  Razor ";
}
<script src="~/lib/jquery/dist/jquery.js"></script>
<h2>Controle_WCS</h2>
<div class="row">
    <div class="form-group">
        @Html.DropDownList("ddlCentre", ViewBag.Centre_Commercial as List<SelectListItem>,
                           " -- Sélectionnez Centre Commercial --", new { @class = "form-control" })
        <br />
        @Html.DropDownList("ddlLocal", new List<SelectListItem>(),
                           " -- Sélectionnez Local --", new { @class = "form-control" })

    </div>
</div>
@section scripts {

    <script>
        $(document).ready(function () {
        $("#ddlCentre").change(function () {
            //$("#ddlLocal").empty().append('<option>-- Sélectionnez Local --</option>');
            var id = $(this).val();
            alert('ID'+id);
            if (id != "")
        $.ajax({
            url:"@Url.Action("GetLocalsList")",
            type:"POST",
            data:'Num_Centre='+id,
            cache: false,
            contentType: "application/json;charset=utf-8",
            // data:"id_local="+id,
            dataType:"json",
            success:function (data) {
                var json = $.parseJSON(data); // create an object with the key of the array
                alert(json);
                console.log(data);
            $.each(data, function (index, row) {
                        $("#ddlLocal").append("<option value='" + row.id + "'>" + row.id + "</option>")
                    });
                   },
            error: function (req, status, error) {
                alert(error);
            }
        });
            });
        });

    </script>

    }
</code>```

Action Controller :

```<code> [HttpGet]
        public JsonResult GetLocalsList(int id)
        {
            List<Local> lstLocal= new List<Local>();
            lstLocal = objLocal.GetLocalsData(id).ToList();

            return Json(lstLocal);

        }
</code>```

Thanks in advance

答:
Your GetLocalsList method is GET. So in the AJAX request, you have to change type to GET. The input parameter of GetLocalsList method is 'id', so you will have to change the data to 'id='+id. And when you are appending JSON result to ddlCentre, you are using row.id but your JsonResult seems to be id_local.

I made those changes to the AJAX request and tried a sample project. It is working for me.

```<code>$.ajax({
            url:"@Url.Action("GetLocalsList")",
            type:"GET",
            data:'id='+id,
            cache: false,
            contentType: "application/json;charset=utf-8",
            // data:"id_local="+id,
            dataType:"json",
            success:function (data) {
                console.log(data);
            $.each(data, function (index, row) {
                $("#ddlLocal").append("<option value='" + row.id_local + "'>" + row.id_local + "</option>")
            });
            },
            error: function (req, status, error) {
                alert(error);
            }
        });
</code>```

Body:
I have small projetc asp.net core mvc when i created view Razor with dropdownlist cascading i used Jquer Ajax to get the result of first dropdownlist by call the action of controller i have nothing on the second dropdownlist i test the action of the controller  I Get JsonResult: result such as

[{"id_local":1,"metrage":150.0,"prix_vente":950000.0,"numAct":1,"activite":null,"type_local":"Commerce","num_Centre":1,"centre_Commercial":null},{"id_local":4,"metrage":190.0,"prix_vente":850000.0,"numAct":1,"activite":null,"type_local":"Commerce","num_Centre":1,"centre_Commercial":null}]

view Razor in below my code:

@{
    ViewBag.Title =
        "Vue  Razor ";
}

Controle_WCS

        @Html.DropDownList("ddlCentre", ViewBag.Centre_Commercial as List<SelectListItem>,
                           " -- Sélectionnez Centre Commercial --", new { @class = "form-control" })

        @Html.DropDownList("ddlLocal", new List<SelectListItem>(),
                           " -- Sélectionnez Local --", new { @class = "form-control" })

@section scripts {

    }

Action Controller :

 [HttpGet]
        public JsonResult GetLocalsList(int id)
        {
            List<Local> lstLocal= new List<Local>();
            lstLocal = objLocal.GetLocalsData(id).ToList();

            return Json(lstLocal);

        }

Thanks in advance

Body:
Your GetLocalsList method is GET. So in the AJAX request, you have to change type to GET. The input parameter of GetLocalsList method is 'id', so you will have to change the data to 'id='+id. And when you are appending JSON result to ddlCentre, you are using row.id but your JsonResult seems to be id_local.

I made those changes to the AJAX request and tried a sample project. It is working for me.

$.ajax({
            url:"@Url.Action("GetLocalsList")",
            type:"GET",
            data:'id='+id,
            cache: false,
            contentType: "application/json;charset=utf-8",
            // data:"id_local="+id,
            dataType:"json",
            success:function (data) {
                console.log(data);
            $.each(data, function (index, row) {
                $("#ddlLocal").append("<option value='" + row.id_local + "'>" + row.id_local + "</option>")
            });
            },
            error: function (req, status, error) {
                alert(error);
            }
        });


问:
FCM InvalidRegistration
I developing an app in which I send notifications using FCM REST API.
But when I send the notification I always get the same error InvalidRegistration.
When I googled the problem I knew that the problem is in the registration token format. so I wanna make sure if I'm sending the right token.
what I do is I authenticate users and the auth request returns.

{
    "kind": "identitytoolkit#VerifyPasswordResponse",
    "localId": "sQFWGMTlRvd8XgbxC9T6UyyKKNW2",
    "email": "01026525200@zeal.com",
    "displayName": "",
    "idToken": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjljYjU0Zjc4OTczNTU4NjU5ZTMxNGFkYzhjMTRkYzVmNjUyMTZmZmQifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vemVhbC1kZXYiLCJhdWQiOiJ6ZWFsLWRldiIsImF1dGhfdGltZSI6MTQ5ODI5ODUxNywidXNlcl9pZCI6InNRRldHTVRsUnZkOFhnYnhDOVQ2VXl5S0tOVzIiLCJzdWIiOiJzUUZXR01UbFJ2ZDhYZ2J4QzlUNlV5eUtLTlcyIiwiaWF0IjoxNDk4Mjk4NTE3LCJleHAiOjE0OTgzMDIxMTcsImVtYWlsIjoiMDEwMjY1MjUyMDBAemVhbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImZpcmViYXNlIjp7ImlkZW50aXRpZXMiOnsiZW1haWwiOlsiMDEwMjY1MjUyMDBAemVhbC5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwYXNzd29yZCJ9fQ.Uuuy7566wziSjp001WD_OwG2OdrsggwbuftCnsdpKTicVKArdayEVGq4-pBNsQOZKYNrhpTmiv86d_lbGeeuu9LNJX0xwjvslGA2EffdS1Vaf_OaBrwlp9rllTdXsIEp5wSpPUX_jSa2dck0lpU5bNPVAPjfw6_q4kmKkf6pMzjKLogGvJmtRJOuA5LMFIbJGrs57QIJfbDbghvG-etYAorgRIXwM1Xfg2eYD5s7sItwv0h9hitkH2R_Fy1yJuml51nbA6GT93YyE05QYowfmrymbfYOCYtOsfdkdL6iU0CLH8I0Cw7sQhGIx1iuQl1Wv5aNN2Z4QAiKERpt2VJ_Hw",
    "registered": true,
    "refreshToken": "ACXxpGEB6dkyDsmRVkaXrTshqAhQPZCSVC8kofhypeWDP473zIIOZQpAF_cMEQP6CaOB2PnyDiYX3cJdYAcG2Wcpyzcpij3s2TauyiaKqfYTy76EtvHDGZrW-FyHXc9fX1sRZWbW4uhslrEZ_tYy2axolmc7g3ZPfWAidqHjEjIzqS2moJTM5lXuvxBRlpZQcNXQFOGtr8E8",
    "expiresIn": "3600"
}
```

so I use the idToken to send the notification. Is that right or I'm doing something wrong.

答: I have also faced this issue..the problem was my device token column length in database table. when I change it to 255, it works. </p>

Title: FCM InvalidRegistration

Body:
I developing an app in which I send notifications using FCM REST API.
But when I send the notification I always get the same error InvalidRegistration.
When I googled the problem I knew that the problem is in the registration token format. so I wanna make sure if I'm sending the right token.
what I do is I authenticate users and the auth request returns.

{
    "kind": "identitytoolkit#VerifyPasswordResponse",
    "localId": "sQFWGMTlRvd8XgbxC9T6UyyKKNW2",
    "email": "01026525200@zeal.com",
    "displayName": "",
    "idToken": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjljYjU0Zjc4OTczNTU4NjU5ZTMxNGFkYzhjMTRkYzVmNjUyMTZmZmQifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vemVhbC1kZXYiLCJhdWQiOiJ6ZWFsLWRldiIsImF1dGhfdGltZSI6MTQ5ODI5ODUxNywidXNlcl9pZCI6InNRRldHTVRsUnZkOFhnYnhDOVQ2VXl5S0tOVzIiLCJzdWIiOiJzUUZXR01UbFJ2ZDhYZ2J4QzlUNlV5eUtLTlcyIiwiaWF0IjoxNDk4Mjk4NTE3LCJleHAiOjE0OTgzMDIxMTcsImVtYWlsIjoiMDEwMjY1MjUyMDBAemVhbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImZpcmViYXNlIjp7ImlkZW50aXRpZXMiOnsiZW1haWwiOlsiMDEwMjY1MjUyMDBAemVhbC5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwYXNzd29yZCJ9fQ.Uuuy7566wziSjp001WD_OwG2OdrsggwbuftCnsdpKTicVKArdayEVGq4-pBNsQOZKYNrhpTmiv86d_lbGeeuu9LNJX0xwjvslGA2EffdS1Vaf_OaBrwlp9rllTdXsIEp5wSpPUX_jSa2dck0lpU5bNPVAPjfw6_q4kmKkf6pMzjKLogGvJmtRJOuA5LMFIbJGrs57QIJfbDbghvG-etYAorgRIXwM1Xfg2eYD5s7sItwv0h9hitkH2R_Fy1yJuml51nbA6GT93YyE05QYowfmrymbfYOCYtOsfdkdL6iU0CLH8I0Cw7sQhGIx1iuQl1Wv5aNN2Z4QAiKERpt2VJ_Hw",
    "registered": true,
    "refreshToken": "ACXxpGEB6dkyDsmRVkaXrTshqAhQPZCSVC8kofhypeWDP473zIIOZQpAF_cMEQP6CaOB2PnyDiYX3cJdYAcG2Wcpyzcpij3s2TauyiaKqfYTy76EtvHDGZrW-FyHXc9fX1sRZWbW4uhslrEZ_tYy2axolmc7g3ZPfWAidqHjEjIzqS2moJTM5lXuvxBRlpZQcNXQFOGtr8E8",
    "expiresIn": "3600"
}

so I use the idToken to send the notification. Is that right or I'm doing something wrong.


问:
How to make label text in jointjs elements not selectable?
i'm trying to find a solution for the following. When I drag a link between elements the label text inside the elements get selected for some reason.

Lets say I have an element A with the property A.attr("body/magnet", "active"); set and A.attr("label/text", "some text"); When I create a link from that element by clicking and dragging the label text gets selected on elements the link goes through.

This seems a little bit random though as sometimes all the labels in the graph gets selected when dragging the link.

Is there a way to make the label text not to be selectable?

答:
From the answer above the links will still be selected, so you can put css on you #paper is or canvas like so </p>

<pre class="lang-css prettyprint-override"><code>#paper {
 -webkit-user-select: none;
 -moz-user-select: none;
 -ms-user-select: none;
  user-select: none;
}
</code>```

Body:
From the answer above the links will still be selected, so you can put css on you #paper is or canvas like so

#paper {
 -webkit-user-select: none;
 -moz-user-select: none;
 -ms-user-select: none;
  user-select: none;
}


答:
try this :

```<code>@Query("SELECT FROM AppConfig n WHERE n.appCode = :x and n.appVersion = :y")
List<AppConfig> findByCodeAndVersion(@Param("x")String appCode,@Param("y") String appVersion);
</code>```

or you can use directly the method:

```<code>List<AppConfig> findByAppCodeAndAppVersion(String appCode,String appVersion);
</code>```

Title: Validation failed for query for method public, spring jpa?

Body:
try this :

@Query("SELECT FROM AppConfig n WHERE n.appCode = :x and n.appVersion = :y")
List<AppConfig> findByCodeAndVersion(@Param("x")String appCode,@Param("y") String appVersion);

or you can use directly the method:

List<AppConfig> findByAppCodeAndAppVersion(String appCode,String appVersion);


问:
How do I install tensorflow_text?
I'm trying to reproduce the notebook on Google Multilingual Universal Encoder. However by downloading the necessary libraries as tensorflow_text:

```<code>%%capture
#@title Setup Environment
# Install the latest Tensorflow version.
!pip3 install tensorflow_text
</code>```

or

```<code>!python -m pip install tensorflow_text
</code>```

And I get in jupyter:

```<code>---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-48-399dd4157896> in <module>
      8 import tensorflow.compat.v2 as tf
      9 import tensorflow_hub as hub
---> 10 from tensorflow_text import SentencepieceTokenizer
     11 import sklearn.metrics.pairwise
     12

ModuleNotFoundError: No module named 'tensorflow_text'
</code>```

I tried to install it with python -m pip install tensorflow-text, but it gave me:

```<code>(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>python -m pip install tensorflow-text
Collecting tensorflow-text
  ERROR: Could not find a version that satisfies the requirement tensorflow-text (from versions: none)
ERROR: No matching distribution found for tensorflow-text
WARNING: You are using pip version 19.2.3, however version 20.0.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
</code>```

I also tried conda install -c conda-forge tensorflow

```<code>(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment> conda install -c conda-forge tensorflow
Collecting package metadata (current_repodata.json): done
Solving environment: done

# All requested packages already installed.

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>set "KERAS_BACKEND="

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>python C:\Users\antoi\.conda\envs\seg_env\etc\keras\load_config.py  1>temp.txt

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>set /p KERAS_BACKEND= 0<temp.txt

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>del temp.txt

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>python -c "import keras"  1>nul 2>&1

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if errorlevel 1 (
ver  1>nul
 set "KERAS_BACKEND=theano"
 python -c "import keras"  1>nul 2>&1
)

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>SET DISTUTILS_USE_SDK=1

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>SET MSSdk=1

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>SET platform=

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>IF /I [AMD64] == [amd64] set "platform=true"

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>IF /I [] == [amd64] set "platform=true"

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if defined platform (set "VSREGKEY=HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0" )  ELSE (set "VSREGKEY=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\14.0" )

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>for /F "skip=2 tokens=2,*" %A in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0" /v InstallDir') do SET "VSINSTALLDIR=%B"
ERROR: The system was unable to find the specified registry key or value.

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if "" == "" (set "VSINSTALLDIR=" )

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if "" == "" (
ECHO "WARNING: Did not find VS in registry or in VS140COMNTOOLS env var - your compiler may not work"
 GOTO End
)
"WARNING: Did not find VS in registry or in VS140COMNTOOLS env var - your compiler may not work"
The system cannot find the batch label specified - End
</code>```

Versions

```<code>(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation>python -m pip list | findstr tensorflow
tensorflow           2.1.0
tensorflow-estimator 2.1.0
</code>```

And python:

```<code>(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation>python
Python 3.6.7 (default, Dec  6 2019, 07:03:06) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
</code>```

I'm on Windows 10

答:
This is a known issue with the packages provided by the TensorFlow-Text project that apparently re-surfaces from time to time. See Issue 89 and Issue 291 in their GitHub.

You can either wait until this is resolved (again), or try to build the package from source.

Title: How do I install tensorflow_text?

Body:
I'm trying to reproduce the notebook on Google Multilingual Universal Encoder. However by downloading the necessary libraries as tensorflow_text:

%%capture
#@title Setup Environment
# Install the latest Tensorflow version.
!pip3 install tensorflow_text

or

!python -m pip install tensorflow_text

And I get in jupyter:

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-48-399dd4157896> in <module>
      8 import tensorflow.compat.v2 as tf
      9 import tensorflow_hub as hub
---> 10 from tensorflow_text import SentencepieceTokenizer
     11 import sklearn.metrics.pairwise
     12

ModuleNotFoundError: No module named 'tensorflow_text'

I tried to install it with python -m pip install tensorflow-text, but it gave me:

(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>python -m pip install tensorflow-text
Collecting tensorflow-text
  ERROR: Could not find a version that satisfies the requirement tensorflow-text (from versions: none)
ERROR: No matching distribution found for tensorflow-text
WARNING: You are using pip version 19.2.3, however version 20.0.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

I also tried conda install -c conda-forge tensorflow

(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment> conda install -c conda-forge tensorflow
Collecting package metadata (current_repodata.json): done
Solving environment: done

# All requested packages already installed.

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>set "KERAS_BACKEND="

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>python C:\Users\antoi\.conda\envs\seg_env\etc\keras\load_config.py  1>temp.txt

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>set /p KERAS_BACKEND= 0<temp.txt

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>del temp.txt

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>python -c "import keras"  1>nul 2>&1

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if errorlevel 1 (
ver  1>nul
 set "KERAS_BACKEND=theano"
 python -c "import keras"  1>nul 2>&1
)

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>SET DISTUTILS_USE_SDK=1

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>SET MSSdk=1

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>SET platform=

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>IF /I [AMD64] == [amd64] set "platform=true"

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>IF /I [] == [amd64] set "platform=true"

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if defined platform (set "VSREGKEY=HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0" )  ELSE (set "VSREGKEY=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\14.0" )

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>for /F "skip=2 tokens=2,*" %A in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0" /v InstallDir') do SET "VSINSTALLDIR=%B"
ERROR: The system was unable to find the specified registry key or value.

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if "" == "" (set "VSINSTALLDIR=" )

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if "" == "" (
ECHO "WARNING: Did not find VS in registry or in VS140COMNTOOLS env var - your compiler may not work"
 GOTO End
)
"WARNING: Did not find VS in registry or in VS140COMNTOOLS env var - your compiler may not work"
The system cannot find the batch label specified - End

Versions

(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation>python -m pip list | findstr tensorflow
tensorflow           2.1.0
tensorflow-estimator 2.1.0

And python:

(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation>python
Python 3.6.7 (default, Dec  6 2019, 07:03:06) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

I'm on Windows 10


问:
Apply single colors for all bars in seaborn countplot
Following codes give different colors for each category

```<code>import seaborn as sns
sns.set(style="darkgrid")
titanic = sns.load_dataset("titanic")
ax = sns.countplot(x="class", data=titanic)
</code>```

how to make all of them have the same color?

答:
documentation:

seaborn.countplot(x=None, y=None, hue=None, data=None, order=None,
  hue_order=None, orient=None, color=None, palette=None,
  saturation=0.75, dodge=True, ax=None, **kwargs)

Function takes color argument, change it to change color.

Body:
Following codes give different colors for each category

import seaborn as sns
sns.set(style="darkgrid")
titanic = sns.load_dataset("titanic")
ax = sns.countplot(x="class", data=titanic)

how to make all of them have the same color?


问:
Using a for loop with geom_point to add points to a existing ggplot object
I'm quite new to R and am trying to create a map of my country with points overlayed on it (representing cities, with points sized by population). I've already created the map with geom_sf() using lat, long boundaries, and have stored it as map.

This is an example of the code I'm trying to replicate, where cities is a df with columns state, pop, lat and long (with no missing values):

```<code>map <- map +
  geom_point(aes(x = cities$long[1], y = cities$lat[1], size = cities$pop[1])) +
  geom_point(aes(x = cities$long[2], y = cities$lat[2], size = cities$pop[2])) +
  geom_point(aes(x = cities$long[3], y = cities$lat[3], size = cities$pop[3])) +
  geom_point(aes(x = cities$long[4], y = cities$lat[4], size = cities$pop[4])) +
  geom_point(aes(x = cities$long[5], y = cities$lat[5], size = cities$pop[5]))
</code>```

This is the loop that I thought would work, but it seems to be overwriting the geom_point with each iteration as my map just ends up with the last point. When I output a map with each iteration, it just shows the most recent point.

```<code>or(i in 1:nrow(cities)){
  if(!is.na(cities$lat[i]) && !is.na(cities$long[i])){
    map <- map +
      geom_point(aes(x = cities$long[i], y = cities$lat[i], size = cities$pop[i]))
  }
}
</code>```

I hope that I've provided enough info - please let me know if I haven't. Thank you!

答:
There's no need to do this in a loop.

Can't reproduce without your data, but assuming that your cities object looks like:

```<code>cities <- data.frame(name = ..,
                     pop = ..,
                     lat = ...,
                     long = ...)
</code>```

and given that your base map is a geom_sf object, this is all the code you'd need.

```<code>cities_spatial <- cities %>%
  st_as_sf(coords = c("lat","long"), crs = 4326)

map <- map +
  geom_sf(data = cities_spatial, aes(size = pop))
</code>```

The option crs = 4326 is to ensure that your data is projected in WGS84 which is standard for lat/long coordinates. If your base map map is projected with a different projection you may need to adjust it to match your lat/long data as well, using sf::st_transform(...)

Body:
I'm quite new to R and am trying to create a map of my country with points overlayed on it (representing cities, with points sized by population). I've already created the map with geom_sf() using lat, long boundaries, and have stored it as map.

This is an example of the code I'm trying to replicate, where cities is a df with columns state, pop, lat and long (with no missing values):

map <- map +
  geom_point(aes(x = cities$long[1], y = cities$lat[1], size = cities$pop[1])) +
  geom_point(aes(x = cities$long[2], y = cities$lat[2], size = cities$pop[2])) +
  geom_point(aes(x = cities$long[3], y = cities$lat[3], size = cities$pop[3])) +
  geom_point(aes(x = cities$long[4], y = cities$lat[4], size = cities$pop[4])) +
  geom_point(aes(x = cities$long[5], y = cities$lat[5], size = cities$pop[5]))

This is the loop that I thought would work, but it seems to be overwriting the geom_point with each iteration as my map just ends up with the last point. When I output a map with each iteration, it just shows the most recent point.

or(i in 1:nrow(cities)){
  if(!is.na(cities$lat[i]) && !is.na(cities$long[i])){
    map <- map +
      geom_point(aes(x = cities$long[i], y = cities$lat[i], size = cities$pop[i]))
  }
}

I hope that I've provided enough info - please let me know if I haven't. Thank you!

Body:
There's no need to do this in a loop.

Can't reproduce without your data, but assuming that your cities object looks like:

cities <- data.frame(name = ..,
                     pop = ..,
                     lat = ...,
                     long = ...)

and given that your base map is a geom_sf object, this is all the code you'd need.

cities_spatial <- cities %>%
  st_as_sf(coords = c("lat","long"), crs = 4326)

map <- map +
  geom_sf(data = cities_spatial, aes(size = pop))

The option crs = 4326 is to ensure that your data is projected in WGS84 which is standard for lat/long coordinates. If your base map map is projected with a different projection you may need to adjust it to match your lat/long data as well, using sf::st_transform(...)


问:
Is it a good practice to close my connection after Sequelize operations?
currently I'm designing an app on top of Sequelize using NodeJS/TypeScript, and I'm wondering if it can cause performance issues not closing a connection.

For instance, in a micro service, I need data from 1 entity.

const resolver = async (,,{db}) => {
  const entity1 = await db.models.Entity1.findOne()
  return entity1
}
```

<p>Is it required to close the connection after having called <code>findOne</code>?</p>

<p>My understanding is that the following config defines a number of concurrent connections and idle is a parameter making the connection manager closing the connection of idle ones:</p>

<pre class="lang-js prettyprint-override"><code>module.exports = {
  development: {
    host: 'db.sqlite',
    dialect: 'sqlite',
    pool: {
        max:5,
        min:0,
        idle:10000
    }
  },
  test: {
    host: 'test.sqlite',
    dialect: 'sqlite',
    pool: {
        max:5,
        min:0,
        idle:10000
    }
  }
}
</code>```

Any advice is welcome

答:
Sequelize maintains an internal database connection pool, that's what the pool parameters are for, so this isn't necessary. Each call actually borrows a connection temporarily and then returns it to the pool when done.

Closing that connection manually may poison the pool and cause performance issues.

Body:
currently I'm designing an app on top of Sequelize using NodeJS/TypeScript, and I'm wondering if it can cause performance issues not closing a connection.

For instance, in a micro service, I need data from 1 entity.

const resolver = async (,,{db}) => {
  const entity1 = await db.models.Entity1.findOne()
  return entity1
}

Is it required to close the connection after having called findOne?

My understanding is that the following config defines a number of concurrent connections and idle is a parameter making the connection manager closing the connection of idle ones:

module.exports = {
  development: {
    host: 'db.sqlite',
    dialect: 'sqlite',
    pool: {
        max:5,
        min:0,
        idle:10000
    }
  },
  test: {
    host: 'test.sqlite',
    dialect: 'sqlite',
    pool: {
        max:5,
        min:0,
        idle:10000
    }
  }
}

Any advice is welcome


问:
Cannot Hide/Supress OOB Model-Driven Apps (Customer Service Hub, Sales Hub, etc)
I am trying to suppress or hide the OOB model-driven apps from all users except System Admins.  I have navigated to Settings -> my Apps -> App (ellipses) -> Manage Roles and removed all roles except admin and customizer.

I have assigned my test user a single role, the role has "Read" permission on Model-driven App in Security Role -> Customization tab.  If I remove read permission the user see NO model-driven Apps, with Read permission the user sees ALL model-driven app, even though roles are restricted.

Any guidance would be much obliged.

答:
The security on what Apps are visible to Users are not done in the security role directly.

You have to go to your app and select security roles which can than see the app.

See https://learn.microsoft.com/en-us/powerapps/maker/model-driven-apps/share-model-driven-app


问:
Can Haskell programs be represented as Lisp S-expressions?
This would be useful for genetic programming, which usually use a Lisp subset as representation for programs.

I've found something called Liskell (Lisp syntax, Haskell inside) on the web, but the links are broken and I can't find the paper on it...

答:
The obvious answer is "yes" -- unsurprising given that S-expressions were intended as a simple & uniform representation of parsed code.  The thing is that languages like Haskell or ML tend to have some problems with that.  I once did something similar to OCaml (abused CamlP4 and wrote some function that translates the P4 AST into some sexpr-like representation), and the fun begins when you run into similar kinds of AST nodes that have different types because they're not really the same...  For example, there's function application, and there's a similar form that is used in patterns, and yet another form that is used in type expressions.

My guess is that trying to do genetic programming this way is likely to suffer from too much junk programs that don't have any meaning.  But that's unsurprising too for any statically typed language -- a dynamically typed language will allow more junk in.  Comparing the two worlds WRT to genetic programming might be interesting for reasons beyond the AI...


问:
Access denied for property "vendor.camera.aux.packagelist"
The application runs but when i try to use the camera only a disturbed grey screen appears and the logs tab gives me two errors:

```<code>E/libc: Access denied finding property "vendor.camera.aux.packagelist"
        Access denied finding property "vendor.camera.aux.packagelist2"
</code>```

AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
```

<p>build.gradle (Module:app)</p>

```apply plugin: 'com.android.application'
android {
    compileSdkVersion 28
    defaultConfig {
        minSdkVersion 22
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
}
```

<p>build.gradle(Project:camera)</p>

```buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.0'
    }
}
allprojects {
    repositories {
        google()
        jcenter()

    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

```

答:
I too faced same error while implementing video capture option, this in my case due to missing Storage and Camera permissions.

Resolved using below code

```<code>  if ((checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) || (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))  {
                Log.d(TAG, "No camera and storage permission");
                requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_CODE);
            }
</code>```

Body:
The application runs but when i try to use the camera only a disturbed grey screen appears and the logs tab gives me two errors:

E/libc: Access denied finding property "vendor.camera.aux.packagelist"
        Access denied finding property "vendor.camera.aux.packagelist2"

AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

build.gradle (Module:app)

apply plugin: 'com.android.application'
android {
    compileSdkVersion 28
    defaultConfig {
        minSdkVersion 22
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
}

build.gradle(Project:camera)

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.0'
    }
}
allprojects {
    repositories {
        google()
        jcenter()

    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

Body:
I too faced same error while implementing video capture option, this in my case due to missing Storage and Camera permissions.

Resolved using below code

  if ((checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) || (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))  {
                Log.d(TAG, "No camera and storage permission");
                requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_CODE);
            }


问:
Laravel 5.3 check if notification is read
I am using database notifications in Laravel 5.3. Is there a function or property to check if the notification is read or not when looping through the user's notifications. Thanks in advance</p>

答:
In the newer versions of laravel (6.2+), you can get all, read or unread notifications as collection. So, to get all read notifications, you can do something like:</p>

```<code>@foreach (Auth::user()->readNotifications as $notification)
    // process $notification
@endforeach
</code>```

Body:
In the newer versions of laravel (6.2+), you can get all, read or unread notifications as collection. So, to get all read notifications, you can do something like:

@foreach (Auth::user()->readNotifications as $notification)
    // process $notification
@endforeach


问:
Is it possible to use a different gcc version inside a Conda environment?
I have to install a package (spatial-correlation-sampler) which calls for gcc: >=5.3. On my system (Linux, remote server), gcc version is 4.8.5, and a Conda virtual environment uses the same version. Is it possible to use a different version within the virtual environment?

答:
Is it possible to use a different gcc version inside a Conda environment?

Probably yes, except if you (or your Conda environment) needs or uses some GCC plugin. These plugins are specific to a particular version of GCC: a plugin coded for GCC 4.8 (such as my old GCC MELT) won't work with GCC 6. But see also this draft report on Bismon (which might become a successor to GCC MELT).

On Linux/x86-64, a C code compiled with GCC 4.8 would be compatible with the same code compiled with GCC 10, since both follow the same ABI and calling conventions.

For C++ code compiled with GCC, there could be subtle ABI or calling conventions incompatibilities (related to name mangling and exceptions).

Be also aware that Python 2 and Python 3 have different foreign function interfaces. Read chapters related to extending and embedding the Python interpreter.

See also the Program Library HowTo, Advanced Linux Programming and C++ dlopen mini-HowTo and Linux Assembly HowTo and of course Linux From Scratch.

On my system (Linux, remote server), gcc version is 4.8.5

GCC is Free Software.

You are allowed to compile and install a more recent GCC from its source code on your system. An installed GCC 4.8 can be use to build e.g. a GCC 8 from its source code (then installed into /usr/local/bin/gcc, then you just configure wisely your $PATH variable). You could even  do that with the unsupported GCC 5.

On recent Debian or Ubuntu you would install dependencies with something like sudo aptitude build-dep g++ and you might also want to use Docker. You may need to download several gigabytes.

Some companies or freelancers are able (for a fee) to compile a GCC tailored for your system. I know AdaCore, but there are many others corporations or freelancers selling support on GCC. Contact me by email for more.

PS. On a powerful AMD Threadripper 2970WX desktop, I just built GCC 10.1 with make -j8 and  g++ 9.3 on Debian/Sid in 10:21.38 elapsed time,  requiring less than 7 Gbytes of disk space  (for both GCC source code and object files). Of course, I disabled the compiler bootstrap. You could do the same thru ssh to your system (it could take an hour or two of elapsed time, because a Linux VPS has less cores so you might need to just make -j2).


问:
How can I track each "step" of a program in PHP?
For example, in my error_log, it says something like:

```<code>Error... require, include, a_function, another_function
</code>```

Basically it tracks each step of the program. I want to implement something like this for debugging purposes. How do I "track" the execution of the program in PHP?

答: The debug_backtrace / debug_print_backtrace functions :)</p>

Body:
For example, in my error_log, it says something like:

Error... require, include, a_function, another_function

Basically it tracks each step of the program. I want to implement something like this for debugging purposes. How do I "track" the execution of the program in PHP?


问:
Keras model taking too long to train
So I have the following model for sentiment analysis (using pre trained word embeddings):

And as visible, I have a pre trained embedding matrix and only about 500k trainable parameters. So why does it take a whole eternity to train this model? The batch size is 128 and number of epochs is 25. And the ETA for first epoch is about 10 minutes. I haven't even completed that.

Just to mention, I am not using CUDA or anything. I don't think I have a GPU enabled Tensorflow. And I'm willing to do anything to increase the speed. And I have Tensorflow 2.1.0.

答: And here's the answer I am not using CUDA or anything. Training on CPU is much slower than on GPU. If you don't have high-performance enough video card, you can use several services such as Google Colab or Kaggle

Title: Keras model taking too long to train


问:
Unable to create Laravel project in PhpStorm
I am trying to create a new Laravel project in PhpStorm using the below steps.

Chosen option "Download composer from composer.org".

In the package list i have selected laravel/laravel with default version.

Create project.

After loading all the files it displays a short message in the bottom right corner of the IDE "Failed to run composer create-project" and I am unable to see that first page that comes when we run server.

I have also tried it using terminal by going into xampp/htdocs in VSCode and then running the below command

```<code>composer new laravel/installer
Changed current directory to /Users/abhishekabhishek/.composer
</code>```

But it gives me the following error

```<code>The "https://repo.packagist.org/packages.json" file could not be downloaded: failed to open stream: Operation timed out
Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info
</code>```

I have no idea what is going on. Can anyone please help me resolve this issue. I am running this on Mac, there is nothing that I came across that can resolve this problem.

答:
Step 1:

Download composer

Step 2:

Download the Laravel installer using Composer.

```<code>composer global require laravel/installer
</code>```

Step 3:

```<code>laravel new blog
</code>```

Step 4:

```<code>php artisan serve
</code>```

This command will start a development server at http://localhost:8000

Tips:

After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run.

```<code>sudo chmod 777 -Rf /folder/bootstrapdirectoryorcachedirectory
</code>```

You dont need any VSCode or PHP Storm to do that.

Body:
I am trying to create a new Laravel project in PhpStorm using the below steps.

Chosen option "Download composer from composer.org".

In the package list i have selected laravel/laravel with default version.

Create project.

After loading all the files it displays a short message in the bottom right corner of the IDE "Failed to run composer create-project" and I am unable to see that first page that comes when we run server.

I have also tried it using terminal by going into xampp/htdocs in VSCode and then running the below command

composer new laravel/installer
Changed current directory to /Users/abhishekabhishek/.composer

But it gives me the following error

The "https://repo.packagist.org/packages.json" file could not be downloaded: failed to open stream: Operation timed out
Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info

I have no idea what is going on. Can anyone please help me resolve this issue. I am running this on Mac, there is nothing that I came across that can resolve this problem.

Body:
Step 1:

Download composer

Step 2:

Download the Laravel installer using Composer.

composer global require laravel/installer

Step 3:

laravel new blog

Step 4:

php artisan serve

This command will start a development server at http://localhost:8000

Tips:

After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run.

sudo chmod 777 -Rf /folder/bootstrapdirectoryorcachedirectory

You dont need any VSCode or PHP Storm to do that.


问:
How can I get the ID of the last INSERTed row using PDO with SQL Server?
Under other circumstances I might be tempted to use

```<code>$result = mssql_query("INSERT INTO table (fields) VALUES (data);
                       SELECT CAST(scope_identity() AS int)");
</code>```

but as I will be inserting user-submitted data, I want to continue to use PDO, which returns an empty array.

Unfortunately, I'm running PHP on a Linux server and using dblib to interface with Microsoft SQL Server, which doesn't support PDO::lastInsertID().

Please help!

Update to include code example

Here's the code I'm using: col1 is a field of type int identity and col2 is a datetime with a default of getdate().

```<code>//  Connect to db with PDO
$pdo = new PDO( 'dblib:host=' . $host . ';dbname=' . $database . ';', $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) );
//  Connect to db with MSSQL
$sql = mssql_connect( $host, $username, $password );
mssql_select_db( $database, $sql );
//  Create SQL statement
$query = "INSERT INTO [table] ( col3, col4, col5 )
          VALUES ( 'str1', 'str2', 'str3' );
          SELECT SCOPE_IDENTITY() AS theID;";
//  Run with MSSQL
echo "Using MSSQL...\n";
$result = mssql_query( $query );
$the_id = mssql_result( $result, 0, 'theID' );
echo "Query OK. Returned ID is " . $the_id . "\n";
// Run with PDO
echo "\nUsing PDO...\n";
$stmt = $pdo->query( $query );
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
print_r( $result );
</code>```

And this is what was displayed:

```<code>Using MSSQL...
Query OK. Returned ID is 149

Using PDO...
Array
(
)
</code>```

I would love to find out that I'd done something stupid, rather than come up against a horrible dead end :)

答: Maybe you are getting two rowsets returned.  Try adding SET NOCOUNT ON; to eliminate the INSERT's rowset, or use $stmt->nextRowset if your driver supports it.</p>

Body:
Under other circumstances I might be tempted to use

$result = mssql_query("INSERT INTO table (fields) VALUES (data);
                       SELECT CAST(scope_identity() AS int)");

but as I will be inserting user-submitted data, I want to continue to use PDO, which returns an empty array.

Unfortunately, I'm running PHP on a Linux server and using dblib to interface with Microsoft SQL Server, which doesn't support PDO::lastInsertID().

Please help!

Update to include code example

Here's the code I'm using: col1 is a field of type int identity and col2 is a datetime with a default of getdate().

//  Connect to db with PDO
$pdo = new PDO( 'dblib:host=' . $host . ';dbname=' . $database . ';', $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) );
//  Connect to db with MSSQL
$sql = mssql_connect( $host, $username, $password );
mssql_select_db( $database, $sql );
//  Create SQL statement
$query = "INSERT INTO [table] ( col3, col4, col5 )
          VALUES ( 'str1', 'str2', 'str3' );
          SELECT SCOPE_IDENTITY() AS theID;";
//  Run with MSSQL
echo "Using MSSQL...\n";
$result = mssql_query( $query );
$the_id = mssql_result( $result, 0, 'theID' );
echo "Query OK. Returned ID is " . $the_id . "\n";
// Run with PDO
echo "\nUsing PDO...\n";
$stmt = $pdo->query( $query );
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
print_r( $result );

And this is what was displayed:

Using MSSQL...
Query OK. Returned ID is 149

Using PDO...
Array
(
)

I would love to find out that I'd done something stupid, rather than come up against a horrible dead end :)


问:
Node js Empty object when executing a function from a required file
so i have this news api js file i can run and execute the api and see a full result when consoling

const NewsAPI = require('newsapi');
const newsapi = new NewsAPI('2a59HIDDEN1bd60');

  newsapi.v2.sources({
    category: 'technology',
    language: 'en',
    country: 'us'
  }).then( response => {
  console.log(response)
    return response
  });```
</div>
</div>
</p>

<p>but when i require the above code in another file its coming as empty object</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const passport = require("passport");
const newsapiapi = require("../services/newsApi");

module.exports = (app) => {

  app.get(
    "/auth/google",
    passport.authenticate("google", {
      scope: ["profile", "email"],
    })
  );

  app.get("/auth/google/callback", passport.authenticate("google"));
  app.get('/api/current_user',(req,res)=>{
      res.send(req.user);
  })
  app.get('/api/newsapi',(req,res)=>{
    var resp =  newsapiapi
    console.log("-----------",resp)

    res.send("hello")

})
};</code>```

In other words the object is empty when executing under  app.get('/api/newsapi') but i get the data with no issue on the first code where the api lies

答:
This is because you haven't exported anything from the api file.
Try this

```<code>module.exports = newsapi.v2.sources({
    category: 'technology',
    language: 'en',
    country: 'us'
  }).then( response => {
  console.log(response)
    return response
  });
</code>```

This would export the function promise and then you can consume it by resolving it in the main file. Like

```<code>app.get('/api/newsapi', async (req,res)=>{
    var resp = await newsapiapi()
    console.log("-----------",resp)

    res.send("hello")

})
</code>```

Or if you don't want to use async-await, you can use promise chaining like

```<code>app.get('/api/newsapi',(req,res)=>{
    var resp =  newsapiapi().then(resp => {
    console.log("-----------",resp)
    res.send("hello")
   })

})
</code>```

Body:
so i have this news api js file i can run and execute the api and see a full result when consoling

const NewsAPI = require('newsapi');
const newsapi = new NewsAPI('2a59HIDDEN1bd60');

  newsapi.v2.sources({
    category: 'technology',
    language: 'en',
    country: 'us'
  }).then( response => {
  console.log(response)
    return response
  });

but when i require the above code in another file its coming as empty object

const passport = require("passport");
const newsapiapi = require("../services/newsApi");

module.exports = (app) => {

  app.get(
    "/auth/google",
    passport.authenticate("google", {
      scope: ["profile", "email"],
    })
  );

  app.get("/auth/google/callback", passport.authenticate("google"));
  app.get('/api/current_user',(req,res)=>{
      res.send(req.user);
  })
  app.get('/api/newsapi',(req,res)=>{
    var resp =  newsapiapi
    console.log("-----------",resp)

    res.send("hello")

})
};

In other words the object is empty when executing under  app.get('/api/newsapi') but i get the data with no issue on the first code where the api lies

Body:
This is because you haven't exported anything from the api file.
Try this

module.exports = newsapi.v2.sources({
    category: 'technology',
    language: 'en',
    country: 'us'
  }).then( response => {
  console.log(response)
    return response
  });

This would export the function promise and then you can consume it by resolving it in the main file. Like

app.get('/api/newsapi', async (req,res)=>{
    var resp = await newsapiapi()
    console.log("-----------",resp)

    res.send("hello")

})

Or if you don't want to use async-await, you can use promise chaining like

app.get('/api/newsapi',(req,res)=>{
    var resp =  newsapiapi().then(resp => {
    console.log("-----------",resp)
    res.send("hello")
   })

})


问:
Sql get latest n rows in sql whose sum is greater than or equal to a value
I have a table  of fb_data of following data

```<code>id sessions created_at

1   25     2020-05-28 12:00:00

2   30     2020-05-28 13:00:00

3   24     2020-05-29 14:00:00
</code>```

I want to get latest rows whose sum creates greater than 40 . For e.g  id 2 and 3 creates the sum greater than 40   . Then I want only 2 and 3 rows excluding the rows 1

答:
If you are using MySQL 8+, then honestly the easiest way is to use analytic functions:

```<code>WITH cte AS (
    SELECT *, SUM(sessions) OVER (ORDER BY created_at DESC) sum_sessions
    FROM yourTable
)

SELECT t1.id, t1.sessions, t1.created_at
FROM yourTable t1
WHERE t1.created_at >= (SELECT MAX(t2.created_at) FROM cte t2
                        WHERE t2.sum_sessions > 40);
</code>```

Here is what the intermediate result defined in the CTE looks like:

```<code>id | sessions | created_at          | sum_sessions
1  | 25       | 2020-05-28 12:00:00 | 79
2  | 30       | 2020-05-28 13:00:00 | 54   <-- most recent date having required sum
3  | 24       | 2020-05-29 14:00:00 | 24
</code>```

The subquery used in the WHERE clause of my query finds the greatest date on which a cumulative sum starting with the most recent date in the table was greater than 40.  Then, we simply select as few records going up to that date.

Body:
I have a table  of fb_data of following data

id sessions created_at

1   25     2020-05-28 12:00:00

2   30     2020-05-28 13:00:00

3   24     2020-05-29 14:00:00

I want to get latest rows whose sum creates greater than 40 . For e.g  id 2 and 3 creates the sum greater than 40   . Then I want only 2 and 3 rows excluding the rows 1

Body:
If you are using MySQL 8+, then honestly the easiest way is to use analytic functions:

WITH cte AS (
    SELECT *, SUM(sessions) OVER (ORDER BY created_at DESC) sum_sessions
    FROM yourTable
)

SELECT t1.id, t1.sessions, t1.created_at
FROM yourTable t1
WHERE t1.created_at >= (SELECT MAX(t2.created_at) FROM cte t2
                        WHERE t2.sum_sessions > 40);

Here is what the intermediate result defined in the CTE looks like:

id | sessions | created_at          | sum_sessions
1  | 25       | 2020-05-28 12:00:00 | 79
2  | 30       | 2020-05-28 13:00:00 | 54   <-- most recent date having required sum
3  | 24       | 2020-05-29 14:00:00 | 24

The subquery used in the WHERE clause of my query finds the greatest date on which a cumulative sum starting with the most recent date in the table was greater than 40.  Then, we simply select as few records going up to that date.