问:
get Lat Lang from a place_id returned by autocomplete place api
I am searching the place in my apps using the google autocomplete place api and now I want to get latitude and longitude of the place that i have searched. How to get latitude and longitude from the result returned by autocomplete place api by google in android?</p>

答:
do provide Place.Field.LAT_LNG to get the latitude and longitude for the place.

```<code> autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID,
 Place.Field.NAME,Place.Field.LAT_LNG));
</code>```

then get LatLng

```<code>LatLng destinationLatLng = place.getLatLng();
</code>```

and can see through toast

```<code> destlat = destinationLatLng.latitude;
 destLon = destinationLatLng.longitude;
 Toast.makeText(getApplicationContext(), "" + destlat + ',' + destLon, Toast.LENGTH_LONG).show();
</code>```

Body:
do provide Place.Field.LAT_LNG to get the latitude and longitude for the place.

 autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID,
 Place.Field.NAME,Place.Field.LAT_LNG));

then get LatLng

LatLng destinationLatLng = place.getLatLng();

and can see through toast

 destlat = destinationLatLng.latitude;
 destLon = destinationLatLng.longitude;
 Toast.makeText(getApplicationContext(), "" + destlat + ',' + destLon, Toast.LENGTH_LONG).show();


来源: stackexchange

问:
Regroup button events in one event
I use 6 different buttons doing practically the same thing.

private void VisaCreaDoc_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.CREADOC);
}

private void VisaTravaux_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.TRAVAUX);

}

private void VisaRemiseOuvrageIR_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.REMISEOUVRIR);
}

private void VisaRemiseOuvrageExpl_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.REMISEOUVREXPL);
}

private void VisaMES_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.MISEENSERVICE);
}

private void VisaEncodageArchivage_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.ENCODAGEARCHIVAGE);
```

As you can see, they're using a function from the ViewModel with a different parameter.

Is there any way to regroup the 6 button events to have only one and kind of pass the parameter directly in the XAML call or something similar to avoid having the "code duplication" ?

答:
Not sure if you like it "better" but you can check which button was clicked inside the handler:

```<code>void HandleButton_Click(object sender, RoutetEventArgs e)
{
    if (sender is Button b)
    {
        if (b == VisaCreaDoc) # VisaCreaDoc is the given name of your button instace in xaml
            ViewModel.ValidateItem(InfosPosteViewModel.CREADOC);
        else if (b == VisaTravaux)
            ViewModel.ValidateItem(InfosPosteViewModel.TRAVAUX);
        else if (...) // etc.
    }
}
</code>```

You can spice it up with a switch pattern matching to get rid of the if / else if / else if / ... chains.

ContentLicense: CC BY-SA 4.0

Title: Regroup button events in one event

Body:
I use 6 different buttons doing practically the same thing.

private void VisaCreaDoc_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.CREADOC);
}

private void VisaTravaux_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.TRAVAUX);

}

private void VisaRemiseOuvrageIR_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.REMISEOUVRIR);
}

private void VisaRemiseOuvrageExpl_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.REMISEOUVREXPL);
}

private void VisaMES_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.MISEENSERVICE);
}

private void VisaEncodageArchivage_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.ENCODAGEARCHIVAGE);

As you can see, they're using a function from the ViewModel with a different parameter.

Is there any way to regroup the 6 button events to have only one and kind of pass the parameter directly in the XAML call or something similar to avoid having the "code duplication" ?

Body:
Not sure if you like it "better" but you can check which button was clicked inside the handler:

void HandleButton_Click(object sender, RoutetEventArgs e)
{
    if (sender is Button b)
    {
        if (b == VisaCreaDoc) # VisaCreaDoc is the given name of your button instace in xaml
            ViewModel.ValidateItem(InfosPosteViewModel.CREADOC);
        else if (b == VisaTravaux)
            ViewModel.ValidateItem(InfosPosteViewModel.TRAVAUX);
        else if (...) // etc.
    }
}

You can spice it up with a switch pattern matching to get rid of the if / else if / else if / ... chains.


问:
How to use parameters in query in several places?
I'm using java PreparedStatement to set two parameters in a query begin time and end time. But in my query, I need to use it in two places. Can I make some query variables or make my request shorter?

```<code>SELECT * FROM publicutilities.orders
WHERE (works_begin between '2019-05-26 09:00:00' and '2019-05-26 14:00:00' OR works_end between '2019-05-26 09:00:00' and '2019-05-26 14:00:00')
</code>```

Something like this:

```<code>SELECT * FROM publicutilities.orders
VARIABLE begin_time = ?
VARIABLE end_time = ?
WHERE (works_begin between begin_time and end_time OR works_end between begin_time and end_time)
</code>```

答:
Use SET @var_name := <value> to identify an alias in SQL.

Rewriting your code,

```<code>SET @begin_ts := '2019-05-26 09:00:00'
SET @end_ts := '2019-05-26 14:00:00'
ELECT * FROM publicutilities.orders
WHERE (works_begin between @ begin_ts and @ end_ts OR works_end between @begin_ts and @end_ts)
</code>```

Body:
I'm using java PreparedStatement to set two parameters in a query begin time and end time. But in my query, I need to use it in two places. Can I make some query variables or make my request shorter?

SELECT * FROM publicutilities.orders
WHERE (works_begin between '2019-05-26 09:00:00' and '2019-05-26 14:00:00' OR works_end between '2019-05-26 09:00:00' and '2019-05-26 14:00:00')

Something like this:

SELECT * FROM publicutilities.orders
VARIABLE begin_time = ?
VARIABLE end_time = ?
WHERE (works_begin between begin_time and end_time OR works_end between begin_time and end_time)

Body:
Use SET @var_name := <value> to identify an alias in SQL.

Rewriting your code,

SET @begin_ts := '2019-05-26 09:00:00'
SET @end_ts := '2019-05-26 14:00:00'
ELECT * FROM publicutilities.orders
WHERE (works_begin between @ begin_ts and @ end_ts OR works_end between @begin_ts and @end_ts)


问:
Azure Stream Analytics Query - get last request for all device
I have IoT Hub, it collects messages from many devices. Data from IoT Hub are sent to stream analytics, and now I would like to stream analytics, display a list of all devices along with the last request. That is, a table in which there are eg 10 devices and with each device its last request.

My actual code:

```<code>SELECT
       deviceId,
       param1 as humidity,
       param2 as temperature,
       datetime as data
FROM hubMessage
GROUP By deviceId, data,temperature,humidity,
TumblingWindow(minute,5)
</code>```

Ont this query i have error on deviceId:

```<code>GROUP BY with no aggregate expressions is not supported.
</code>```

I dont'h have any idea, how resolve my problem with not supported expression and change last request for all device ;/

答:
GROUP BY with no aggregate expressions is not supported.

According to this error message,you need to use group by with aggregate expression.All aggregate expressions supported by ASA are listed here.

If you want to get the latest request,i think the TopOne is suitable for you.

If you want to select all the data match the filter,maybe you could use COUNT with group by.

Body:
I have IoT Hub, it collects messages from many devices. Data from IoT Hub are sent to stream analytics, and now I would like to stream analytics, display a list of all devices along with the last request. That is, a table in which there are eg 10 devices and with each device its last request.

My actual code:

SELECT
       deviceId,
       param1 as humidity,
       param2 as temperature,
       datetime as data
FROM hubMessage
GROUP By deviceId, data,temperature,humidity,
TumblingWindow(minute,5)

Ont this query i have error on deviceId:

GROUP BY with no aggregate expressions is not supported.

I dont'h have any idea, how resolve my problem with not supported expression and change last request for all device ;/


问:
Android SQLite: No such table error when trying to fetch data from Database
I am trying to use an already created DB from a csv file using DB Browser.
I tried uninstalling and re-installing the app. Also upgraded the DB version and still the same error occurs!
Checked my DB path and if the file is being created or not.

DatabaseHelper.java

```<code>package com.timespro.bookaseat.Model;

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

import com.timespro.bookaseat.Students;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String TABLE_NAME1 = "StudentDetails";

    private static final int DB_VERSION = 5;
    private static String DB_NAME = "data.sqlite";
    private  String DB_PATH;
    private  Context mContext;
    private SQLiteDatabase mDataBase;
    private boolean mNeedUpdate = false;

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        this.mContext = context;
        DB_PATH = context.getDatabasePath(DB_NAME).getAbsolutePath();
        Log.d("DB_Path",DB_PATH);
    }

    public void updateDataBase() throws IOException {
        if (mNeedUpdate) {
            File dbFile = new File(DB_PATH + DB_NAME);
            if (dbFile.exists())
                dbFile.delete();

            copyDataBase();

            mNeedUpdate = false;
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

        }catch(SQLiteException e){

            Log.d("DB","DB doesn't exist!");

        }

        if(checkDB != null){

            checkDB.close();

        }

        return checkDB != null;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transferring bytestream.
     * */
    private void copyDataBase() throws IOException{
        Log.d("DB","Database copied!");
        //Open your local db as the input stream
        InputStream myInput = mContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the input file to the output file
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }
    /**
     * Creates a empty database on the system and rewrites it with your own database.
     **/
    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();

        if(dbExist){
            Log.d("DatabaseHelper","DB already exists!");
            //do nothing - database already exist
        }else{

            //By calling this method and empty database will be created into the default system path
            //of your application so we are gonna be able to overwrite that database with our database.
            this.getReadableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");

            }
        }

    }

    private void copyDBFile() throws IOException {
        Log.d("DB","DB File created on phone");
        InputStream mInput = mContext.getAssets().open(DB_NAME);
        //InputStream mInput = mContext.getResources().openRawResource(getResources().getIdentifier("data","raw", getPackageName()));
        OutputStream mOutput = new FileOutputStream(DB_PATH + DB_NAME);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0)
            mOutput.write(mBuffer, 0, mLength);
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }

    public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_PATH + DB_NAME;
        mDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        Log.d("DB","DB opened");
    }

    @Override
    public void onConfigure(SQLiteDatabase db) {
        super.onConfigure(db);
        db.setForeignKeyConstraintsEnabled(true);
    }
    @Override
    public synchronized void close() {

        if(mDataBase != null)
            mDataBase.close();

        super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d("DB","DB created");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion)
            mNeedUpdate = true;
    }
    public ArrayList<Students> getAllData(){
        ArrayList<Students> students = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            Cursor res = db.rawQuery("select * from "+TABLE_NAME1, null);
            res.moveToFirst();
            while(res.moveToNext()) {
                int uid = Integer.parseInt(res.getString(0));   //0 is the number of id column in your database table
                String name = res.getString(1);
                String pass = res.getString(2);
                String city = res.getString(3);
                String centre = res.getString(4);
                String inst = res.getString(5);
                String pro = res.getString(6);
                String batch = res.getString(7);
                String days = res.getString(8);
                String time = res.getString(9);

                Students newStudents = new Students(uid,name,pass,city,centre,inst,pro,batch,days,time);
                students.add(newStudents);
            }
            res.close();
        }
        catch(SQLiteException sql){
            Log.d("DatabaseError!","No table found!");
        }
        finally {

            db.close();
        }

        return students;
    }
</code>```

}

error message:
E/SQLiteLog: (1) no such table: StudentDetails
D/DatabaseError!: No table found!

答:
If you have the No such table error you might do these things:

A. Try to increment the Database schema.

B. Uninstall the app from the device and install again.

C. Rename the table, there might have been some issue on the background of the SQLite

Body:
I am trying to use an already created DB from a csv file using DB Browser.
I tried uninstalling and re-installing the app. Also upgraded the DB version and still the same error occurs!
Checked my DB path and if the file is being created or not.

DatabaseHelper.java

package com.timespro.bookaseat.Model;

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

import com.timespro.bookaseat.Students;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String TABLE_NAME1 = "StudentDetails";

    private static final int DB_VERSION = 5;
    private static String DB_NAME = "data.sqlite";
    private  String DB_PATH;
    private  Context mContext;
    private SQLiteDatabase mDataBase;
    private boolean mNeedUpdate = false;

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        this.mContext = context;
        DB_PATH = context.getDatabasePath(DB_NAME).getAbsolutePath();
        Log.d("DB_Path",DB_PATH);
    }

    public void updateDataBase() throws IOException {
        if (mNeedUpdate) {
            File dbFile = new File(DB_PATH + DB_NAME);
            if (dbFile.exists())
                dbFile.delete();

            copyDataBase();

            mNeedUpdate = false;
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

        }catch(SQLiteException e){

            Log.d("DB","DB doesn't exist!");

        }

        if(checkDB != null){

            checkDB.close();

        }

        return checkDB != null;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transferring bytestream.
     * */
    private void copyDataBase() throws IOException{
        Log.d("DB","Database copied!");
        //Open your local db as the input stream
        InputStream myInput = mContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the input file to the output file
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }
    /**
     * Creates a empty database on the system and rewrites it with your own database.
     **/
    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();

        if(dbExist){
            Log.d("DatabaseHelper","DB already exists!");
            //do nothing - database already exist
        }else{

            //By calling this method and empty database will be created into the default system path
            //of your application so we are gonna be able to overwrite that database with our database.
            this.getReadableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");

            }
        }

    }

    private void copyDBFile() throws IOException {
        Log.d("DB","DB File created on phone");
        InputStream mInput = mContext.getAssets().open(DB_NAME);
        //InputStream mInput = mContext.getResources().openRawResource(getResources().getIdentifier("data","raw", getPackageName()));
        OutputStream mOutput = new FileOutputStream(DB_PATH + DB_NAME);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0)
            mOutput.write(mBuffer, 0, mLength);
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }

    public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_PATH + DB_NAME;
        mDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        Log.d("DB","DB opened");
    }

    @Override
    public void onConfigure(SQLiteDatabase db) {
        super.onConfigure(db);
        db.setForeignKeyConstraintsEnabled(true);
    }
    @Override
    public synchronized void close() {

        if(mDataBase != null)
            mDataBase.close();

        super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d("DB","DB created");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion)
            mNeedUpdate = true;
    }
    public ArrayList<Students> getAllData(){
        ArrayList<Students> students = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            Cursor res = db.rawQuery("select * from "+TABLE_NAME1, null);
            res.moveToFirst();
            while(res.moveToNext()) {
                int uid = Integer.parseInt(res.getString(0));   //0 is the number of id column in your database table
                String name = res.getString(1);
                String pass = res.getString(2);
                String city = res.getString(3);
                String centre = res.getString(4);
                String inst = res.getString(5);
                String pro = res.getString(6);
                String batch = res.getString(7);
                String days = res.getString(8);
                String time = res.getString(9);

                Students newStudents = new Students(uid,name,pass,city,centre,inst,pro,batch,days,time);
                students.add(newStudents);
            }
            res.close();
        }
        catch(SQLiteException sql){
            Log.d("DatabaseError!","No table found!");
        }
        finally {

            db.close();
        }

        return students;
    }

}

error message:
E/SQLiteLog: (1) no such table: StudentDetails
D/DatabaseError!: No table found!


问:
Add rows to pandas dataframe using column of dictionaries
I have a dataframe like this:

```<code>matrix = [(222, {'a': 1, 'b':3, 'c':2, 'd':1}),
         (333, {'a': 1, 'b':0, 'c':0, 'd':1})]

df = pd.DataFrame(matrix, columns=['ordernum', 'dict_of item_counts'])
</code>```

```<code>   ordernum               dict_of item_counts
0       222  {'a': 1, 'b': 3, 'c': 2, 'd': 1}
1       333  {'a': 1, 'b': 0, 'c': 0, 'd': 1}
</code>```

and I would like to create a dataframe in which each ordernum is repeated for each dictionary key in dict_of_item_counts that is not 0. I would also like to create a key column that shows the corresponding dictionary key for this row as well as a value column that contains the dictionary values. Finally, I would also an ordernum_index that counts the different rows in the dataframe for each ordernum.

The final dataframe should look like this:

```<code>ordernum      ordernum_index      key     value

222           1                   a       1
222           2                   b       3
222           3                   c       2
222           4                   d       1
333           1                   a       1
333           2                   d       1
</code>```

Any help would be much appreciated :)

答:
Construct dataframe df1 using df['dict_of item_counts'].tolist() for values and df.ordernum for index. replace 0 with np.nan and stack with dropna=True to ignore 0 values. reset_index to get all columns.

Next, create column ordernum_index by using groupby and cumcount.

Finally, change column names to appropriate names.

```<code>df1 = pd.DataFrame(df['dict_of item_counts'].tolist(), index=df.ordernum).replace(0, np.nan).stack(dropna=True).reset_index(name='value')
df1['ordernum_index'] = df1.groupby('ordernum')['value'].cumcount() + 1
df1 = df1.rename(columns={'level_1': 'key'})

Out[732]:
   ordernum key  value  ordernum_index
0       222   a    1.0               1
1       222   b    3.0               2
2       222   c    2.0               3
3       222   d    1.0               4
4       333   a    1.0               1
5       333   d    1.0               2
</code>```

Body:
I have a dataframe like this:

matrix = [(222, {'a': 1, 'b':3, 'c':2, 'd':1}),
         (333, {'a': 1, 'b':0, 'c':0, 'd':1})]

df = pd.DataFrame(matrix, columns=['ordernum', 'dict_of item_counts'])

   ordernum               dict_of item_counts
0       222  {'a': 1, 'b': 3, 'c': 2, 'd': 1}
1       333  {'a': 1, 'b': 0, 'c': 0, 'd': 1}

and I would like to create a dataframe in which each ordernum is repeated for each dictionary key in dict_of_item_counts that is not 0. I would also like to create a key column that shows the corresponding dictionary key for this row as well as a value column that contains the dictionary values. Finally, I would also an ordernum_index that counts the different rows in the dataframe for each ordernum.

The final dataframe should look like this:

ordernum      ordernum_index      key     value

222           1                   a       1
222           2                   b       3
222           3                   c       2
222           4                   d       1
333           1                   a       1
333           2                   d       1

Any help would be much appreciated :)

Body:
Construct dataframe df1 using df['dict_of item_counts'].tolist() for values and df.ordernum for index. replace 0 with np.nan and stack with dropna=True to ignore 0 values. reset_index to get all columns.

Next, create column ordernum_index by using groupby and cumcount.

Finally, change column names to appropriate names.

df1 = pd.DataFrame(df['dict_of item_counts'].tolist(), index=df.ordernum).replace(0, np.nan).stack(dropna=True).reset_index(name='value')
df1['ordernum_index'] = df1.groupby('ordernum')['value'].cumcount() + 1
df1 = df1.rename(columns={'level_1': 'key'})

Out[732]:
   ordernum key  value  ordernum_index
0       222   a    1.0               1
1       222   b    3.0               2
2       222   c    2.0               3
3       222   d    1.0               4
4       333   a    1.0               1
5       333   d    1.0               2


问:
Loop through all contents of a folder to put on website
I have recordings and photos folder for my personal website. I want to write code so that it will automatically go through the directory and display the images on the website

I've tried looking at a bunch of solutions already on SO but the problems weren't similar to mine and I couldn't understand the code to change it into what I need.

答:
You can try this code here

where 736 in the loop is the total images.

```<code>jQuery('document').ready(function() {
  var imgPath='images/';
  var imgExtinction='.jpg';

  var html='<ul>';
  for(var i=1; i<=736; i+=1){
    var imgNumber = getFourDigitNumber(i);
    var Image =imgPath+imgNumber+imgExtinction;
    html+=('<li><span class="overlay"></span> <img src="'+Image+'" /></li>');
  }
  jQuery('#images').append(PDFHTML+'</ul>');

});
</code>```

Body:
You can try this code here

where 736 in the loop is the total images.

jQuery('document').ready(function() {
  var imgPath='images/';
  var imgExtinction='.jpg';

  var html='<ul>';
  for(var i=1; i<=736; i+=1){
    var imgNumber = getFourDigitNumber(i);
    var Image =imgPath+imgNumber+imgExtinction;
    html+=('<li><span class="overlay"></span> <img src="'+Image+'" /></li>');
  }
  jQuery('#images').append(PDFHTML+'</ul>');

});


问:
Form gives error if I don't fill all the details in Angular reactive forms
I am using a reactive form to insert contact details.
Some of the fields are mandatory while others are optional.
The issue I have is if the user doesn't fill optional details fields and click on submit button I get following error:

```<code>ERROR TypeError: "this.contactForm.value.contactLastVerifiedDate is null"
</code>```

HTML Code:

 ngOnInit() {
    this.contactForm = this.formBuilder.group({
      contactType: ['', Validators.required],
      contactSubType: ['', Validators.required],
      referenceNumber: ['', Validators.required],
      contactStartDate: ['', Validators.required],
      contactLastVerifiedDate: ['']
    });
  }
  onSubmit() {
   if (this.contactForm.valid) {
      const newContact = {
        contactType: this.contactForm.value.contactType,
        contactSubType: this.contactForm.value.contactSubType,
        referenceNumber: this.contactForm.value.referenceNumber,
        startDate: this.parseDate(this.contactForm.value.contactStartDate.toString()),
        lastVerifiedDate: this.parseDate(this.contactForm.value.contactLastVerifiedDate.toString()),
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
  <div class="form-group">
    <label>Contact Type</label>
    <mat-select
      formControlName="contactType"
      class="form-control"
      [ngClass]="{ 'is-invalid': submitted && contactFormf.contactType.errors }"
      required
    >
      <mat-option *ngFor="let obj of contactTypes" [value]="obj.value"> {{ obj.viewValue }}</mat-option>
    </mat-select>
    <div *ngIf="submitted && contactFormf.contactType.errors" class="invalid-feedback">
      <div *ngIf="submitted && contactFormf.contactType.errors.required">Contact Type is required</div>
    </div>
  </div>

  <div class="form-group">
    <label>Contact Sub Type</label>
    <mat-select
      formControlName="contactSubType"
      class="form-control"
      [ngClass]="{ 'is-invalid': submitted && contactFormf.contactType.errors }"
      required
    >
      <mat-option *ngFor="let obj of contactSubTypes" [value]="obj.value"> {{ obj.viewValue }}</mat-option>
    </mat-select>
    <div *ngIf="submitted && contactFormf.contactSubType.errors" class="invalid-feedback">
      <div *ngIf="submitted && contactFormf.contactSubType.errors.required">Name Type is required</div>
    </div>
  </div>
  <div class="form-group">
    <label>Reference Number</label>
    <input
      type="text"
      formControlName="referenceNumber"
      class="form-control"
      [ngClass]="{ 'is-invalid': submitted && contactFormf.referenceNumber.errors }"
      required
    />
    <div *ngIf="submitted && contactFormf.referenceNumber.errors" class="invalid-feedback">
      <div *ngIf="submitted && contactFormf.referenceNumber.errors.required">Reference Number is required</div>
    </div>
  </div>

  <div class="form-group">
    <input
      matInput
      [matDatepicker]="startDate"
      formControlName="contactStartDate"
      placeholder="Choose Start date"
      [ngClass]="{ 'is-invalid': submitted && contactFormf.contactStartDate.errors }"
      required
    />
    <mat-datepicker-toggle matSuffix [for]="startDate"></mat-datepicker-toggle>
    <mat-datepicker #startDate></mat-datepicker>
    <div *ngIf="submitted && contactFormf.contactStartDate.errors" class="invalid-feedback">
      <div *ngIf="submitted && contactFormf.contactStartDate.errors.required">Contact Start Date is required</div>
    </div>
  </div>

  <div class="form-group">
    <input matInput [matDatepicker]="lastVerifiedDate" formControlName="contactLastVerifiedDate" placeholder="Choose Last Verified date" />
    <mat-datepicker-toggle matSuffix [for]="lastVerifiedDate"></mat-datepicker-toggle>
    <mat-datepicker #lastVerifiedDate></mat-datepicker>
  </div>

  <div class="form-group">
    <button>Save</button>
  </div>
</form></code>```

How can I make it Optional for user to submit form without entering Optional Details.Currently if user doesn't enter Optional details form gives error and if user enters details then it is successfully submitted

答:
You shouldn't have an error, but you can still prevent any error like that with something like </p>

```<code>lastVerifiedDate: this
  .parseDate((this.contactForm.value.contactLastVerifiedDate || '').toString()),
</code>```

Body:
I am using a reactive form to insert contact details.
Some of the fields are mandatory while others are optional.
The issue I have is if the user doesn't fill optional details fields and click on submit button I get following error:

ERROR TypeError: "this.contactForm.value.contactLastVerifiedDate is null"

HTML Code:

 ngOnInit() {
    this.contactForm = this.formBuilder.group({
      contactType: ['', Validators.required],
      contactSubType: ['', Validators.required],
      referenceNumber: ['', Validators.required],
      contactStartDate: ['', Validators.required],
      contactLastVerifiedDate: ['']
    });
  }
  onSubmit() {
   if (this.contactForm.valid) {
      const newContact = {
        contactType: this.contactForm.value.contactType,
        contactSubType: this.contactForm.value.contactSubType,
        referenceNumber: this.contactForm.value.referenceNumber,
        startDate: this.parseDate(this.contactForm.value.contactStartDate.toString()),
        lastVerifiedDate: this.parseDate(this.contactForm.value.contactLastVerifiedDate.toString()),
    }

<form [formGroup]="contactForm" (ngSubmit)="onSubmit()">

    Contact Type
    <mat-select
      formControlName="contactType"
      class="form-control"
      [ngClass]="{ 'is-invalid': submitted && contactFormf.contactType.errors }"
      required
    >
      <mat-option *ngFor="let obj of contactTypes" [value]="obj.value"> {{ obj.viewValue }}</mat-option>
    </mat-select>

Contact Type is required

    Contact Sub Type
    <mat-select
      formControlName="contactSubType"
      class="form-control"
      [ngClass]="{ 'is-invalid': submitted && contactFormf.contactType.errors }"
      required
    >
      <mat-option *ngFor="let obj of contactSubTypes" [value]="obj.value"> {{ obj.viewValue }}</mat-option>
    </mat-select>

Name Type is required

    Reference Number
    <input
      type="text"
      formControlName="referenceNumber"
      class="form-control"
      [ngClass]="{ 'is-invalid': submitted && contactFormf.referenceNumber.errors }"
      required
    />

Reference Number is required

    <input
      matInput
      [matDatepicker]="startDate"
      formControlName="contactStartDate"
      placeholder="Choose Start date"
      [ngClass]="{ 'is-invalid': submitted && contactFormf.contactStartDate.errors }"
      required
    />
    <mat-datepicker-toggle matSuffix [for]="startDate"></mat-datepicker-toggle>
    <mat-datepicker #startDate></mat-datepicker>

Contact Start Date is required

    <input matInput [matDatepicker]="lastVerifiedDate" formControlName="contactLastVerifiedDate" placeholder="Choose Last Verified date" />
    <mat-datepicker-toggle matSuffix [for]="lastVerifiedDate"></mat-datepicker-toggle>
    <mat-datepicker #lastVerifiedDate></mat-datepicker>

    <button>Save</button>

</form>

How can I make it Optional for user to submit form without entering Optional Details.Currently if user doesn't enter Optional details form gives error and if user enters details then it is successfully submitted

Body:
You shouldn't have an error, but you can still prevent any error like that with something like

lastVerifiedDate: this
  .parseDate((this.contactForm.value.contactLastVerifiedDate || '').toString()),


问:
Rspec parallel_test controller spec random fails
While running parallel_rspec spec random fails with controller any solution.

In Gemfile

```<code>group :development, :test do
  gem 'parallel_tests'
end
</code>```

My Spec execution like this

```<code>name@root:/project# parallel_rspec spec/controllers/
4 processes for 21 specs, ~ 5 specs per process

Randomized with seed 3503

Randomized with seed 41377
 0/62 |>                                                       |  ETA: ??:??:??
Randomized with seed 43603
 0/50 |>                                                       |  ETA: ??:??:??
Randomized with seed 61169
 3/62 |==>                                                     |  ETA: 00:08:03
  1) Admin::ReportingsController when signed-in non-admin GET #instance_reports redirects to root_url
     Failure/Error: expect( response ).to redirect_to root_url

       Expected response to be a redirect to <http://xxx/> but was a redirect to <http://yyyy>.
       Expected "http://xxxx/" to be === "http://xxxx/code".
     # ./spec/support/functions.rb:12:in `expect_root_redirect'
     # ./spec/controllers/admin/reportings_controller_spec.rb:25:in `block (4 levels) in <top (required)>'
     # ./spec/support/factory_bot.rb:18:in `block (3 levels) in <top (required)>'
     # /usr/local/bundle/gems/database_cleaner-1.7.0/lib/database_cleaner/generic/base.rb:16:in `cleaning'
     # /usr/local/bundle/gems/database_cleaner-1.7.0/lib/database_cleaner/base.rb:100:in `cleaning'
     # /usr/local/bundle/gems/database_cleaner-1.7.0/lib/database_cleaner/configuration.rb:86:in `block (2 levels) in cleaning'
     # /usr/local/bundle/gems/database_cleaner-1.7.0/lib/database_cleaner/configuration.rb:87:in `cleaning'
     # ./spec/support/factory_bot.rb:17:in `block (2 levels) in <top (required)>'
</code>```

like this fails randomly.

IF we run with below command its works fine.

```<code>rspec spec/controllers
</code>```

Note :

Single DB connected while execution.

Except controller everything works fine.

most are like json related conditions are faild.

答:
It looks like the the test assumes one state of the app, but it was probably changed by some concurrent request. (I'd bet that session is shared, and when testing your controller you think the person logged in is X, but it's Y).

Make sure each of the parallel runs are separated, it seems like all your tests are connecting to the same DB

Single DB connected while execution.
  This makes sense in single threaded apps, because it's cleaned after each example. But when running in parallel it can be a mess, and you can never be sure what's in the DB.

Did you change you DB config like this:

```<code>test:
  database: yourproject_test<%= ENV['TEST_ENV_NUMBER'] %>
</code>```

If you miss that - that's your u

Body:
While running parallel_rspec spec random fails with controller any solution.

In Gemfile

group :development, :test do
  gem 'parallel_tests'
end

My Spec execution like this

name@root:/project# parallel_rspec spec/controllers/
4 processes for 21 specs, ~ 5 specs per process

Randomized with seed 3503

Randomized with seed 41377
 0/62 |>                                                       |  ETA: ??:??:??
Randomized with seed 43603
 0/50 |>                                                       |  ETA: ??:??:??
Randomized with seed 61169
 3/62 |==>                                                     |  ETA: 00:08:03
  1) Admin::ReportingsController when signed-in non-admin GET #instance_reports redirects to root_url
     Failure/Error: expect( response ).to redirect_to root_url

       Expected response to be a redirect to <http://xxx/> but was a redirect to <http://yyyy>.
       Expected "http://xxxx/" to be === "http://xxxx/code".
     # ./spec/support/functions.rb:12:in `expect_root_redirect'
     # ./spec/controllers/admin/reportings_controller_spec.rb:25:in `block (4 levels) in <top (required)>'
     # ./spec/support/factory_bot.rb:18:in `block (3 levels) in <top (required)>'
     # /usr/local/bundle/gems/database_cleaner-1.7.0/lib/database_cleaner/generic/base.rb:16:in `cleaning'
     # /usr/local/bundle/gems/database_cleaner-1.7.0/lib/database_cleaner/base.rb:100:in `cleaning'
     # /usr/local/bundle/gems/database_cleaner-1.7.0/lib/database_cleaner/configuration.rb:86:in `block (2 levels) in cleaning'
     # /usr/local/bundle/gems/database_cleaner-1.7.0/lib/database_cleaner/configuration.rb:87:in `cleaning'
     # ./spec/support/factory_bot.rb:17:in `block (2 levels) in <top (required)>'

like this fails randomly.

IF we run with below command its works fine.

rspec spec/controllers

Note :

Single DB connected while execution.

Except controller everything works fine.

most are like json related conditions are faild.

Body:
It looks like the the test assumes one state of the app, but it was probably changed by some concurrent request. (I'd bet that session is shared, and when testing your controller you think the person logged in is X, but it's Y).

Make sure each of the parallel runs are separated, it seems like all your tests are connecting to the same DB

Single DB connected while execution.
  This makes sense in single threaded apps, because it's cleaned after each example. But when running in parallel it can be a mess, and you can never be sure what's in the DB.

Did you change you DB config like this:

test:
  database: yourproject_test<%= ENV['TEST_ENV_NUMBER'] %>

If you miss that - that's your u


问:
Preloading a UIImageView animation using objective c for the iphone
I have an animated image which works great. It consists of 180 high quality images and it plays fine and loops continuously. My problem is that the first time I load the view containing these images it takes a long time to load. Every subsequent time after that it loads immediately as I am assuming that the images have been cached or preloaded!!! I come from a flash background and as I am sure you aware preloaders are as common as muck so I don't feel this should be difficult to find but after countless googling I cannot find any good examples on preloading or any articles on why there is a delay and what to do about it.

So my question(s) is this:

Is there a checkbox in the info.plist to preload all my images at the start of the app?

How can you preload images and are there any simple example projects that I could look at?

Is this the best way to implement what is essentially a video but has been output to a png sequence?

Is there another method as viewDidLoad does not work as I expect it to do. It traces "FINISHED LOADING IMAGES" (see code below) but the view does not show for a second or two after the images have been loaded so if the view does not show until the images have loaded then neither will the UIActivityIndicatorView which is also in the same view.

How do you do event listening in objective c?

Below is the code in the viewDidLoad which I believe is fairly standard:

Any help is greatly appreciated as I am banging my head on a brick wall on something that seems so basic in ui development. Help :)

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    imageArray = [[NSMutableArray alloc] initWithCapacity:IMAGE_COUNT];

    NSLog(@"START LOADING IMAGES");

    // Build array of images, cycling through image names
    for (int i = 0; i < IMAGE_COUNT; i++){
        [imageArray addObject:[UIImage imageNamed: [NSString stringWithFormat:@"Main_%d.png", i]]];
    }

    animatedImages = [[UIImageView alloc] initWithFrame:CGRectMake(0,20,IMAGE_WIDTH, IMAGE_HEIGHT)];
    animatedImages.animationImages = [NSArray arrayWithArray:imageArray];
    animatedImages.animationDuration = 6.0;
    animatedImages.animationRepeatCount = 0;
    [self.view addSubview:animatedImages];
    animatedImages.startAnimating;
    [animatedImages release];

    NSLog(@"FINISH LOADING IMAGES");

}
</code>```

Cheers

M

答:
```<code>My problem is that the first time I load the view containing these images it takes a long time to load. Every subsequent time after that it loads immediately as I am assuming that the images have been cached or preloaded
</code>```

you are right at this point ...... as you are using method imageNamed: for this method document quotes.....

```<code>This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.
</code>```

so in my opinion, rather than doing following stuff in viewDidLoad, you should do it earlier where delay is of not considerable......

```<code>    for (int i = 0; i < IMAGE_COUNT; i++)
    {
    [imageArray addObject:[UIImage imageNamed: [NSString stringWithFormat:@"Main_%d.png", i]]];
}
</code>```

another approach

```<code>- (void)spinLayer:(CALayer *)inLayer duration:(CFTimeInterval)inDuration
        direction:(int)direction
{
    CABasicAnimation* rotationAnimation;

    // Rotate about the z axis
    rotationAnimation =
    [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];

    // Rotate 360 degress, in direction specified
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 * direction];

    // Perform the rotation over this many seconds
    rotationAnimation.duration = inDuration;
    rotationAnimation.repeatCount = 100;
    //rotationAnimation.

    // Set the pacing of the animation
    //rotationAnimation.timingFunction =
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

    // Add animation to the layer and make it so
    [inLayer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}
</code>```

this method will help in animation call it as follow(I am assuming that you are putting above method in same class where you have imageView.

```<code>[self spinLayer:yourImageView.layer duration:5.0
            direction:<-1 or 1 for anti clockwise or clockwise spin>];
</code>```

remember just set only one image to that imageView(which you wish to animate.
thanks,

ContentLicense: CC BY-SA 3.0

Body:
I have an animated image which works great. It consists of 180 high quality images and it plays fine and loops continuously. My problem is that the first time I load the view containing these images it takes a long time to load. Every subsequent time after that it loads immediately as I am assuming that the images have been cached or preloaded!!! I come from a flash background and as I am sure you aware preloaders are as common as muck so I don't feel this should be difficult to find but after countless googling I cannot find any good examples on preloading or any articles on why there is a delay and what to do about it.

So my question(s) is this:

Is there a checkbox in the info.plist to preload all my images at the start of the app?

How can you preload images and are there any simple example projects that I could look at?

Is this the best way to implement what is essentially a video but has been output to a png sequence?

Is there another method as viewDidLoad does not work as I expect it to do. It traces "FINISHED LOADING IMAGES" (see code below) but the view does not show for a second or two after the images have been loaded so if the view does not show until the images have loaded then neither will the UIActivityIndicatorView which is also in the same view.

How do you do event listening in objective c?

Below is the code in the viewDidLoad which I believe is fairly standard:

Any help is greatly appreciated as I am banging my head on a brick wall on something that seems so basic in ui development. Help :)

- (void)viewDidLoad {
    [super viewDidLoad];

    imageArray = [[NSMutableArray alloc] initWithCapacity:IMAGE_COUNT];

    NSLog(@"START LOADING IMAGES");

    // Build array of images, cycling through image names
    for (int i = 0; i < IMAGE_COUNT; i++){
        [imageArray addObject:[UIImage imageNamed: [NSString stringWithFormat:@"Main_%d.png", i]]];
    }

    animatedImages = [[UIImageView alloc] initWithFrame:CGRectMake(0,20,IMAGE_WIDTH, IMAGE_HEIGHT)];
    animatedImages.animationImages = [NSArray arrayWithArray:imageArray];
    animatedImages.animationDuration = 6.0;
    animatedImages.animationRepeatCount = 0;
    [self.view addSubview:animatedImages];
    animatedImages.startAnimating;
    [animatedImages release];

    NSLog(@"FINISH LOADING IMAGES");

}

Cheers

M

Body:
My problem is that the first time I load the view containing these images it takes a long time to load. Every subsequent time after that it loads immediately as I am assuming that the images have been cached or preloaded

you are right at this point ...... as you are using method imageNamed: for this method document quotes.....

This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.

so in my opinion, rather than doing following stuff in viewDidLoad, you should do it earlier where delay is of not considerable......

    for (int i = 0; i < IMAGE_COUNT; i++)
    {
    [imageArray addObject:[UIImage imageNamed: [NSString stringWithFormat:@"Main_%d.png", i]]];
}

another approach

- (void)spinLayer:(CALayer *)inLayer duration:(CFTimeInterval)inDuration
        direction:(int)direction
{
    CABasicAnimation* rotationAnimation;

    // Rotate about the z axis
    rotationAnimation =
    [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];

    // Rotate 360 degress, in direction specified
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 * direction];

    // Perform the rotation over this many seconds
    rotationAnimation.duration = inDuration;
    rotationAnimation.repeatCount = 100;
    //rotationAnimation.

    // Set the pacing of the animation
    //rotationAnimation.timingFunction =
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

    // Add animation to the layer and make it so
    [inLayer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

this method will help in animation call it as follow(I am assuming that you are putting above method in same class where you have imageView.

[self spinLayer:yourImageView.layer duration:5.0
            direction:<-1 or 1 for anti clockwise or clockwise spin>];

remember just set only one image to that imageView(which you wish to animate.
thanks,


问:
Resize cell after scrolling (Autolayout)
Resize cell size after some scrolling.

CommentViewController.swift Code

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    tblView.register(UINib(nibName: "CellComment", bundle: nil), forCellReuseIdentifier: "CellComment")

    // Remove extra space from group tableview
    var frame = CGRect.zero
    frame.size.height = .leastNormalMagnitude
    tblView.tableFooterView = UIView(frame: frame)

    tblView.rowHeight = UITableView.automaticDimension
    tblView.estimatedRowHeight = 123

    tblView.estimatedSectionFooterHeight = 0.01
    tblView.separatorColor = .clear
    tblView.reloadData()
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

}

// UITableViewDelegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 15
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tblView.dequeueReusableCell(withIdentifier: "CellComment", for: indexPath) as! CellComment
    cell.selectionStyle = .none
    cell.delegate = self
    cell.imgViewUser.image = UIImage.init(named: "userImage1.jpg")
    cell.lblUserName.text = "User Name \(indexPath.row + 1)"

    if indexPath.row % 2 == 0 {
        cell.lblComment.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
    }
    else {
        cell.lblComment.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged."

    }
    //        cell.updateConstraintsIfNeeded() //I try but not working
    //        cell.layoutIfNeeded()
    cell.layoutSubviews()
    return cell
}
</code>```

CellComment.swift

```<code>override func layoutSubviews() {
        super.layoutSubviews()
        //lblComment.preferredMaxLayoutWidth = lblComment.bounds.width
        lblComment.preferredMaxLayoutWidth = lblComment.bounds.size.width
    }
</code>```

Full Video

答: It's because tableview is not able to calculate cell's frame correctly. You don't need to call cell.layoutSubviews(). You should check your constraints of contentView of tableview cell.   </p>

Body:
Resize cell size after some scrolling.

CommentViewController.swift Code

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    tblView.register(UINib(nibName: "CellComment", bundle: nil), forCellReuseIdentifier: "CellComment")

    // Remove extra space from group tableview
    var frame = CGRect.zero
    frame.size.height = .leastNormalMagnitude
    tblView.tableFooterView = UIView(frame: frame)

    tblView.rowHeight = UITableView.automaticDimension
    tblView.estimatedRowHeight = 123

    tblView.estimatedSectionFooterHeight = 0.01
    tblView.separatorColor = .clear
    tblView.reloadData()
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

}

// UITableViewDelegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 15
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tblView.dequeueReusableCell(withIdentifier: "CellComment", for: indexPath) as! CellComment
    cell.selectionStyle = .none
    cell.delegate = self
    cell.imgViewUser.image = UIImage.init(named: "userImage1.jpg")
    cell.lblUserName.text = "User Name \(indexPath.row + 1)"

    if indexPath.row % 2 == 0 {
        cell.lblComment.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
    }
    else {
        cell.lblComment.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged."

    }
    //        cell.updateConstraintsIfNeeded() //I try but not working
    //        cell.layoutIfNeeded()
    cell.layoutSubviews()
    return cell
}

CellComment.swift

override func layoutSubviews() {
        super.layoutSubviews()
        //lblComment.preferredMaxLayoutWidth = lblComment.bounds.width
        lblComment.preferredMaxLayoutWidth = lblComment.bounds.size.width
    }

Full Video


问:
New Google Places Autocomplete and its pricing
I am using the new Place Autocomplete that is from the new static Google Places SDK client library (here). So it is really easy to use and I just got this tutorial and it is working as expected.

To add this in the project, I have to add following dependency in the Gradle file:

implementation ‘com.google.android.libraries.places:places:1.0.0’

I have been reading Google pricing/usage and billing, but I have not figured out the pricing of this new Autocomplete (library version). All I found was this, but to me it looks like it is for the web version, as I do not think the session needs to maintain this new client library version.

As I am not able to figure out pricing for the Places Auto complete (library version), is it free? Or if it is not free, what are billing criteria for this?

答:
First of all, the new Google Place Autocomplete API is not free (after exceeding the US$200 monthly credit equivalent free usage).

Now coming to the pricing, Google has introduced three possible pricing criteria:

Autocomplete without Places Details – Per Session

Autocomplete (included with Places Details) – Per Session

Autocomplete - Per Request

You might be wondering: What's the difference between session and request?

Session

The session begins when the user starts typing a query, and concludes
when they select a place and a call to Place Details is made. If the
user does not make a selection, the session will end after a short
time out period.

Request
If you don't go with a session-based approach, you'll get billed per search query.

For example, if you type "S", it will increase your request count, now you write one more character "Sa", and it will again increase your request count.

So, if you type the whole word "San Francisco", you'll get billed for 13 requests.

Benefits of using session

As mentioned in the above example, if you don't want to get charged per character that you write, you have an option to combine your search queries into a single session. That way you'll save some bucks to spend somewhere else.

So, the "San Francisco" whole string will be billed as one session request instead of multiple.

Please note that session price is always higher than per request price but it is decided in such a way that if you are heavily using the auto-complete in your project with lots of user-base, then ultimately, session-based pricing becomes cheaper than request-based pricing.

Usually, in my opinion, a session-based approach can be helpful only to those who are having heavy usage of autocomplete, otherwise, the request-based approach is fine.

To do the math, go to Google Pricing Table and scroll to Places.


问:
moving focus on selecting value from aoutocomplete menue using mouse click
I have the below mentioned code which validates whether the user had entered data which is only available in the autocomplete menu and if its valid then it will move to the next textbox.

```<code>$("#Text1").autocomplete({ source: function(req, responseFn) {
  var re = $.ui.autocomplete.escapeRegex(req.term);
  var textinput = new RegExp( "" +re, "i" );
  var match = $.grep( crtfdesc, function(item,index){
  return textinput.test(item);
  });
  responseFn( match );
  },
  change: function(event, ui){var flag;
    var cval=$(this).val();
    var len=crtfdesc.length;

    for(var c=0;c<len;c++)
    {
        if(cval==crtfdesc[c]){ flag=1;$("#text2").focus();break;}
        else
        { flag=2;}
    }
 if(flag==2){$(this).val("");}

  },
  select: function(event, ui){
        $("#text2").focus();
  }
});//Text1
</code>```

but this code is not working if i select a value using mouse click. The focus remains on the autocomplete textbox.

答: The code is working fine. The only change that i made is i moved from jQuery UI Autocomplete 1.8.2 to jQuery UI Autocomplete 1.8.11 and the problem is solved. </p>

Body:
I have the below mentioned code which validates whether the user had entered data which is only available in the autocomplete menu and if its valid then it will move to the next textbox.

$("#Text1").autocomplete({ source: function(req, responseFn) {
  var re = $.ui.autocomplete.escapeRegex(req.term);
  var textinput = new RegExp( "" +re, "i" );
  var match = $.grep( crtfdesc, function(item,index){
  return textinput.test(item);
  });
  responseFn( match );
  },
  change: function(event, ui){var flag;
    var cval=$(this).val();
    var len=crtfdesc.length;

    for(var c=0;c<len;c++)
    {
        if(cval==crtfdesc[c]){ flag=1;$("#text2").focus();break;}
        else
        { flag=2;}
    }
 if(flag==2){$(this).val("");}

  },
  select: function(event, ui){
        $("#text2").focus();
  }
});//Text1

but this code is not working if i select a value using mouse click. The focus remains on the autocomplete textbox.


问:
Align Widget inside Expanded in row in flutter
I'm trying to align widget inside the row but the widget automatically aligns to the center. I want to align both the widget to the top of the row.

```<code> Widget PlayerConnectWidget(double width,double height){
      return SingleChildScrollView(
          child: Container(

            margin: EdgeInsets.only(left: width*0.03,right: width*0.03,top: width*0.05),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[

                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    Flexible(flex:1,fit:FlexFit.loose,child:MyFeedTile(),),
                    Flexible(flex:1,fit:FlexFit.loose,child:_logoContainer(width),),

                ],),
                SizedBox(height: width*0.02),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                   Expanded(flex: 7,child: Container(
                     margin: EdgeInsets.only(right: width*0.03),
                     padding: EdgeInsets.all(width*0.03),
                     decoration: BoxDecoration(color: Colors.white70,borderRadius: new BorderRadius.circular(12.0),),
                     child: Column(
                       crossAxisAlignment: CrossAxisAlignment.stretch,
                       children: <Widget>[
                       Text('Venue'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Location'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Sports'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Opening Times'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Notes'),
                         new Divider(
                           color: Colors.black87,
                         ),
                     ],),

                   ),),
                    Expanded(flex: 3, child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                    //  mainAxisAlignment: MainAxisAlignment.start,
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[

                      //  SizedBox(height: width*0.02),
                        Container(
                          decoration: BoxDecoration(
                            color: MyColors.yellowBg,
                            borderRadius: new BorderRadius.circular(8.0),
                          ),
                          child:  FlatButton(
                              onPressed: (){
                              },
                              child: Text(
                                  'Message',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16.0,

                                  )
                              )
                          ),),
                        SizedBox(height: width*0.02),
                        Container(
                          decoration: BoxDecoration(
                            color: MyColors.yellowBg,
                            borderRadius: new BorderRadius.circular(8.0),
                          ),
                          child:  FlatButton(
                              onPressed: (){
                              },
                              child: Text(
                                  'Continue',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16.0,

                                  )
                              )
                          ),)
                      ],),)
                  ],)
              ],
            ),
          )
      );
    }

Widget _logoContainer(double width){
  return Container(
    margin: EdgeInsets.only(left:width*0.05),
    height: 110.0,
    width: 120.0,
    decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/images/cmp_click.png"),
          fit: BoxFit.fill,
        )
    ),
  );
}
Widget MyFeedTile(){
  return GestureDetector(
    onTap: (){
      Navigator.push(context, MaterialPageRoute(builder: (context) => FeedView()),);
    },
    child: Container(
      padding: EdgeInsets.only(top:width*0.02,bottom: width*0.02),
      decoration: BoxDecoration(
        color: MyColors.colorPrimaryDark,
        borderRadius: new BorderRadius.circular(12.0),

      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Expanded(flex: 3,
            child: Container(
              //decoration: BoxDecoration(color: Colors.green[100]),
              height: 50,
              width: 50,
              margin: EdgeInsets.all(width*0.01),
              child: CircleAvatar(
                radius: 50.0,
                backgroundImage:
                NetworkImage('https://via.placeholder.com/150'),
                backgroundColor: Colors.transparent,),),

          ),
          Expanded(flex: 7,child: Container(
            //decoration: BoxDecoration(color: Colors.green[100]),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                Text('User name',style: TextStyle(color: Colors.white,fontFamily: 'bold'),),
                SizedBox(height: width*0.01),
                Text('Time',style: TextStyle(color: Colors.white,fontFamily: 'light'),),
                SizedBox(height: width*0.01),
                Text('Location',style: TextStyle(color: Colors.white,fontFamily: 'light'),),
                SizedBox(height: width*0.01),
                Text('Date',style: TextStyle(color: Colors.white,fontFamily: 'light'),),
              ],),),)
        ],),

    ),);
}
</code>```

I'm getting this

and I'm trying to achieve this

and this

答:
You just need to add the following line in your code :

crossAxisAlignment: CrossAxisAlignment.start

```<code>  Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.start,
</code>```

Body:
I'm trying to align widget inside the row but the widget automatically aligns to the center. I want to align both the widget to the top of the row.

 Widget PlayerConnectWidget(double width,double height){
      return SingleChildScrollView(
          child: Container(

            margin: EdgeInsets.only(left: width*0.03,right: width*0.03,top: width*0.05),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[

                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    Flexible(flex:1,fit:FlexFit.loose,child:MyFeedTile(),),
                    Flexible(flex:1,fit:FlexFit.loose,child:_logoContainer(width),),

                ],),
                SizedBox(height: width*0.02),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                   Expanded(flex: 7,child: Container(
                     margin: EdgeInsets.only(right: width*0.03),
                     padding: EdgeInsets.all(width*0.03),
                     decoration: BoxDecoration(color: Colors.white70,borderRadius: new BorderRadius.circular(12.0),),
                     child: Column(
                       crossAxisAlignment: CrossAxisAlignment.stretch,
                       children: <Widget>[
                       Text('Venue'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Location'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Sports'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Opening Times'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Notes'),
                         new Divider(
                           color: Colors.black87,
                         ),
                     ],),

                   ),),
                    Expanded(flex: 3, child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                    //  mainAxisAlignment: MainAxisAlignment.start,
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[

                      //  SizedBox(height: width*0.02),
                        Container(
                          decoration: BoxDecoration(
                            color: MyColors.yellowBg,
                            borderRadius: new BorderRadius.circular(8.0),
                          ),
                          child:  FlatButton(
                              onPressed: (){
                              },
                              child: Text(
                                  'Message',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16.0,

                                  )
                              )
                          ),),
                        SizedBox(height: width*0.02),
                        Container(
                          decoration: BoxDecoration(
                            color: MyColors.yellowBg,
                            borderRadius: new BorderRadius.circular(8.0),
                          ),
                          child:  FlatButton(
                              onPressed: (){
                              },
                              child: Text(
                                  'Continue',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16.0,

                                  )
                              )
                          ),)
                      ],),)
                  ],)
              ],
            ),
          )
      );
    }

Widget _logoContainer(double width){
  return Container(
    margin: EdgeInsets.only(left:width*0.05),
    height: 110.0,
    width: 120.0,
    decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/images/cmp_click.png"),
          fit: BoxFit.fill,
        )
    ),
  );
}
Widget MyFeedTile(){
  return GestureDetector(
    onTap: (){
      Navigator.push(context, MaterialPageRoute(builder: (context) => FeedView()),);
    },
    child: Container(
      padding: EdgeInsets.only(top:width*0.02,bottom: width*0.02),
      decoration: BoxDecoration(
        color: MyColors.colorPrimaryDark,
        borderRadius: new BorderRadius.circular(12.0),

      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Expanded(flex: 3,
            child: Container(
              //decoration: BoxDecoration(color: Colors.green[100]),
              height: 50,
              width: 50,
              margin: EdgeInsets.all(width*0.01),
              child: CircleAvatar(
                radius: 50.0,
                backgroundImage:
                NetworkImage('https://via.placeholder.com/150'),
                backgroundColor: Colors.transparent,),),

          ),
          Expanded(flex: 7,child: Container(
            //decoration: BoxDecoration(color: Colors.green[100]),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                Text('User name',style: TextStyle(color: Colors.white,fontFamily: 'bold'),),
                SizedBox(height: width*0.01),
                Text('Time',style: TextStyle(color: Colors.white,fontFamily: 'light'),),
                SizedBox(height: width*0.01),
                Text('Location',style: TextStyle(color: Colors.white,fontFamily: 'light'),),
                SizedBox(height: width*0.01),
                Text('Date',style: TextStyle(color: Colors.white,fontFamily: 'light'),),
              ],),),)
        ],),

    ),);
}

I'm getting this

and I'm trying to achieve this

and this

Body:
You just need to add the following line in your code :

crossAxisAlignment: CrossAxisAlignment.start

  Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.start,


问:
How can I select the data between some specific hours in a specific month?
I already have InfluxDB working and getting monitoring data about some services (the value is just 1 for up and 0 for down). For the management I need to select the values from the database that are in a specific month and either night time or day time. For example: I want to select all the data from April 2019 (doesn't matter if it 1 or 0) between 08:00AM and 07:00PM (day time)

Here is what I've tried:

```<code>SELECT value FROM probe_success
WHERE "instance" = 'https://myservice/api' AND time >= '08:00:00' AND time < '19:00:00'
AND time >= '2019-04-01' AND time <= '2019-04-30'
</code>```

But I've got an error:

{"results":[{"statement_id":0,"error":"invalid operation: time and
  *influxql.StringLiteral are not compatible"}]}

Can anyone tell me what I'm doing wrong or point me in the right direction?

Thank you very much!

答: Ok, so after some research I've found that it is not possible to use the "OR" statement in a "WHERE" clause to specify multiple time ranges. See this. I solved this problem by sending separate requests for each day in a for loop and then concatenate all the results. It's not the best solution, I admit, but since they say it's not possible I guess this is the workaround.</p>

Body:
I already have InfluxDB working and getting monitoring data about some services (the value is just 1 for up and 0 for down). For the management I need to select the values from the database that are in a specific month and either night time or day time. For example: I want to select all the data from April 2019 (doesn't matter if it 1 or 0) between 08:00AM and 07:00PM (day time)

Here is what I've tried:

SELECT value FROM probe_success
WHERE "instance" = 'https://myservice/api' AND time >= '08:00:00' AND time < '19:00:00'
AND time >= '2019-04-01' AND time <= '2019-04-30'

But I've got an error:

{"results":[{"statement_id":0,"error":"invalid operation: time and
  *influxql.StringLiteral are not compatible"}]}

Can anyone tell me what I'm doing wrong or point me in the right direction?

Thank you very much!


问:
Transfering file from local to a linux system (java code) without using any 3rd party jar
I want to do some file transfer between my local system to a Linux server with Java code.
below functionality, I need to write

Connect to Linux server

Put file from Local to Linux server

Get file from Linux to local

Delete file in Linux server if exist

Note That I should not use any kind of 3rd party jar like jsch.

Previously I did this Job with the help of jsch jar and that was working very fine for me. But for my project, I should not use this 3rd party jar. So I need to perform the same task without the use of any 3rd party jar.

答:
Not sure if this could help you, but if you can't use any libs, maybe go back to the basics.  Look into connecting through Sockets.

You will need a client module and a server module (One is installed on your local machine), and one is installed on your server module)

I suggest you google a lot and discuss with your teacher.