问:
How do I handle my data model class to get Firebase Firestore data into recyclerView?
I have a Firestore database like this:

I want to access each of the different symptom data's i.e. "Anxiety_data" and its children which consists of timestamps, and then a dictionary, and place them into a RecyclerView using FirebaseUI FirebaseRecyclerViewAdapter

I have this model class:

```<code>  public class EntryDataModel {
private String timestamp, symptom, severity, comment;

public EntryDataModel() {}

public EntryDataModel(String timestamp, String symptom, String severity, String comment) {
    this.timestamp = timestamp;
    this.symptom = symptom;
    this.severity = severity;
    this.comment = comment;
}

public String getTimestamp() {return timestamp;}
public String getSymptom() {return symptom;}
public String getSeverity() {return severity;}
public String getComment() {return comment;}

}
</code>```

Here is my Query:

```<code>Query query = db.collection("users").document(user_id).collection("symptom_data");
</code>```

Here is the Firebase RecyclerView Adapter:

```<code>void fireStoreRecyclerAdapterSetup() {

    FirestoreRecyclerOptions<EntryDataModel> options = new FirestoreRecyclerOptions.Builder<EntryDataModel>()
            .setQuery(query, EntryDataModel.class)
            .build();

    FirestoreRecyclerAdapter adapter = new FirestoreRecyclerAdapter<EntryDataModel, EntryDataHolder>(options) {
        @Override
        public void onBindViewHolder(EntryDataHolder holder, int position, EntryDataModel model) {
            // Bind the Chat object to the ChatHolder
            // ...

           System.out.println("Query: " + query.toString());

        }

        @Override
        public EntryDataHolder onCreateViewHolder(ViewGroup group, int i) {
            // Create a new instance of the ViewHolder, in this case we are using a custom
            // layout called R.layout.message for each item
            View view = LayoutInflater.from(group.getContext())
                    .inflate(R.layout.entry_data_recyclerview_item, group, false);

            return new EntryDataHolder(view);
        }
    };

    recyclerView.setAdapter(adapter);
    adapter.startListening();

}

}
</code>```

I am not sure how I should set this up so that I take all the Timestamp arrays from each of the symptom data fields, and have them all together in a list that I can use for the recyclerView.

Maybe I cannot use FirebaseUI Recycler adapter, or I need to iterate through each different symptom field first and build + append a list? Hopefully I am clear in what I would like to do Thank you.

EDIT: I have done it on iOS, This is the result that I want:

EDIT: I have added this, getting the names of each individual document, and then once I have that in a for loop I am now trying to get the Array values and add that to an EntryDataModel list, then I can use my own adapter:

EDIT: This works, I get the data I need, from each Document. Now I just need to be able to Iterate over the fields and timestamps, and use my model to create a list. How can I do that? Log.d("example", "DocumentSnapshot data: " + document.getData()); this prints: D/example: DocumentSnapshot data: {1558879769={severity=Mild, symptom=Anxiety, comment=Mild anxiety at work., timestamp=1558879769}, 1558879745={severity=Mild, symptom=Anxiety, comment=Feeling relaxed watching TV., timestamp=1558879745}, 1558879710={severity=Moderate, symptom=Anxiety, comment=Walking the cat., timestamp=1558879710}, 1558879827={severity=Moderate, symptom=Anxiety, comment=Taking the cat for a walk., timestamp=1558879827}, 1558888729={severity=Mild, symptom=Anxiety, comment=The cat is fed up with walking., timestamp=1558888729}} Now I just need to get each timestamp array and add them to a seperate list, and i can then do this for each document and have a full list of all the timestamp arrays.

```<code>  void getSymptomData() {
     final CollectionReference colRef = db.collection("users").document(user_id).collection("symptom_data");

     colRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
         @Override
         public void onComplete(@NonNull Task<QuerySnapshot> task) {
             if (task.isSuccessful()) {
                 List<String> list = new ArrayList<>();
                 for (QueryDocumentSnapshot document : task.getResult()) {
                     list.add(document.getId());
                     DocumentReference docRef = colRef.document(document.getId());
                     docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                         @Override
                         public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                             if (task.isSuccessful()) {
                                 DocumentSnapshot document = task.getResult();
                                 if (document.exists()) {
                                     Log.d("Iteration", "DocumentSnapshot data: " + document.getData());
                                 } else {
                                     Log.d("NoDoc", "No such document");
                                 }
                             } else {
                                 Log.d("Failed", "get failed with ", task.getException());
                             }
                         }
                     });
                 }
                 Log.d("listylist", list.toString());
             } else {
                 Log.d("tag", "Error getting documents: ", task.getException());
             }
         }
     });

}
</code>```

答:
The automatic mapping that the Firebase SDK can do from a Firestore document to a Java object, requires that each field name from the document matches a property name in the Java class. It has no mechanism to deal with dynamic fields, such as the timestamps in your example.

So you will have to do your own conversion. For that you can use the public T get (FieldPath fieldPath, Class<T> valueType) or public T get (String field, Class<T> valueType) method, which allow you to get an object from a specific field that you specify. So you will have to loop over the timestamp fields, but after that the Firebase SDK can map the severity, symptom, and timestamp properties to the object.

Body:
I have a Firestore database like this:

I want to access each of the different symptom data's i.e. "Anxiety_data" and its children which consists of timestamps, and then a dictionary, and place them into a RecyclerView using FirebaseUI FirebaseRecyclerViewAdapter

I have this model class:

  public class EntryDataModel {
private String timestamp, symptom, severity, comment;

public EntryDataModel() {}

public EntryDataModel(String timestamp, String symptom, String severity, String comment) {
    this.timestamp = timestamp;
    this.symptom = symptom;
    this.severity = severity;
    this.comment = comment;
}

public String getTimestamp() {return timestamp;}
public String getSymptom() {return symptom;}
public String getSeverity() {return severity;}
public String getComment() {return comment;}

}

Here is my Query:

Query query = db.collection("users").document(user_id).collection("symptom_data");

Here is the Firebase RecyclerView Adapter:

void fireStoreRecyclerAdapterSetup() {

    FirestoreRecyclerOptions<EntryDataModel> options = new FirestoreRecyclerOptions.Builder<EntryDataModel>()
            .setQuery(query, EntryDataModel.class)
            .build();

    FirestoreRecyclerAdapter adapter = new FirestoreRecyclerAdapter<EntryDataModel, EntryDataHolder>(options) {
        @Override
        public void onBindViewHolder(EntryDataHolder holder, int position, EntryDataModel model) {
            // Bind the Chat object to the ChatHolder
            // ...

           System.out.println("Query: " + query.toString());

        }

        @Override
        public EntryDataHolder onCreateViewHolder(ViewGroup group, int i) {
            // Create a new instance of the ViewHolder, in this case we are using a custom
            // layout called R.layout.message for each item
            View view = LayoutInflater.from(group.getContext())
                    .inflate(R.layout.entry_data_recyclerview_item, group, false);

            return new EntryDataHolder(view);
        }
    };

    recyclerView.setAdapter(adapter);
    adapter.startListening();

}

}

I am not sure how I should set this up so that I take all the Timestamp arrays from each of the symptom data fields, and have them all together in a list that I can use for the recyclerView.

Maybe I cannot use FirebaseUI Recycler adapter, or I need to iterate through each different symptom field first and build + append a list? Hopefully I am clear in what I would like to do Thank you.

EDIT: I have done it on iOS, This is the result that I want:

EDIT: I have added this, getting the names of each individual document, and then once I have that in a for loop I am now trying to get the Array values and add that to an EntryDataModel list, then I can use my own adapter:

EDIT: This works, I get the data I need, from each Document. Now I just need to be able to Iterate over the fields and timestamps, and use my model to create a list. How can I do that? Log.d("example", "DocumentSnapshot data: " + document.getData()); this prints: D/example: DocumentSnapshot data: {1558879769={severity=Mild, symptom=Anxiety, comment=Mild anxiety at work., timestamp=1558879769}, 1558879745={severity=Mild, symptom=Anxiety, comment=Feeling relaxed watching TV., timestamp=1558879745}, 1558879710={severity=Moderate, symptom=Anxiety, comment=Walking the cat., timestamp=1558879710}, 1558879827={severity=Moderate, symptom=Anxiety, comment=Taking the cat for a walk., timestamp=1558879827}, 1558888729={severity=Mild, symptom=Anxiety, comment=The cat is fed up with walking., timestamp=1558888729}} Now I just need to get each timestamp array and add them to a seperate list, and i can then do this for each document and have a full list of all the timestamp arrays.

  void getSymptomData() {
     final CollectionReference colRef = db.collection("users").document(user_id).collection("symptom_data");

     colRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
         @Override
         public void onComplete(@NonNull Task<QuerySnapshot> task) {
             if (task.isSuccessful()) {
                 List<String> list = new ArrayList<>();
                 for (QueryDocumentSnapshot document : task.getResult()) {
                     list.add(document.getId());
                     DocumentReference docRef = colRef.document(document.getId());
                     docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                         @Override
                         public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                             if (task.isSuccessful()) {
                                 DocumentSnapshot document = task.getResult();
                                 if (document.exists()) {
                                     Log.d("Iteration", "DocumentSnapshot data: " + document.getData());
                                 } else {
                                     Log.d("NoDoc", "No such document");
                                 }
                             } else {
                                 Log.d("Failed", "get failed with ", task.getException());
                             }
                         }
                     });
                 }
                 Log.d("listylist", list.toString());
             } else {
                 Log.d("tag", "Error getting documents: ", task.getException());
             }
         }
     });

}


来源: stackexchange

问:
java.lang.NoSuchMethodException: <init> [class android.view.View]. getting this error while trying to use button in recycleview
I am trying to make a sample app using the FirebaseRecyclerAdapter but keep getting the error java.lang.NoSuchMethodException:  [class android.view.View]

I am fetching the data from firebase real time database. I but in the recycleview, i can't use any navigation button.

Here is my Activity code:

```<code>
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.location_tracking.Users.Employee;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class AdminPanelActivity extends AppCompatActivity {

    private RecyclerView mEmployeeList;

    private DatabaseReference mEmployeeDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_panel);

        mEmployeeDatabase = FirebaseDatabase.getInstance().getReference().child("Employee");

        mEmployeeList = (RecyclerView) findViewById(R.id.recyclerViewEmplyeeList);
        mEmployeeList.setHasFixedSize(true);
        mEmployeeList.setLayoutManager(new LinearLayoutManager(this));

    }

    @Override
    protected void onStart() {
        super.onStart();

        FirebaseRecyclerAdapter<Employee, EmployeeViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Employee, EmployeeViewHolder>(
                Employee.class,
                R.layout.recycle_list_single_user,
                EmployeeViewHolder.class,
                mEmployeeDatabase
        ) {
            @Override
            protected void populateViewHolder(EmployeeViewHolder viewHolder, Employee model, int position) {

                viewHolder.setName(model.getName());
                viewHolder.setEmployeeImage(model.getImage(), getApplicationContext());
                final String user_id = getRef(position).getKey();
                viewHolder.attendanceButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(AdminPanelActivity.this,AttenadnceActivity.class));
                    }
                });

            }
        };

        mEmployeeList.setAdapter(firebaseRecyclerAdapter);

    }

    public static class EmployeeViewHolder extends RecyclerView.ViewHolder {

        View mView;

        View attendanceButton;

        public EmployeeViewHolder(@NonNull View itemView,View button) {
            super(itemView);
            mView = itemView;
            attendanceButton = (Button) button.findViewById(R.id.button_attendance);
        }

        public void setName(String name) {
            TextView EmployeeNameView = mView.findViewById(R.id.textViewSingleListName);
            EmployeeNameView.setText(name);
        }

        public void setEmployeeImage(String image, Context ctx) {
            CircleImageView EmployeeImageView = (CircleImageView) mView.findViewById(R.id.circleImageViewUserImage);

            Picasso.with(ctx).load(image).placeholder(R.drawable.user_img).into(EmployeeImageView);
        }

    }

}
</code>```

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.firebase:firebase-auth:16.0.5'
    implementation 'com.google.firebase:firebase-database:16.0.4'
    implementation 'com.firebaseui:firebase-ui-database:1.2.0'

    implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.+'
    implementation 'de.hdodenhof:circleimageview:2.2.0'

    implementation 'id.zelory:compressor:2.1.0'

    implementation 'com.squareup.picasso:picasso:2.5.2'

    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'org.greenrobot:eventbus:3.0.0'

    implementation 'com.android.support:recyclerview-v7:28.0.0-alpha3'
    implementation 'com.android.support:gridlayout-v7:28.0.0-alpha3'
    implementation 'com.android.support:cardview-v7:28.0.0-alpha3'

    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'
}

</code>```

My XMl code:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ccc"
    android:layout_margin="5dp"
    android:padding="10dp">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/circleImageViewUserImage"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_marginTop="16dp"
        android:src="@drawable/user_img"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textViewSingleListName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="15dp"
        android:text="Employee Name"
        android:textColor="#000000"
        android:textStyle="bold"
        app:layout_constraintStart_toEndOf="@+id/circleImageViewUserImage"
        app:layout_constraintTop_toTopOf="@+id/circleImageViewUserImage" />

    <Button
        android:id="@+id/button_attendance"
        android:layout_width="wrap_content"
        android:layout_height="36dp"
        android:layout_marginStart="228dp"
        android:layout_marginTop="44dp"
        android:background="@color/red"
        android:padding="7dp"
        android:text="Attendence"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="36dp"
        android:layout_marginStart="72dp"
        android:layout_marginTop="44dp"
        android:background="@color/colorButton"
        android:padding="7dp"
        android:text="Show location"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

Recycleview

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".AdminPanelActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerViewEmplyeeList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="5sp">
    </android.support.v7.widget.RecyclerView>

</LinearLayout>
</code>```

the ERROR:

```<code>    Process: com.example.location_tracking, PID: 8939
    java.lang.RuntimeException: java.lang.NoSuchMethodException: <init> [class android.view.View]
        at com.firebase.ui.database.FirebaseRecyclerAdapter.onCreateViewHolder(FirebaseRecyclerAdapter.java:171)
        at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6748)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5929)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5812)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5808)
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3878)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3595)
        at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1842)
        at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:361)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:925)
        at android.view.Choreographer.doCallbacks(Choreographer.java:737)
        at android.view.Choreographer.doFrame(Choreographer.java:666)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:911)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:6760)
        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:826)
     Caused by: java.lang.NoSuchMethodException: <init> [class android.view.View]
        at java.lang.Class.getConstructor0(Class.java:2320)
        at java.lang.Class.getConstructor(Class.java:1725)
        at com.firebase.ui.database.FirebaseRecyclerAdapter.onCreateViewHolder(FirebaseRecyclerAdapter.java:168)
        at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6748)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5929)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5812)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5808)
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3878)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3595)
        at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1842)
        at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:361)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:925)
        at android.view.Choreographer.doCallbacks(Choreographer.java:737)
        at android.view.Choreographer.doFrame(Choreographer.java:666)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:911)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:6760)
        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:826)
2019-05-26 07:08:46.529 8939-8949/com.example.location_tracking I/zygote64: Do partial code cache collection, code=30KB, data=18KB
2019-05-26 07:08:46.530 8939-8949/com.example.location_tracking I/zygote64: After code cache collection, code=30KB, data=18KB
2019-05-26 07:08:46.530 8939-8949/com.example.location_tracking I/zygote64: Increasing code cache capacity to 128KB
2019-05-26 07:08:46.619 8939-8939/com.example.location_tracking I/Process: Sending signal. PID: 8939 SIG: 9
</code>```

答:
According to the stack info maybe because you customize the ViewHolder constructor but did not create the ViewHolder instance correctly.

This is the README file of FirebaseRecyclerAdapter.

If you got a customized ViewHolder you should override the onCreateViewHolder method to create your EmployeeViewHolder

Here is a similar problem Question like yours, his problem is ViewHolder constructor not public and create ViewHolder failed. So the problem is the Customized ViewHolder instance not create successfully!

I didn't sure this works but you can try it.

```<code>FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Chat, ChatHolder>(options) {
    @Override
    public ChatHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // Create a new instance of the ViewHolder, in this case we are using a custom
        // layout called R.layout.message for each item

        //replace your own layout file R.layout.recycle_list_single_user
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.message, parent, false);

        //create your own EmployeeViewHolder
        return new ChatHolder(view);
    }

    @Override
    protected void onBindViewHolder(ChatHolder holder, int position, Chat model) {
        // Bind the Chat object to the ChatHolder
        // ...
    }
};
</code>```

And last maybe you should replace your constructor from

EmployeeViewHolder(@NonNull View itemView,View button)

to

EmployeeViewHolder(View itemView)

because there is no need to pass second param at all according to the code, you can init the attendanceButton with itemView.findViewById

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a sample app using the FirebaseRecyclerAdapter but keep getting the error java.lang.NoSuchMethodException:  [class android.view.View]

I am fetching the data from firebase real time database. I but in the recycleview, i can't use any navigation button.

Here is my Activity code:

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.location_tracking.Users.Employee;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class AdminPanelActivity extends AppCompatActivity {

    private RecyclerView mEmployeeList;

    private DatabaseReference mEmployeeDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_panel);

        mEmployeeDatabase = FirebaseDatabase.getInstance().getReference().child("Employee");

        mEmployeeList = (RecyclerView) findViewById(R.id.recyclerViewEmplyeeList);
        mEmployeeList.setHasFixedSize(true);
        mEmployeeList.setLayoutManager(new LinearLayoutManager(this));

    }

    @Override
    protected void onStart() {
        super.onStart();

        FirebaseRecyclerAdapter<Employee, EmployeeViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Employee, EmployeeViewHolder>(
                Employee.class,
                R.layout.recycle_list_single_user,
                EmployeeViewHolder.class,
                mEmployeeDatabase
        ) {
            @Override
            protected void populateViewHolder(EmployeeViewHolder viewHolder, Employee model, int position) {

                viewHolder.setName(model.getName());
                viewHolder.setEmployeeImage(model.getImage(), getApplicationContext());
                final String user_id = getRef(position).getKey();
                viewHolder.attendanceButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(AdminPanelActivity.this,AttenadnceActivity.class));
                    }
                });

            }
        };

        mEmployeeList.setAdapter(firebaseRecyclerAdapter);

    }

    public static class EmployeeViewHolder extends RecyclerView.ViewHolder {

        View mView;

        View attendanceButton;

        public EmployeeViewHolder(@NonNull View itemView,View button) {
            super(itemView);
            mView = itemView;
            attendanceButton = (Button) button.findViewById(R.id.button_attendance);
        }

        public void setName(String name) {
            TextView EmployeeNameView = mView.findViewById(R.id.textViewSingleListName);
            EmployeeNameView.setText(name);
        }

        public void setEmployeeImage(String image, Context ctx) {
            CircleImageView EmployeeImageView = (CircleImageView) mView.findViewById(R.id.circleImageViewUserImage);

            Picasso.with(ctx).load(image).placeholder(R.drawable.user_img).into(EmployeeImageView);
        }

    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.firebase:firebase-auth:16.0.5'
    implementation 'com.google.firebase:firebase-database:16.0.4'
    implementation 'com.firebaseui:firebase-ui-database:1.2.0'

    implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.+'
    implementation 'de.hdodenhof:circleimageview:2.2.0'

    implementation 'id.zelory:compressor:2.1.0'

    implementation 'com.squareup.picasso:picasso:2.5.2'

    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'org.greenrobot:eventbus:3.0.0'

    implementation 'com.android.support:recyclerview-v7:28.0.0-alpha3'
    implementation 'com.android.support:gridlayout-v7:28.0.0-alpha3'
    implementation 'com.android.support:cardview-v7:28.0.0-alpha3'

    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'
}

My XMl code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ccc"
    android:layout_margin="5dp"
    android:padding="10dp">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/circleImageViewUserImage"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_marginTop="16dp"
        android:src="@drawable/user_img"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textViewSingleListName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="15dp"
        android:text="Employee Name"
        android:textColor="#000000"
        android:textStyle="bold"
        app:layout_constraintStart_toEndOf="@+id/circleImageViewUserImage"
        app:layout_constraintTop_toTopOf="@+id/circleImageViewUserImage" />

    <Button
        android:id="@+id/button_attendance"
        android:layout_width="wrap_content"
        android:layout_height="36dp"
        android:layout_marginStart="228dp"
        android:layout_marginTop="44dp"
        android:background="@color/red"
        android:padding="7dp"
        android:text="Attendence"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="36dp"
        android:layout_marginStart="72dp"
        android:layout_marginTop="44dp"
        android:background="@color/colorButton"
        android:padding="7dp"
        android:text="Show location"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Recycleview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".AdminPanelActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerViewEmplyeeList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="5sp">
    </android.support.v7.widget.RecyclerView>

</LinearLayout>

the ERROR:

    Process: com.example.location_tracking, PID: 8939
    java.lang.RuntimeException: java.lang.NoSuchMethodException: <init> [class android.view.View]
        at com.firebase.ui.database.FirebaseRecyclerAdapter.onCreateViewHolder(FirebaseRecyclerAdapter.java:171)
        at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6748)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5929)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5812)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5808)
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3878)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3595)
        at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1842)
        at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:361)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:925)
        at android.view.Choreographer.doCallbacks(Choreographer.java:737)
        at android.view.Choreographer.doFrame(Choreographer.java:666)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:911)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:6760)
        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:826)
     Caused by: java.lang.NoSuchMethodException: <init> [class android.view.View]
        at java.lang.Class.getConstructor0(Class.java:2320)
        at java.lang.Class.getConstructor(Class.java:1725)
        at com.firebase.ui.database.FirebaseRecyclerAdapter.onCreateViewHolder(FirebaseRecyclerAdapter.java:168)
        at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6748)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5929)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5812)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5808)
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3878)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3595)
        at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1842)
        at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:361)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:925)
        at android.view.Choreographer.doCallbacks(Choreographer.java:737)
        at android.view.Choreographer.doFrame(Choreographer.java:666)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:911)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:6760)
        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:826)
2019-05-26 07:08:46.529 8939-8949/com.example.location_tracking I/zygote64: Do partial code cache collection, code=30KB, data=18KB
2019-05-26 07:08:46.530 8939-8949/com.example.location_tracking I/zygote64: After code cache collection, code=30KB, data=18KB
2019-05-26 07:08:46.530 8939-8949/com.example.location_tracking I/zygote64: Increasing code cache capacity to 128KB
2019-05-26 07:08:46.619 8939-8939/com.example.location_tracking I/Process: Sending signal. PID: 8939 SIG: 9

Body:
According to the stack info maybe because you customize the ViewHolder constructor but did not create the ViewHolder instance correctly.

This is the README file of FirebaseRecyclerAdapter.

If you got a customized ViewHolder you should override the onCreateViewHolder method to create your EmployeeViewHolder

Here is a similar problem Question like yours, his problem is ViewHolder constructor not public and create ViewHolder failed. So the problem is the Customized ViewHolder instance not create successfully!

I didn't sure this works but you can try it.

FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Chat, ChatHolder>(options) {
    @Override
    public ChatHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // Create a new instance of the ViewHolder, in this case we are using a custom
        // layout called R.layout.message for each item

        //replace your own layout file R.layout.recycle_list_single_user
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.message, parent, false);

        //create your own EmployeeViewHolder
        return new ChatHolder(view);
    }

    @Override
    protected void onBindViewHolder(ChatHolder holder, int position, Chat model) {
        // Bind the Chat object to the ChatHolder
        // ...
    }
};

And last maybe you should replace your constructor from

EmployeeViewHolder(@NonNull View itemView,View button)

to

EmployeeViewHolder(View itemView)

because there is no need to pass second param at all according to the code, you can init the attendanceButton with itemView.findViewById


问:
How to get R function to return multiple values of parameters
I would like that my function would produce values for different values of one of my parameters (in this case CC), so that I can easily turn this into a dataframe.

Here is the code I am using:

```<code>ub_duration <- function(age, cc = c(12, 18, 24), cc_lag, dur,
                        extended) {
    dur = if (age < 30){
        if (cc < 15) return(150)
        if (cc >= 15 & cc < 24) return(210)
        if (cc >= 24) return(330)
    }
    dur = if (age >= 30 & age < 40){
        if (cc < 15) return(180)
        if (cc >= 15 & cc < 24) return(330)
        if (cc >= 24) return(420)
    }
    dur = if (age >= 50){
        if (cc < 15) return(270)
        if (cc >= 15 & cc < 24) return(480)
        if (cc >= 24) return(540)
    }
    return(dur)
}
</code>```

When I call the function, this is what  get

```<code>> ub_duration(25,c(12, 18, 24),0)
[1] 150
Warning message:
In if (cc < 15) return(150) :
the condition has length > 1 and only the first element will be used
</code>```

答:
I think the warning is caused here if (cc < 15) because cc is not a single element but a vector. So you're having something like if (c(TRUE, FALSE, FALSE)). Since if needs one single condition it pics only the first one, which is true.

If you want to evaluate all elements of cc togehter you could check out functions like all or any.

for a little illustration of what i want to say:

```<code>if(c(TRUE, TRUE, FALSE))
{
  print("Entered if")
  # do something
} else {print("Entered else")}
# output:
# [1] "Entered if"
# Warning message:
# In if (c(TRUE, TRUE, FALSE)) { :
# the condition has length > 1 and only the first element will be used

if(c(FALSE, TRUE, FALSE))
{
 print("Entered if")
 # do something
} else {print("Entered else")}
# output:
# [1] "Entered else"
# Warning message:
# In if (c(FALSE, TRUE, FALSE)) { :
# the condition has length > 1 and only the first element will be used
</code>```

a possible workaround might be something like this

```<code>ub_duration <- function(age, cc = c(12, 18, 24), cc_lag, dur,
                        extended) {
# create matrix countaining the desired values
outcome_matrix = data.frame("age_under_30" = c(150, 210, 330), "age_30_to_40" = c(180, 330, 420), "age_over_40" = c(270, 480, 540))
# reduced the highest age limit from 50 to 40. Not sure if this is intendet, but otherwise there would be an undefined gap for age 40 to 50
# check which column is needed for the given age value
coldedect = sum(c(30, 40)<=age)+1
# check wich rows are needed for the given cc values
rowdedect = sapply(cc, function(f) sum(c(14, 24)<=f)+1)
# select values and return them
return(outcome_matrix[rowdedect, coldedect])
}

ub_duration(25,c(12, 18, 24),0)
</code>```

Body:
I would like that my function would produce values for different values of one of my parameters (in this case CC), so that I can easily turn this into a dataframe.

Here is the code I am using:

ub_duration <- function(age, cc = c(12, 18, 24), cc_lag, dur,
                        extended) {
    dur = if (age < 30){
        if (cc < 15) return(150)
        if (cc >= 15 & cc < 24) return(210)
        if (cc >= 24) return(330)
    }
    dur = if (age >= 30 & age < 40){
        if (cc < 15) return(180)
        if (cc >= 15 & cc < 24) return(330)
        if (cc >= 24) return(420)
    }
    dur = if (age >= 50){
        if (cc < 15) return(270)
        if (cc >= 15 & cc < 24) return(480)
        if (cc >= 24) return(540)
    }
    return(dur)
}

When I call the function, this is what  get

> ub_duration(25,c(12, 18, 24),0)
[1] 150
Warning message:
In if (cc < 15) return(150) :
the condition has length > 1 and only the first element will be used

Body:
I think the warning is caused here if (cc < 15) because cc is not a single element but a vector. So you're having something like if (c(TRUE, FALSE, FALSE)). Since if needs one single condition it pics only the first one, which is true.

If you want to evaluate all elements of cc togehter you could check out functions like all or any.

for a little illustration of what i want to say:

if(c(TRUE, TRUE, FALSE))
{
  print("Entered if")
  # do something
} else {print("Entered else")}
# output:
# [1] "Entered if"
# Warning message:
# In if (c(TRUE, TRUE, FALSE)) { :
# the condition has length > 1 and only the first element will be used

if(c(FALSE, TRUE, FALSE))
{
 print("Entered if")
 # do something
} else {print("Entered else")}
# output:
# [1] "Entered else"
# Warning message:
# In if (c(FALSE, TRUE, FALSE)) { :
# the condition has length > 1 and only the first element will be used

a possible workaround might be something like this

ub_duration <- function(age, cc = c(12, 18, 24), cc_lag, dur,
                        extended) {
# create matrix countaining the desired values
outcome_matrix = data.frame("age_under_30" = c(150, 210, 330), "age_30_to_40" = c(180, 330, 420), "age_over_40" = c(270, 480, 540))
# reduced the highest age limit from 50 to 40. Not sure if this is intendet, but otherwise there would be an undefined gap for age 40 to 50
# check which column is needed for the given age value
coldedect = sum(c(30, 40)<=age)+1
# check wich rows are needed for the given cc values
rowdedect = sapply(cc, function(f) sum(c(14, 24)<=f)+1)
# select values and return them
return(outcome_matrix[rowdedect, coldedect])
}

ub_duration(25,c(12, 18, 24),0)


问:
How do I retrieve available phone numbers in Nexmo?
I want to retrieve all available phone voice phone numbers (Phone Numbers only) using a pattern search without all the parameters.

I have tried the api code given by nexmo.  It works, but I only get a limited amount of phone numbers and I am also getting a bunch of other parameters, I don't want.  here are the 2 api calls I am using:

phnumbers = client.get_available_numbers("US", {"features": "VOICE"})
phnumbers = client.get_available_numbers("US", {"pattern": "007", "search_pattern": 2})
```

<p>I just want to have a list of available numbers. I don;t care if it's 1000.  Not sure if there is a way to limit the number it brings back.  Currently getting a limited amount of number with parameters like the following:</p>

<pre class="lang-py prettyprint-override"><code>{'count': 394773, 'numbers': [{'country': 'US', 'msisdn': '12014790696', 'cost': '0.90', 'type': 'mobile-lvn', 'features': ['VOICE', 'SMS']}
</code>```

That's one number.  I only want to tell it give me all the voice numbers and get them in a list...Thank you in advance for your help.

答:
I looked at the docs and I don't think it's possible to only get the phone number (also called msisdn) back.

Instead, for each number, you'll get a thing which includes country, cost, type, etc... , part of, as the docs say, "A paginated array of available numbers and their details".

If you look at the response, you can see that you get count as the first key/value pair, in your example the count is 394773, and this is the total count of numbers available for the search condition you specified when you made the request.

Now, I don't know all the reasons but to send back one response with a payload of 394773 numbers would probably be taxing too much the system.

What you can do:

From my tests, if you specify a size of 100, then you'll get a response with 100 records per page and you have the index parameter which you can use to paginate (anything above 100 for size and you get only 10 records).

So, if the count is 394773 for your search query, with size = 100, we have 3947 + 1 pages (the last page (index = 3948) only has 73 records) and you would have to get them one by one with a total of 3948 requests passing the appropriate index value.

Of course you can reduce the count if you pass a more specific search query.

I understand what you want, and I don't work for Nexmo, and again, after reading the docs I don't think it's possible to get everything back in just one request. You'll just need to be more specific in your search query.

Docs:

Retrieve inbound numbers that are available for the specified country.

Body:
I want to retrieve all available phone voice phone numbers (Phone Numbers only) using a pattern search without all the parameters.

I have tried the api code given by nexmo.  It works, but I only get a limited amount of phone numbers and I am also getting a bunch of other parameters, I don't want.  here are the 2 api calls I am using:

phnumbers = client.get_available_numbers("US", {"features": "VOICE"})
phnumbers = client.get_available_numbers("US", {"pattern": "007", "search_pattern": 2})

I just want to have a list of available numbers. I don;t care if it's 1000.  Not sure if there is a way to limit the number it brings back.  Currently getting a limited amount of number with parameters like the following:

{'count': 394773, 'numbers': [{'country': 'US', 'msisdn': '12014790696', 'cost': '0.90', 'type': 'mobile-lvn', 'features': ['VOICE', 'SMS']}

That's one number.  I only want to tell it give me all the voice numbers and get them in a list...Thank you in advance for your help.


问:
Datatemplate not showing in ListView after being returned by DataTemplateSelector
I am building a Xamarin Forms app and on one of the screens, I am populating a ListView using an ObservableCollection.  The ItemTemplate is selected using a DataTemplateSelector class which is being hit during debugging and returning a DataTemplate.  However I am not seeing the template displaying on the form when it is opened.  I am currently doing my debugging using the UWP interface.

So far, I've tried adding a ListView that has a simple label item template which also doesn't appear to be working as well.  I see that there is a list view item in the Visual Tree though it only contains a ListViewItemPresenter which contains a CellControl.

The property I am binding to is:

public Generators.Parameter.ConfigurationList Parameters { get; }
```

<p>ConfigurationList inherits ObservableCollection:</p>

<pre class="lang-cs prettyprint-override"><code>public class ConfigurationList : ObservableCollection<Configuration>
</code>```

The xaml to display a simple ListView is:

<ListView ItemsSource="{Binding Parameters}">
    <ListView.ItemTemplate>
        <DataTemplate>

        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
```

The full source is available on github here TheRandomizer.Mobile

答:
Immediately after submitting my question I figured it out but thought I would leave it in case anyone else runs into this.  The DataTemplate requires a :</p>

```<code><ListView ItemsSource="{Binding Parameters}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Label Text="Test" />
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

Body:
I am building a Xamarin Forms app and on one of the screens, I am populating a ListView using an ObservableCollection.  The ItemTemplate is selected using a DataTemplateSelector class which is being hit during debugging and returning a DataTemplate.  However I am not seeing the template displaying on the form when it is opened.  I am currently doing my debugging using the UWP interface.

So far, I've tried adding a ListView that has a simple label item template which also doesn't appear to be working as well.  I see that there is a list view item in the Visual Tree though it only contains a ListViewItemPresenter which contains a CellControl.

The property I am binding to is:

public Generators.Parameter.ConfigurationList Parameters { get; }

ConfigurationList inherits ObservableCollection:

public class ConfigurationList : ObservableCollection<Configuration>

The xaml to display a simple ListView is:

<ListView ItemsSource="{Binding Parameters}">
    <ListView.ItemTemplate>
        <DataTemplate>

        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

The full source is available on github here TheRandomizer.Mobile

Body:
Immediately after submitting my question I figured it out but thought I would leave it in case anyone else runs into this.  The DataTemplate requires a :

<ListView ItemsSource="{Binding Parameters}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Label Text="Test" />
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>


问:
Programmatically get height of navigation bar
I know that the presence of the more view controller (navigation bar) pushes down the UIView by its height.  I also know that this height = 44px.  I have also discovered that this push down maintains the [self.view].frame.origin.y = 0.

So how do I determine the height of this navigation bar, other than just setting it to a constant?

Or, shorter version, how do I determine that my UIView is showing with the navigation bar on top?

The light bulb started to come on. Unfortunately, I have not discovered a uniform way to correct the problem, as described below.

I believe that my whole problem centers on my autoresizingMasks. And the reason I have concluded that is the same symptoms exist, with or without a UIWebView. And that symptom is that everything is peachy for Portrait. For Landscape, the bottom-most UIButton pops down behind the TabBar.

For example, on one UIView, I have, from top to bottom:

UIView – both springs set (default case) and no struts

UIScrollView - If I set the two springs, and clear everything else (like the UIView), then the UIButton intrudes on the object immediately above it. If I clear everything, then UIButton is OK, but the stuff at the very top hides behind the StatusBar Setting only the top strut, the UIButton pops down behind the Tab Bar.

UILabel and UIImage next vertically – top strut set, flexible everywhere else

Just to complete the picture for the few that have a UIWebView:

UIWebView - Struts: top, left, right Springs: both

UIButton – nothing set, i.e., flexible everywhere

Although my light bulb is dim, there appears to be hope.

Please bear with me because I needed more room than that provided for a short reply comment.

Thanks for trying to understand what I am really fishing for ... so here goes.

1) Each UIViewController (a TabBar app) has a UIImage, some text and whatever on top. Another common denominator is a UIButton on the bottom. On some of the UIViewControllers I have a UIWebView above the UIButton.

So, UIImage, text etc. UIWebView (on SOME) UIButton

Surrounding all the above is a UIScrollView.

2) For those that have a UIWebView, its autoresizingMask looks like:

```<code>   —
   |
   —

   ^
   |
   |
</code>```

|—| ←----→ |—|
       |
       |
       V
The UIButton's mask has nothing set, i.e., flexible everywhere

Within my -viewDidLoad, I call my -repositionSubViews within which I do the following:

If there is no UIWebView, I do nothing except center the UIButton that I placed with IB.

If I do have a UIWebView, then I determine its *content*Height and set its frame to enclose the entire content.

```<code>UIScrollView *scrollViewInsideWebView = [[webView_ subviews] lastObject];
webViewContentHeight = scrollViewInsideWebView.contentSize.height;
[webView_ setFrame:CGRectMake(webViewOriginX, webViewOriginY,
                          sameWholeViewScrollerWidth, webViewContentHeight)]
</code>```

Once I do that, then I programmatically push the UIButton down so that it ends up placed below the UIWebView.

Everything works, until I rotate it from Portrait to Landscape.

I call my -repositionSubViews within my -didRotateFromInterfaceOrientation.

Why does the content height of my UIWebView not change with rotation?.

From Portrait to Landscape, the content width should expand and the content height should shrink. It does visually as it should, but not according to my NSLog.

Anyway, with or without a UIWebView, the button I've talked about moves below the TabBar when in Landscape mode but it will not scroll up to be seen. I see it behind the TabBar when I scroll "vigorously", but then it "falls back" behind the TabBar.

Bottom line, this last is the reason I've asked about the height of the TabBar and the NavigationBar because the TabBar plants itself at the bottom of the UIView and the NavigationBar pushes the UIView down.

Now, I'm going to add a comment or two here because they wouldn't have made sense earlier.

With no UIWebView, I leave everything as is as seen by IB.

With a UIWebView, I increase the UIWebView's frame.height to its contentHeight and also adjust upward the height of the surrounding UIScrollView that surrounds all the sub-views.

Well there you have it.

答:
My application has a couple views that required a customized navigation bar in the UI for look & feel, however without navigation controller. And the application is required to support iOS version prior to iOS 11, so the handy safe area layout guide could not be used, and I have to adjust the position and height of navigation bar programmatically.

I attached the Navigation Bar to its superview directly, skipping the safe area layout guide as mentioned above. And the status bar height could be retrieved from UIApplication easily, but the default navigation bar height is really a pain-ass...

It struck me for almost half a night, with a number of searching and testing, until I finally got the hint from another post (not working to me though), that you could actually get the height from UIView.sizeThatFits(), like this:

```<code>- (void)viewWillLayoutSubviews {
    self.topBarHeightConstraint.constant = [UIApplication sharedApplication].statusBarFrame.size.height;
    self.navBarHeightConstraint.constant = [self.navigationBar sizeThatFits:CGSizeZero].height;

    [super viewWillLayoutSubviews];
}
</code>```

Finally, a perfect navigation bar looking exactly the same as the built-in one!

ContentLicense: CC BY-SA 3.0

Body:
I know that the presence of the more view controller (navigation bar) pushes down the UIView by its height.  I also know that this height = 44px.  I have also discovered that this push down maintains the [self.view].frame.origin.y = 0.

So how do I determine the height of this navigation bar, other than just setting it to a constant?

Or, shorter version, how do I determine that my UIView is showing with the navigation bar on top?

The light bulb started to come on. Unfortunately, I have not discovered a uniform way to correct the problem, as described below.

I believe that my whole problem centers on my autoresizingMasks. And the reason I have concluded that is the same symptoms exist, with or without a UIWebView. And that symptom is that everything is peachy for Portrait. For Landscape, the bottom-most UIButton pops down behind the TabBar.

For example, on one UIView, I have, from top to bottom:

UIView – both springs set (default case) and no struts

UIScrollView - If I set the two springs, and clear everything else (like the UIView), then the UIButton intrudes on the object immediately above it. If I clear everything, then UIButton is OK, but the stuff at the very top hides behind the StatusBar Setting only the top strut, the UIButton pops down behind the Tab Bar.

UILabel and UIImage next vertically – top strut set, flexible everywhere else

Just to complete the picture for the few that have a UIWebView:

UIWebView - Struts: top, left, right Springs: both

UIButton – nothing set, i.e., flexible everywhere

Although my light bulb is dim, there appears to be hope.

Please bear with me because I needed more room than that provided for a short reply comment.

Thanks for trying to understand what I am really fishing for ... so here goes.

1) Each UIViewController (a TabBar app) has a UIImage, some text and whatever on top. Another common denominator is a UIButton on the bottom. On some of the UIViewControllers I have a UIWebView above the UIButton.

So, UIImage, text etc. UIWebView (on SOME) UIButton

Surrounding all the above is a UIScrollView.

2) For those that have a UIWebView, its autoresizingMask looks like:

   —
   |
   —

   ^
   |
   |

|—| ←----→ |—|
       |
       |
       V
The UIButton's mask has nothing set, i.e., flexible everywhere

Within my -viewDidLoad, I call my -repositionSubViews within which I do the following:

If there is no UIWebView, I do nothing except center the UIButton that I placed with IB.

If I do have a UIWebView, then I determine its *content*Height and set its frame to enclose the entire content.

UIScrollView *scrollViewInsideWebView = [[webView_ subviews] lastObject];
webViewContentHeight = scrollViewInsideWebView.contentSize.height;
[webView_ setFrame:CGRectMake(webViewOriginX, webViewOriginY,
                          sameWholeViewScrollerWidth, webViewContentHeight)]

Once I do that, then I programmatically push the UIButton down so that it ends up placed below the UIWebView.

Everything works, until I rotate it from Portrait to Landscape.

I call my -repositionSubViews within my -didRotateFromInterfaceOrientation.

Why does the content height of my UIWebView not change with rotation?.

From Portrait to Landscape, the content width should expand and the content height should shrink. It does visually as it should, but not according to my NSLog.

Anyway, with or without a UIWebView, the button I've talked about moves below the TabBar when in Landscape mode but it will not scroll up to be seen. I see it behind the TabBar when I scroll "vigorously", but then it "falls back" behind the TabBar.

Bottom line, this last is the reason I've asked about the height of the TabBar and the NavigationBar because the TabBar plants itself at the bottom of the UIView and the NavigationBar pushes the UIView down.

Now, I'm going to add a comment or two here because they wouldn't have made sense earlier.

With no UIWebView, I leave everything as is as seen by IB.

With a UIWebView, I increase the UIWebView's frame.height to its contentHeight and also adjust upward the height of the surrounding UIScrollView that surrounds all the sub-views.

Well there you have it.

Body:
My application has a couple views that required a customized navigation bar in the UI for look & feel, however without navigation controller. And the application is required to support iOS version prior to iOS 11, so the handy safe area layout guide could not be used, and I have to adjust the position and height of navigation bar programmatically.

I attached the Navigation Bar to its superview directly, skipping the safe area layout guide as mentioned above. And the status bar height could be retrieved from UIApplication easily, but the default navigation bar height is really a pain-ass...

It struck me for almost half a night, with a number of searching and testing, until I finally got the hint from another post (not working to me though), that you could actually get the height from UIView.sizeThatFits(), like this:

- (void)viewWillLayoutSubviews {
    self.topBarHeightConstraint.constant = [UIApplication sharedApplication].statusBarFrame.size.height;
    self.navBarHeightConstraint.constant = [self.navigationBar sizeThatFits:CGSizeZero].height;

    [super viewWillLayoutSubviews];
}

Finally, a perfect navigation bar looking exactly the same as the built-in one!


问:
How to remove unmatched data from two data frames, to create a new data frame in R
I am creating a graph that correlates the life expectancy age and the state pension age for each country. I have used web scraping packages to scrape 2 datasets from 2 Wikipedia pages.

One of the datasets contains the column "Country" and the other dataset contains the column "Country and regions". This is a problem because both datasets need to merge but are unbalanced due to the regions in the "Country and regions" column.

To solve this, I need to remove the regions in "Country and regions", before merging the datasets, so it is balanced. I need to find the unmatched data from "Country and regions" with "Country", remove it, and create one data frame with the 2 datasets.

```<code>library(xml2)
library(rvest)
library(stringr)

urlLifeExpectancy <- "https://en.wikipedia.org/wiki/List_of_countries_by_life_expectancy"

extractedLifeData = urlLifeExpectancy %>%
  read_html() %>%
  html_node(xpath = '//*[@id="mw-content-text"]/div/table[1]') %>%
  html_table(fill = TRUE)

urlPensionAge <- "https://en.wikipedia.org/wiki/Retirement_age#Retirement_age_by_country"

extractedPensionData = urlPensionAge %>%
  read_html() %>%
  html_node(xpath = '//*[@id="mw-content-text"]/div/table[3]') %>%
  html_table(fill = TRUE)
</code>```

答:
We can use join from data.table

```<code>library(data.table)
setDT(extractedLifeData[c(1, 5, 7)][extractedPensionDate[1:3],
       on = .(Country = `Country and regions`)]
</code>```

Body:
I am creating a graph that correlates the life expectancy age and the state pension age for each country. I have used web scraping packages to scrape 2 datasets from 2 Wikipedia pages.

One of the datasets contains the column "Country" and the other dataset contains the column "Country and regions". This is a problem because both datasets need to merge but are unbalanced due to the regions in the "Country and regions" column.

To solve this, I need to remove the regions in "Country and regions", before merging the datasets, so it is balanced. I need to find the unmatched data from "Country and regions" with "Country", remove it, and create one data frame with the 2 datasets.

library(xml2)
library(rvest)
library(stringr)

urlLifeExpectancy <- "https://en.wikipedia.org/wiki/List_of_countries_by_life_expectancy"

extractedLifeData = urlLifeExpectancy %>%
  read_html() %>%
  html_node(xpath = '//*[@id="mw-content-text"]/div/table[1]') %>%
  html_table(fill = TRUE)

urlPensionAge <- "https://en.wikipedia.org/wiki/Retirement_age#Retirement_age_by_country"

extractedPensionData = urlPensionAge %>%
  read_html() %>%
  html_node(xpath = '//*[@id="mw-content-text"]/div/table[3]') %>%
  html_table(fill = TRUE)

Body:
We can use join from data.table

library(data.table)
setDT(extractedLifeData[c(1, 5, 7)][extractedPensionDate[1:3],
       on = .(Country = `Country and regions`)]


问:
Update form with foreign key Laravel
I have a form that contains 3 data. One data is a data from another table that has been linked using a foreign key. What should I add so that the data in the table that has been saved can appear in the edit form and can update it?

View

```<code><div class="col-xs-12 col-sm-12 col-md-12">
  <div class="form-group">
    <strong>Kelas:</strong>
    {!! Form::select('idkelas', $kelas_theresia, [], array('class' => 'form-control')) !!}
  </div>
</div>
</code>```

Controller

```<code>public function edit($id)
    {
        $kamar_theresia = Kamar_Theresia::find($id);
        $kelas_theresia = Kelas_Theresia::pluck('name','id')->all();
        return view('kamar_theresia.edit',compact('kamar_theresia','kelas_theresia'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */

    public function update(Request $request, $id)
    {
         request()->validate([
            'nama' => 'required',
            'idkelas' => 'required',
            'ketersediaan' => 'required',
        ]);

        $input = $request->all();
        $kamar_theresia = Kamar_Theresia::find($id);
        $kamar_theresia->update($input);

        return redirect()->route('kamar_theresia.index')
                        ->with('success','Kamar Theresia updated successfully');
    }
</code>```

答:
Take a look for the documentation in the "Recursively Saving Models & Relationships" section:

```<code>  https://laravel.com/docs/5.8/eloquent-relationships#inserting-and-updating-related-models
</code>```

This is an example:

```<code>$client = Client::find($id);
$client->name = "Daniel";
$client->addressInfo->street = 'Daniel's street';
$client->push();
</code>```

Regards

Title: Update form with foreign key Laravel

Body:
I have a form that contains 3 data. One data is a data from another table that has been linked using a foreign key. What should I add so that the data in the table that has been saved can appear in the edit form and can update it?

View

    Kelas:
    {!! Form::select('idkelas', $kelas_theresia, [], array('class' => 'form-control')) !!}

Controller

public function edit($id)
    {
        $kamar_theresia = Kamar_Theresia::find($id);
        $kelas_theresia = Kelas_Theresia::pluck('name','id')->all();
        return view('kamar_theresia.edit',compact('kamar_theresia','kelas_theresia'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */

    public function update(Request $request, $id)
    {
         request()->validate([
            'nama' => 'required',
            'idkelas' => 'required',
            'ketersediaan' => 'required',
        ]);

        $input = $request->all();
        $kamar_theresia = Kamar_Theresia::find($id);
        $kamar_theresia->update($input);

        return redirect()->route('kamar_theresia.index')
                        ->with('success','Kamar Theresia updated successfully');
    }

Body:
Take a look for the documentation in the "Recursively Saving Models & Relationships" section:

  https://laravel.com/docs/5.8/eloquent-relationships#inserting-and-updating-related-models

This is an example:

$client = Client::find($id);
$client->name = "Daniel";
$client->addressInfo->street = 'Daniel's street';
$client->push();

Regards


问:
Unable to connect to AWS-RDS MySql Database
When creating the database in AWS RDS console, I can connect to the database using MySql Workbench, but after some time, when restarting the MySql Workbench and try to connect to the same database then I am getting an error Your connection attempt failed for user 'username' from your host to server at <endpoint>.

This is strange, but I am facing this issue, don't know why. I tried to be logged in to AWS when connecting to the database.

Also, when I try to connect from my PHP script, it always gets Timed Out, even for the first time.

Link to my demo site:- http://phpdynamicappone-env.xgbztdyxar.us-west-2.elasticbeanstalk.com/ (click on view posts)

答:
There are two cases to connect with an AWS RDS -

Publicly -

1. You need to select the Publicly Accessible option in RDS configuration.

2. Your RDS Security group, needs to allow MYSQL traffic from your
local/server/security group

Private -

1. If your RDS is Private, you'll need to create a Bastion Host.

2. Allow MYSQL Traffic to RDS, from the Bastion Host's Security group.

3. Allow SSH Traffic from your local, to the Bastion Host's Security group

4. Create Tunneling to your RDS via Bastion Host,

This can be done via using "Standard TCP/IP over SSH" method in MySql Workbench


问:
Materialize CSS - Select Doesn't Seem to Render
I am currently working with materialize CSS and it seems I've gotten snagged with the select fields.

I'm using the example provided from their site but unfortunately it it's rendering in the view whatsoever.  I was wondering if someone else might be able to help.

What I am trying to do is create a row with 2 end spacers that provide padding - then within the inner two row items there should be a search text input and a search select dropdown.

This is the example I'm working from: http://materializecss.com/forms.html

Thank you in advance.

Here is the snippet of code in question.

```<code><div class="row">
<form class="col s12">
    <div class="row">
        <div class="input-field col s2"></div>
        <div class="input-field col s5">
            <input id="icon_prefix" type="text" class="validate" />
            <label for="icon_prefix">Search</label>
        </div>
        <div class="input-field col s3">
            <label>Materialize Select</label>
            <select>
                <option value="" disabled="disabled" selected="selected">Choose your option</option>
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
            </select>
        </div>
        <div class="input-field col s2"></div>
    </div>
</form>
</code>```

答:
Only this worked for me:</p>

```<code>$(document).ready(function(){
    $('select').not('.disabled').formSelect();
});
</code>```

Body:
I am currently working with materialize CSS and it seems I've gotten snagged with the select fields.

I'm using the example provided from their site but unfortunately it it's rendering in the view whatsoever.  I was wondering if someone else might be able to help.

What I am trying to do is create a row with 2 end spacers that provide padding - then within the inner two row items there should be a search text input and a search select dropdown.

This is the example I'm working from: http://materializecss.com/forms.html

Thank you in advance.

Here is the snippet of code in question.

<form class="col s12">

            <input id="icon_prefix" type="text" class="validate" />
            Search

            Materialize Select
            <select>
                <option value="" disabled="disabled" selected="selected">Choose your option</option>
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
            </select>

</form>

Body:
Only this worked for me:

$(document).ready(function(){
    $('select').not('.disabled').formSelect();
});


问:
When git rebasing two branches with some shared history, is there an easy way to have the common history remain common?
Suppose we have the following revision graph:

```<code>A-X-Z--B
     \
      \-C
</code>```

with A preceding both B and C. Further suppose I rebase A from upstream, creating a new commit A*, and then rebase both B and C onto A*. The resulting revision graph is the following:

```<code>A*-X'-Z'-B
 \
  \-X"-Z"-C
</code>```

Note that the shared history is no longer shared. Is there a simple way to fix this, other than, say, rebasing B and then rebasing C onto Z' explicitly. In other words is there a better way to automatically rebase multiple branches at the same time in order to preserve shared history? It just seems a little bit awkward to have to either artificially place a tag at the split point, or manually inspect the graph to find out sha1 of the commit on which to rebase C to keep the shared history, not to mention opening up the possibility of mistakes, especially since I have to do this every time I rebase until I check the changes into the upstream branch.

答:
```<code>git rebase --committer-date-is-author-date --preserve-merges --onto A* A C
git rebase --committer-date-is-author-date --preserve-merges --onto A* A B
</code>```

This should keep the common commits having the same sha1 and any merges preserved. Preserve merges is not required in this case, but will become an issue with a less trivial history.

To do this for all branches that contain A in their history do:

```<code>git branch --contains A | xargs -n 1 git rebase --committer-date-is-author-date --preserve-merges --onto A* A
</code>```

Hope this helps.

UPDATE:

This may be cleaner syntax:

```<code>for branch in $(git branch --contains A); do git rebase --committer-date-is-author-date --preserve-merges --onto A* A $branch; done
</code>```

Body:
Suppose we have the following revision graph:

A-X-Z--B
     \
      \-C

with A preceding both B and C. Further suppose I rebase A from upstream, creating a new commit A*, and then rebase both B and C onto A*. The resulting revision graph is the following:

A*-X'-Z'-B
 \
  \-X"-Z"-C

Note that the shared history is no longer shared. Is there a simple way to fix this, other than, say, rebasing B and then rebasing C onto Z' explicitly. In other words is there a better way to automatically rebase multiple branches at the same time in order to preserve shared history? It just seems a little bit awkward to have to either artificially place a tag at the split point, or manually inspect the graph to find out sha1 of the commit on which to rebase C to keep the shared history, not to mention opening up the possibility of mistakes, especially since I have to do this every time I rebase until I check the changes into the upstream branch.

Body:
git rebase --committer-date-is-author-date --preserve-merges --onto A* A C
git rebase --committer-date-is-author-date --preserve-merges --onto A* A B

This should keep the common commits having the same sha1 and any merges preserved. Preserve merges is not required in this case, but will become an issue with a less trivial history.

To do this for all branches that contain A in their history do:

git branch --contains A | xargs -n 1 git rebase --committer-date-is-author-date --preserve-merges --onto A* A

Hope this helps.

UPDATE:

This may be cleaner syntax:

for branch in $(git branch --contains A); do git rebase --committer-date-is-author-date --preserve-merges --onto A* A $branch; done


问:
Excel: Sum duplicates values only once and only on visible cells
Given the following FILTERED table :

```<code>TYPE    NUM
A       3
A       3
A       3
B       5
B       5
</code>```

I need to find the sum of column NUM without including the duplicate values.
I currently have the following solution based on another post:

=SUMPRODUCT(B2:B6/COUNTIFS(A2:A6,A2:A6))

In this case, the result is 8, which is correct when no filters have been applied.

Now if I filter the column to show only A in TYPE, it will still show me 8. The issue I am having is I need the sum to be adjusted based on what is visible. After applying the filter to show only A, I should be getting 3 and if I filter to show B only I should get 5. I've tried AGGREGATE and SUBTOTAL and haven't gotten anywhere.

Is there a way to adjust the above formula to VISIBLE cells only?

Thanks,

答:
So, try this:

The drop down validation picks either A or B, but you can change that.
The formula is :

```<code>=SUMIFS(B2:B6,A2:A6,D2)/COUNTIFS(A2:A6,D2)
</code>```

Edit, based on re-reading the question, I think this might be closer:

Body:
Given the following FILTERED table :

TYPE    NUM
A       3
A       3
A       3
B       5
B       5

I need to find the sum of column NUM without including the duplicate values.
I currently have the following solution based on another post:

=SUMPRODUCT(B2:B6/COUNTIFS(A2:A6,A2:A6))

In this case, the result is 8, which is correct when no filters have been applied.

Now if I filter the column to show only A in TYPE, it will still show me 8. The issue I am having is I need the sum to be adjusted based on what is visible. After applying the filter to show only A, I should be getting 3 and if I filter to show B only I should get 5. I've tried AGGREGATE and SUBTOTAL and haven't gotten anywhere.

Is there a way to adjust the above formula to VISIBLE cells only?

Thanks,

Body:
So, try this:

The drop down validation picks either A or B, but you can change that.
The formula is :

=SUMIFS(B2:B6,A2:A6,D2)/COUNTIFS(A2:A6,D2)

Edit, based on re-reading the question, I think this might be closer:


问:
How to use a vector when indexing columns?
So basically, I have a vector:

Note, thetitanic is a data frame of the people who attended the titanic.

```<code>femalesurvivors_1 <- thetitanic[(thetitanic$Sex=="female") & (thetitanic$Survived==1) & (thetitanic$PClass=="1st"),]
</code>```

This shows the female survivors of the 1st class. However, now I only want the female survivors of the 1st class who are above 18 years of age. So:

I want to also index (thetitanic$Sex>=18)

I have been trying some forms of code but I keep getting errors.
x <- thetitanic[(femalesurvivors_1) & (thetitanic$Age>=18)]

The error shows: 1: In Ops.factor(left, right) : '&' not meaningful for factors

Am I able to pass through a vector when doing? Or would I have to make a new vector and repeat code?

I am trying to return the value of female survivors in the 1st class, who are above 18 years age.

I am a noob.. Any help would be appreciated. Thank you.

答:
An option with data.table

```<code>library(data.table)
nrow(setDT(thetitanic)[Survived == 1 & Sex == "Female" & Pclass == 1 & Age >= 18])
</code>```

Body:
So basically, I have a vector:

Note, thetitanic is a data frame of the people who attended the titanic.

femalesurvivors_1 <- thetitanic[(thetitanic$Sex=="female") & (thetitanic$Survived==1) & (thetitanic$PClass=="1st"),]

This shows the female survivors of the 1st class. However, now I only want the female survivors of the 1st class who are above 18 years of age. So:

I want to also index (thetitanic$Sex>=18)

I have been trying some forms of code but I keep getting errors.
x <- thetitanic[(femalesurvivors_1) & (thetitanic$Age>=18)]

The error shows: 1: In Ops.factor(left, right) : '&' not meaningful for factors

Am I able to pass through a vector when doing? Or would I have to make a new vector and repeat code?

I am trying to return the value of female survivors in the 1st class, who are above 18 years age.

I am a noob.. Any help would be appreciated. Thank you.

Body:
An option with data.table

library(data.table)
nrow(setDT(thetitanic)[Survived == 1 & Sex == "Female" & Pclass == 1 & Age >= 18])


问:
Vue variables not reactive in children of extended TypeScript parent class
I very recently started playing around with TypeScript on my Vue.js projects. For my current project (a very simple chat application) I have created a TypeScript class called ChatParent.ts. It contains all methods and variables necessary for sending/receiving messages. I extend this class in my other components. Calling the parent methods from these child class works fine, however, when I monitor a variable in the parent class (e.g., username) the change is not reflected in the DOM of the child component.

I have tried adding setter/getter methods and computed properties (e.g., get methodName(): boolean), neither of which works.

The code below is from ChatParent.ts and has been simplified.

```<code>@Component({
    name: "ChatParent",
})
 export default class ChatParent extends Vue {
    private chatClient: new ChatClient(...);
    subscribed: boolean = false;

    username: string = "";

    subscribe() {
        const subscriptionRequest = new SubscriptionRequest();
        subscriptionRequest.setUsername(username);

        this.chatClient.subscribe(subscriptionRequest).on("data", data => {
            this.subscribed = true;
        });
    }
    ...
}
</code>```

The following is from TypeBox.vue.

```<code><template>
    <v-container pa-2>
        <v-textarea
                outline
                label="Type message here..."
                :disabled="!subscribed"
                v-model="message"
        ></v-textarea>
    </v-container>

</template>

<script lang="ts">
    import {Component} from "vue-property-decorator";
    import ChatParent from "@/components/ChatParent.ts";

    @Component({
        name: "TypeBox",
    })
    export default class TypeBox extends ChatParent {
        message : string = "";
    }
</script>
</code>```

Whenever the data callback is called in the subscribe(...) method, the subscription variable gets updated in the parent class, but the change is not reflected in the child component (where it is supposed to enable the text area if the subscribe variable is true).

I think that my understanding of Vue + TypeScript is perhaps completely incorrect (with regards to extending classes). I would, therefore, really appreciate some insight.

答:
It seems I did not understand the use of extending classes in Vue/TypeScript correctly. The variable data is not shared amongst all classes that extend the parent class (ChatParent), which is why the variables did not trigger DOM changes.

I solved this problem by using Vuex as follows:

```<code>  class ChatModule extends VuexModule {
  // Variables
  chatClient!: ChatClient;
  subscribed: boolean = false;
  username: string = "";
  messages: string = "";

  // Getters
  get getUsername(): string {
    return this.username;
  }

  get getMessages(): string {
    return this.messages;
  }

  get isSubscribed(): boolean {
    return this.subscribed;
  }

  // Mutations and Actions
  ...

  export default getModule(ChatModule);
}
</code>```

The Vuex store contains all the variables. The TypeBox.vue component now simply extends Vue and calls store actions/getters:

```<code><script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import chat from "@/store/modules/chat";
@Component({
  name: "TypeBox"
})
export default class TypeBox extends Vue {
  private message: string = "";
  clearMessage(): void {
    this.message = "";
  }
  sendMessage(message: string): void {
    chat.sendMessage(message);
  }
  get isSubscribed(): boolean {
    return chat.isSubscribed;
  }
}
</script>
</code>```

The Vuex store actions/getters/mutations can be made Type Safe by using the vuex-module-decorators npm module.

For more details, see my GitHub repository.

Body:
I very recently started playing around with TypeScript on my Vue.js projects. For my current project (a very simple chat application) I have created a TypeScript class called ChatParent.ts. It contains all methods and variables necessary for sending/receiving messages. I extend this class in my other components. Calling the parent methods from these child class works fine, however, when I monitor a variable in the parent class (e.g., username) the change is not reflected in the DOM of the child component.

I have tried adding setter/getter methods and computed properties (e.g., get methodName(): boolean), neither of which works.

The code below is from ChatParent.ts and has been simplified.

@Component({
    name: "ChatParent",
})
 export default class ChatParent extends Vue {
    private chatClient: new ChatClient(...);
    subscribed: boolean = false;

    username: string = "";

    subscribe() {
        const subscriptionRequest = new SubscriptionRequest();
        subscriptionRequest.setUsername(username);

        this.chatClient.subscribe(subscriptionRequest).on("data", data => {
            this.subscribed = true;
        });
    }
    ...
}

The following is from TypeBox.vue.

<template>
    <v-container pa-2>
        <v-textarea
                outline
                label="Type message here..."
                :disabled="!subscribed"
                v-model="message"
        ></v-textarea>
    </v-container>

</template>

Whenever the data callback is called in the subscribe(...) method, the subscription variable gets updated in the parent class, but the change is not reflected in the child component (where it is supposed to enable the text area if the subscribe variable is true).

I think that my understanding of Vue + TypeScript is perhaps completely incorrect (with regards to extending classes). I would, therefore, really appreciate some insight.

Body:
It seems I did not understand the use of extending classes in Vue/TypeScript correctly. The variable data is not shared amongst all classes that extend the parent class (ChatParent), which is why the variables did not trigger DOM changes.

I solved this problem by using Vuex as follows:

  class ChatModule extends VuexModule {
  // Variables
  chatClient!: ChatClient;
  subscribed: boolean = false;
  username: string = "";
  messages: string = "";

  // Getters
  get getUsername(): string {
    return this.username;
  }

  get getMessages(): string {
    return this.messages;
  }

  get isSubscribed(): boolean {
    return this.subscribed;
  }

  // Mutations and Actions
  ...

  export default getModule(ChatModule);
}

The Vuex store contains all the variables. The TypeBox.vue component now simply extends Vue and calls store actions/getters:

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import chat from "@/store/modules/chat";
@Component({
  name: "TypeBox"
})
export default class TypeBox extends Vue {
  private message: string = "";
  clearMessage(): void {
    this.message = "";
  }
  sendMessage(message: string): void {
    chat.sendMessage(message);
  }
  get isSubscribed(): boolean {
    return chat.isSubscribed;
  }
}
</script>

The Vuex store actions/getters/mutations can be made Type Safe by using the vuex-module-decorators npm module.

For more details, see my GitHub repository.


问:
What does type signature for `undefined` mean in Haskell?
I am a beginner in Haskell and I am taken aback by the undefined function's type signature.

I expected something more simple, but I found this on Hackage:

```<code>undefined :: forall (r :: RuntimeRep). forall (a :: TYPE r). HasCallStack => a
</code>```

A special case of error. It is expected that compilers will recognize this and insert error messages which are more appropriate to the context in which undefined appears.

Could you please explain what does this signature mean?

Thanks!

答:
For all regards a beginner needs to know, the signature is simply

```<code>undefined :: a
</code>```

which means, as always with type variables (i.e. any lowercase letters) that a is universally quantified, which can also be made explicit:

```<code>{-# LANGUAGE ExplicitForall #-}
undefined :: forall a. a
</code>```

...or, as I prefer to write it

```<code>{-# LANGUAGE ExplicitForall, UnicodeSyntax #-}
undefined :: ∀ a. a
</code>```

The quantification is infered to be over all types, i.e. all things with kind * (read: “type”, more accurate the kind of lifted types – lifted meaning it can be lazy thunk). Therefore, you can use undefined in any expression, no matter what type is required.

Now, undefined is of course a “partial function” like thing, basically a function which zero arguments which is defined nowhere. (FTR, it's not a function, as a function by definition has argument[s].)

You'd like to get a useful error message when it is actually evaluated, but GHC doesn't by default produce a call stack for everything (for performance reasons), so it used to be the case that the error message was almost completely useless. That's where the HasCallStack comes in: that's a constraint which essentially tells the context in which some code might incur undefined that it should note the place where it happens, in order for the error message to actually show it up. So,

```<code>undefined :: ∀ a. HasCallStack => a
</code>```

It's a bit confusing that the HasCallStack appears after the ∀ a – this doesn't really have anything to do with a but with the context in which undefined will be used. Just, the form of signatures is always

```<i>Identifier</i> :: <i>Quantifiers</i>. <i>Constraints</i> => <i>Type</i>```

and HasCallStack is a constraint, that's why it appears in the middle. (More often, constraints actually apply to one of the type variables you've quantified over.)

Finally, this RunTimeRep stuff is about levity polymorphism. I don't really understand that myself, but it's discussed in Why is the undefined function levity-polymorphic when using it with unboxed types?

Body:
I am a beginner in Haskell and I am taken aback by the undefined function's type signature.

I expected something more simple, but I found this on Hackage:

undefined :: forall (r :: RuntimeRep). forall (a :: TYPE r). HasCallStack => a

A special case of error. It is expected that compilers will recognize this and insert error messages which are more appropriate to the context in which undefined appears.

Could you please explain what does this signature mean?

Thanks!

Body:
For all regards a beginner needs to know, the signature is simply

undefined :: a

which means, as always with type variables (i.e. any lowercase letters) that a is universally quantified, which can also be made explicit:

{-# LANGUAGE ExplicitForall #-}
undefined :: forall a. a

...or, as I prefer to write it

{-# LANGUAGE ExplicitForall, UnicodeSyntax #-}
undefined :: ∀ a. a

The quantification is infered to be over all types, i.e. all things with kind * (read: “type”, more accurate the kind of lifted types – lifted meaning it can be lazy thunk). Therefore, you can use undefined in any expression, no matter what type is required.

Now, undefined is of course a “partial function” like thing, basically a function which zero arguments which is defined nowhere. (FTR, it's not a function, as a function by definition has argument[s].)

You'd like to get a useful error message when it is actually evaluated, but GHC doesn't by default produce a call stack for everything (for performance reasons), so it used to be the case that the error message was almost completely useless. That's where the HasCallStack comes in: that's a constraint which essentially tells the context in which some code might incur undefined that it should note the place where it happens, in order for the error message to actually show it up. So,

undefined :: ∀ a. HasCallStack => a

It's a bit confusing that the HasCallStack appears after the ∀ a – this doesn't really have anything to do with a but with the context in which undefined will be used. Just, the form of signatures is always

Identifier :: Quantifiers. Constraints => Type

and HasCallStack is a constraint, that's why it appears in the middle. (More often, constraints actually apply to one of the type variables you've quantified over.)

Finally, this RunTimeRep stuff is about levity polymorphism. I don't really understand that myself, but it's discussed in Why is the undefined function levity-polymorphic when using it with unboxed types?


问:
Do we need .NET framework for installing windows app in Client Machine?
Can any one help me regarding this ? Is it mandatory?</p>

答: Yes, if the client machine does not have the .Net framework on it you will need to install it.</p>


问:
How to get last 3 weeks date range using moment ?
I need date range of last 3 weeks including current week date range.

Ex: today's date is : 31/08/2018

output will be :

Aug 26 - Sep 01 ,
 Aug 19 - Aug 25 ,
 Aug 12 - Aug 18

答:
```<code> let startOfWeek = moment().subtract(1, 'weeks').startOf('week').toDate().toISOString();
 let endOfWeek = moment().subtract(1, 'weeks').endOf('week').toDate().toISOString();
 console.log(startOfWeek, endOfWeek)
</code>```


问:
upload files to github directory using github api
I want to upload files from my system to a directory in github repo using the api .Is there any api endpoint which allows me to do that.</p>

答:
There's deffinitly a way to do it.
This is how I did it;

```<code>curl -i -X PUT -H ‘Authorization: token 9xxxxxxxxxxxxxxxxxxxxxxxe2’ -d
‘{“message”: “uploading a sample pdf”,
“content”:”bXkgbm……………………………..”
}’ https://api.github.com/repos/batman/toys/contents/sample.pdf
</code>```

Where the content property is a base64 encoded string of characters. I used this tool to encode my pdf file. https://www.freeformatter.com/base64-encoder.html

Notice, "batman" is the owner, "toys" is  my repo, "contents" has to be there by default, and sample.pdf would the name of the file you want to upload your file as.
In short, stick to this format: /repos/:owner/:repo/contents/:path
And you can run the identical step for any of these files:
PNG (.png)
GIF (.gif)
JPEG (.jpg)
Log files (.log)
Microsoft Word (.docx), Powerpoint (.pptx), and Excel (.xlsx) documents
Text files (.txt)
PDFs (.pdf)
ZIP (.zip, .gz)

Good luck.
Btw, I have these same details added on here: http://www.simplexanswer.com/2019/05/github-api-how-to-upload-a-file/

Body:
There's deffinitly a way to do it.
This is how I did it;

curl -i -X PUT -H ‘Authorization: token 9xxxxxxxxxxxxxxxxxxxxxxxe2’ -d
‘{“message”: “uploading a sample pdf”,
“content”:”bXkgbm……………………………..”
}’ https://api.github.com/repos/batman/toys/contents/sample.pdf

Where the content property is a base64 encoded string of characters. I used this tool to encode my pdf file. https://www.freeformatter.com/base64-encoder.html

Notice, "batman" is the owner, "toys" is  my repo, "contents" has to be there by default, and sample.pdf would the name of the file you want to upload your file as.
In short, stick to this format: /repos/:owner/:repo/contents/:path
And you can run the identical step for any of these files:
PNG (.png)
GIF (.gif)
JPEG (.jpg)
Log files (.log)
Microsoft Word (.docx), Powerpoint (.pptx), and Excel (.xlsx) documents
Text files (.txt)
PDFs (.pdf)
ZIP (.zip, .gz)

Good luck.
Btw, I have these same details added on here: http://www.simplexanswer.com/2019/05/github-api-how-to-upload-a-file/


问:
Problem with understanding usage of identify
i need to paint a graph using LakeHuron data in R, single paiting is easy just

```<code>df= data.frame(LakeHuron)
plot(df)
</code>```

but I need to use identify to sign the years where the point of water was the highest and the lowest

```<code>df=data.frame(LakeHuron)
df
plot(df)
minimum = min(df)
maximum = max(df)
</code>```

I got those minimum and maximum variables, but how can i use identify to point them on plot?

答:
Try adding this piece of code

```<code>minx <- which(df$LakeHuron == minimum)
maxx <- which(df$LakeHuron == maximum)
points(x = 1874 + minx,minimum, col = "red")
points(x = 1874 + maxx,maximum, col = "red")
</code>```

I've used the points function to plot points on your graph. You could change its visual. To that, see the page website

Body:
i need to paint a graph using LakeHuron data in R, single paiting is easy just

df= data.frame(LakeHuron)
plot(df)

but I need to use identify to sign the years where the point of water was the highest and the lowest

df=data.frame(LakeHuron)
df
plot(df)
minimum = min(df)
maximum = max(df)

I got those minimum and maximum variables, but how can i use identify to point them on plot?

Body:
Try adding this piece of code

minx <- which(df$LakeHuron == minimum)
maxx <- which(df$LakeHuron == maximum)
points(x = 1874 + minx,minimum, col = "red")
points(x = 1874 + maxx,maximum, col = "red")

I've used the points function to plot points on your graph. You could change its visual. To that, see the page website