问:
How to retrieve data from firebase database which is having nested array and objects structure?
I tried data extraction code from many places but everywhere i get how to retrieve data in a simple list. As the structure of my JSON is complex and i can't change it now, so please help me in retrieving data from firebase database. Please help as i am not able to understand Firebase code. Following is my code and JSON database:

CategoryModel.xml

```<code>package com.example.firedb;

import android.os.Parcel;
import android.os.Parcelable;

import java.util.ArrayList;

/**
 * Created by Android on 5/31/2017.
 */

public class CategoryModel {

    private ArrayList<CategoryList> categoryList;

    public CategoryModel() {
    }

    public CategoryModel(ArrayList<CategoryList> categoryList) {
        this.categoryList = categoryList;
    }

    public ArrayList<CategoryList> getCategoryList() {
        return categoryList;
    }

    public void setCategoryList(ArrayList<CategoryList> categoryList) {
        this.categoryList = categoryList;
    }

    // CategoryList

    public  static class CategoryList {

        public int Category_id;
        public String Category_name;
        public ArrayList<String>Emails;
        public ArrayList<String>Epabx;
        public ArrayList<String>Category_Fax;
        public ArrayList<Persons> persons;

        public CategoryList() {
        }
        //constructor of CategoryList

        public CategoryList(int category_id, String category_name,
                            ArrayList<String> emails, ArrayList<String> epabx, ArrayList<String> category_Fax,
                            ArrayList<Persons> persons) {
            Category_id = category_id;
            Category_name = category_name;
            Emails = emails;
            Epabx = epabx;
            Category_Fax = category_Fax;
            this.persons = persons;
        }

        // getters and setters of CategoryList

        public int getCategory_id() {
            return Category_id;
        }

        public void setCategory_id(int category_id) {
            Category_id = category_id;
        }

        public String getCategory_name() {
            return Category_name;
        }

        public void setCategory_name(String category_name) {
            Category_name = category_name;
        }

        public ArrayList<String> getEmails() {
            return Emails;
        }

        public void setEmails(ArrayList<String> emails) {
            Emails = emails;
        }

        public ArrayList<String> getEpabx() {
            return Epabx;
        }

        public void setEpabx(ArrayList<String> epabx) {
            Epabx = epabx;
        }

        public ArrayList<String> getCategory_Fax() {
            return Category_Fax;
        }

        public void setCategory_Fax(ArrayList<String> category_Fax) {
            Category_Fax = category_Fax;
        }

        public ArrayList<Persons> getPersons() {
            return persons;
        }

        public void setPersons(ArrayList<Persons> persons) {
            this.persons = persons;
        }

    }

    //Persons

    public static class Persons {

        private int Person_ID;
        private String Name;
        private String Designation;
        private ArrayList<String> Office_Phone;
        private ArrayList<String> Residence_Phone;
        private String VOIP;
        private String Address;
        private ArrayList<String>Fax;
        private String Ext;
        private ArrayList<String>Extra_info;
        private String Category_name;

        public Persons() {
        }

        // Constructor of Persons
        public Persons(int person_ID, String name, String designation, ArrayList<String> office_Phone,
                       ArrayList<String> residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext,
                       ArrayList<String>extra_info, String category_name) {
            Person_ID = person_ID;
            Name = name;
            Designation = designation;
            Office_Phone = office_Phone;
            Residence_Phone = residence_Phone;
            this.VOIP = VOIP;
            Address = address;
            Fax = fax;
            Ext = ext;
            Extra_info=extra_info;
            Category_name=category_name;
        }

        // Getter and Setters of Persons

        public int getPerson_ID() {
            return Person_ID;
        }

        public void setPerson_ID(int person_ID) {
            Person_ID = person_ID;
        }

        public String getName() {
            return Name;
        }

        public void setName(String name) {
            Name = name;
        }

        public String getDesignation() {
            return Designation;
        }

        public void setDesignation(String designation) {
            Designation = designation;
        }

        public ArrayList<String> getOffice_Phone() {
            return Office_Phone;
        }

        public void setOffice_Phone(ArrayList<String> office_Phone) {
            Office_Phone = office_Phone;
        }

        public ArrayList<String> getResidence_Phone() {
            return Residence_Phone;
        }

        public void setResidence_Phone(ArrayList<String> residence_Phone) {
            Residence_Phone = residence_Phone;
        }

        public String getVOIP() {
            return VOIP;
        }

        public void setVOIP(String VOIP) {
            this.VOIP = VOIP;
        }

        public String getAddress() {
            return Address;
        }

        public void setAddress(String address) {
            Address = address;
        }

        public ArrayList<String> getFax() {
            return Fax;
        }

        public void setFax(ArrayList<String> fax) {
            Fax = fax;
        }

        public String getExt() {
            return Ext;
        }

        public void setExt(String ext) {
            Ext = ext;
        }

        public ArrayList<String> getExtra_info() {
            return Extra_info;
        }

        public void setExtra_info(ArrayList<String> extra_info) {
            Extra_info = extra_info;
        }

        public String getCategory_name() {
            return Category_name;
        }

        public void setCategory_name(String category_name) {
            Category_name = category_name;
        }

    }

}
</code>```

CardviewActivity: Earlier i used an asset file but now i want to get data from firebase whose code is ambiguous online

```<code>package com.example.firedb;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.LoginFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import static android.R.attr.button;

public class CardViewActivity extends AppCompatActivity {
    Toolbar mActionBarToolbar;
    private RecyclerView mainRecyclerView;
    private RecyclerView.Adapter mainAdapter;
    private RecyclerView.LayoutManager mainLayoutManager;
    private static String LOG_TAG = "CardViewActivity";
    EditText inputSearchMain;
    private ArrayList<CategoryModel.CategoryList> categoryLists;
    TextView toolbar_title_main;
    ImageView back_cardviewActivity;
//    DatabaseHandler db;

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

//         db = new DatabaseHandler (CardViewActivity.this);

        mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
        toolbar_title_main=(TextView)findViewById(R.id.toolbar_title);

//        mActionBarToolbar.setTitle("Hry. Govt. Telephone Directory");
       // mActionBarToolbar.setLogo(R.drawable.logotoolbar);

//        mActionBarToolbar.setTitleMargin(5,2,2,2);
        setSupportActionBar(mActionBarToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar_title_main.setText("Hry. Govt. Telephone Directory");
        back_cardviewActivity=(ImageView)findViewById(R.id.back);
        back_cardviewActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        categoryLists=new ArrayList<CategoryModel.CategoryList>();
        categoryLists.addAll(getmcategoryset());
        mainRecyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
        mainRecyclerView.setHasFixedSize(true);
        mainLayoutManager=new LinearLayoutManager(this);
        mainRecyclerView.setLayoutManager(mainLayoutManager);
//        Log.d( "onCreate: ", "List Size: "+categoryLists.size());
        mainAdapter=new RecyclerViewAdapterMain(getmcategoryset());
        mainRecyclerView.setAdapter(mainAdapter);
        inputSearchMain = (EditText) findViewById(R.id.inputSearchMain);

        addTextListener();
    }

    public void addTextListener(){

        inputSearchMain.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {}

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            public void onTextChanged(CharSequence query, int start, int before, int count) {

                query = query.toString().toLowerCase();

                final ArrayList<CategoryModel.CategoryList> filteredList = new ArrayList<CategoryModel.CategoryList>();

                for (int i = 0; i < categoryLists.size(); i++) {

                    final String text = categoryLists.get(i).getCategory_name().toLowerCase();
                    if (text.contains(query)) {

                        filteredList.add(categoryLists.get(i));
                    }
                }

                mainRecyclerView.setLayoutManager(new LinearLayoutManager(CardViewActivity.this));
                mainAdapter = new RecyclerViewAdapterMain(filteredList);
                mainRecyclerView.setAdapter(mainAdapter);
                mainAdapter.notifyDataSetChanged();  // data set changed
            }
        });
    }

    private ArrayList<CategoryModel.CategoryList> getmcategoryset() {
//        JSONObject obj = new JSONObject(readJSONFromAsset());

        try {

            ArrayList<CategoryModel.CategoryList>categoryList = new ArrayList<CategoryModel.CategoryList>();
            JSONObject jsonObject = new JSONObject(readJSONFromAsset());

            JSONArray categoryArray = jsonObject.getJSONArray("Category");
            Log.d("getmcategoryset", "category count: "+categoryArray.length());
            for (int i = 0; i < categoryArray.length(); i++)
            {
                JSONObject job = categoryArray.getJSONObject(i);

                int categoryId = job.getInt("Category_id");
                String categoryName = job.getString("Category_name");

                //this is for email array
                ArrayList<String> emails = new ArrayList<>();
                JSONArray emailArray = job.getJSONArray("Emails");
                for (int j = 0; j< emailArray.length(); j++){
//                    JSONObject jobE = emailArray.getString(j);
                    emails.add(emailArray.getString(j));
                }

                //This i for Epabx array
                ArrayList<String> epabx = new ArrayList<>();
                JSONArray epabxArray = job.getJSONArray("Epabx");
                for (int j = 0; j < epabxArray.length(); j++){
//                    JSONObject jobE = epabxArray.getString(j);
                    epabx.add(epabxArray.getString(j));
                }

                //This i for Category_Fax array
                ArrayList<String> category_Fax = new ArrayList<>();
                JSONArray category_FaxJson = job.getJSONArray("Category_Fax");
                for (int j = 0; j < category_FaxJson.length(); j++){
//                    JSONObject jobE = category_FaxJson.getString(j);
                    category_Fax.add(category_FaxJson.getString(j));
                }

                //This i for Persons array
                ArrayList<CategoryModel.Persons> personsList = new ArrayList<>();
                JSONArray personsArray = job.getJSONArray("Persons");
                for (int j = 0; j < personsArray.length(); j++){
                    JSONObject jobIn = personsArray.getJSONObject(j);

                    int Person_ID = jobIn.getInt("Person_ID");
                    String Name = jobIn.getString("Name");
                    String Designation = jobIn.getString("Designation");

                    //this is for Office_Phone array
                    ArrayList<String>Office_Phone = new ArrayList<>();
                    JSONArray office_Phone = jobIn.getJSONArray("Office_Phone");
                    for (int k=0; k < office_Phone.length(); k++)
                    {
                        Office_Phone.add(office_Phone.getString(k));
                    }

                    //this is for Residence_Phone array
                    ArrayList<String>Residence_Phone = new ArrayList<>();
                    JSONArray residence_Phone = jobIn.getJSONArray("Residence_Phone");
                    for (int k=0; k < residence_Phone.length(); k++)
                    {
                        Residence_Phone.add(residence_Phone.getString(k));
                    }

                    String VOIP = jobIn.getString("VOIP");
                    String Address = jobIn.getString("Address");

                    //this is for Fax array
                    ArrayList<String>Fax = new ArrayList<>();
                    JSONArray fax = jobIn.getJSONArray("Fax");
                    for (int k=0; k < fax.length(); k++)
                    {
                        Fax.add(fax.getString(k));
                    }

                    String Ext = jobIn.getString("Ext");

                    //this is for Extra_info array
                    ArrayList<String>Extra_info = new ArrayList<>();
                    JSONArray extra_info = jobIn.getJSONArray("Extra_info");
                    for (int k=0; k < extra_info.length(); k++)
                    {
                        Extra_info.add(extra_info.getString(k));
                    }

                    personsList.add(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
                            VOIP, Address, Fax, Ext,Extra_info,categoryName));
//                    db.addPerson(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
//                            VOIP, Address, Fax, Ext,Extra_info));
                }

                //here your Category[] value store in categoryArrayList
                categoryList.add(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));

//                db.addCategory(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));

                Log.i("categoryList size = ", ""+categoryArray.length());
                Log.i("cat_name=",""+categoryName);
            }

            if (categoryList != null)
            {
                Log.i("categoryList size = ", ""+categoryArray.length());
            }
            return categoryList;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
//        ((RecyclerViewAdapterMain) mainAdapter).setOnItemClickListener(new RecyclerViewAdapterMain()
//                .CategoryClickListener() {
//            public void onItemClick(int position, View v) {
//                Log.i(LOG_TAG, " Clicked on Item " + position);
//            }
//        });
    }

}
</code>```

RecyclerViewAdapter:

```<code>package com.example.firedb;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;

public class RecyclerViewAdapterMain extends RecyclerView.Adapter<RecyclerViewAdapterMain.CategoryObjectHolder> {
    private static String LOG_TAG = "categoryRecyclrVwAdptr";
    private  ArrayList<CategoryModel.CategoryList> mcategoryset;
    private static CategoryClickListener categoryClickListener;

    public static class CategoryObjectHolder extends RecyclerView.ViewHolder  {
        TextView category_name;
        /*TextView category_emails;
        TextView category_epabx;
        TextView category_fax;*/

        public CategoryObjectHolder(View itemView){
            super(itemView);
            category_name=(TextView)itemView.findViewById(R.id.category_name);
            /*category_emails=(TextView)itemView.findViewById(R.id.category_emails);
            category_epabx=(TextView)itemView.findViewById(R.id.category_epabx);
            category_fax=(TextView)itemView.findViewById(R.id.category_fax);*/
            Log.i(LOG_TAG, "Adding Listener");

        }
//        @Override
//        public void onClick(View v) {
//            categoryClickListener.onItemClick(getAdapterPosition(), v);
//        }
    }
//    public void setOnItemClickListener(CategoryClickListener categoryClickListener) {
//        this.categoryClickListener = categoryClickListener;
//    }

    public RecyclerViewAdapterMain(ArrayList<CategoryModel.CategoryList> myDataset) {
        mcategoryset = myDataset;
    }

    public CategoryObjectHolder onCreateViewHolder(ViewGroup parent,int viewType){
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_row_main_activity,parent,false);
        CategoryObjectHolder categoryObjectHolder=new CategoryObjectHolder(view);
        return categoryObjectHolder;
    }

    @Override
    public void onBindViewHolder(CategoryObjectHolder holder, final int position) {
        /*final StringBuilder stringBuilder_emails = new StringBuilder();
        for (String email : mcategoryset.get(position).getEmails()) {
            if (!stringBuilder_emails.toString().isEmpty()) {
                stringBuilder_emails.append(", ");
            }
            stringBuilder_emails.append(email);
        }

        final StringBuilder stringBuilder_Epabx = new StringBuilder();
        for (String epabx : mcategoryset.get(position).getEpabx()) {
            if (!stringBuilder_Epabx.toString().isEmpty()) {
                stringBuilder_Epabx.append(", ");
            }
            stringBuilder_Epabx.append(epabx);
        }

        final StringBuilder stringBuilder_Category_Fax = new StringBuilder();
        for (String category_Fax : mcategoryset.get(position).getCategory_Fax()) {
            if (!stringBuilder_Category_Fax.toString().isEmpty()) {
                stringBuilder_Category_Fax.append(", ");
            }
            stringBuilder_Category_Fax.append(category_Fax);
        }*/

        holder.category_name.setText(mcategoryset.get(position).getCategory_name());
        /*holder.category_emails.setText(stringBuilder_emails.toString());
        holder.category_epabx.setText(stringBuilder_Epabx.toString());
        holder.category_fax.setText(stringBuilder_Category_Fax.toString());*/
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent (v.getContext(), PeopleListActivity.class);
                i.putParcelableArrayListExtra("Persons",mcategoryset.get(position).getPersons());
                i.putStringArrayListExtra("emails",mcategoryset.get(position).getEmails());
                //i.putExtras(b);
                v.getContext().startActivity(i);

            }
        });
    }
    public void addItem(CategoryModel.CategoryList dataObj, int index) {
        mcategoryset.add(index, dataObj);
        notifyItemInserted(index);
    }

    public void deleteItem(int index) {
        mcategoryset.remove(index);
        notifyItemRemoved(index);
    }

    @Override
    public int getItemCount() {
        return mcategoryset.size();
    }

    public interface CategoryClickListener {
        public void onItemClick(int position, View v);
    }
}
</code>```

答:
The only way to get data from Firebase Database it's using a ValueEventListener.
Firebase work with asynchronous calls, so you can't call the function, get the data and use it. You have to set a ValueEventListener in a specific database reference.

For your actual problem, you have to create an array, set the Firebase Reference, add the ValueEventListener and inside add each occurrence of CategoryList in the array. Finally , still inside of the ValueEventListener, you can create your CategoryModel, with the CategoryList's array as parameter, and update your UI, to see the data in CategoryModel:

```<code>CategoryModel categoryModel;
ArrayList<CategoryList> array = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference categoryRef = database.getReference("Category");
categoryRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // This method is called once with the initial value and again
        // whenever data at this location is updated.
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            CategoryList categoryList = childSnapshot.getValue(CategoryList.class);
            array.add(categoryList);
        }
        categoryModel = new CategoryModel(array);
        // Method to show the data in category model,
        // usually populating an ListView or something
        updateUI()
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.w(TAG, "Failed to read value.", error.toException());
    }
});
</code>```

For have this working, your CategoryList class has to implement all the setters of his members so "datasnapshot.getValue()" works.
Another approach can be, create a Constructor in CategoryList that recibe a DataSnapshot in this way:

```<code>public CategoryList(DataSnapshot snapshot){
    Category_id = snapshot.child("Category_id").getValue(int.class);
    Category_name = snapshot.child("Category_name").getValue(String.class);
    GenericTypeIndicator<List<String>> stringList = new GenericTypeIndicator<List<String>>() {};
    Emails = snapshot.child("Emails").getValue(stringList);
    Epabx= snapshot.child("Epabx").getValue(stringList);
    Category_Fax= snapshot.child("Category_Fax").getValue(stringList);
    GenericTypeIndicator<List<Persons>> personsList = new GenericTypeIndicator<List<Persons>>() {};
    persons = snapshot.child("Persons").getValue(personsList);
}
</code>```

If you create the constructor, you have to replace this line:

```<code>CategoryList categoryList = childSnapshot.getValue(CategoryList.class);
</code>```

with this:

```<code>CategoryList categoryList = new CategoryList(childSnapshot);
</code>```

You can see that I use GenericTypeIndicator to work with collections of data, this is a helper class provide for Firebase to work with Lists, Maps, Sets or another Collection.

Body:
I tried data extraction code from many places but everywhere i get how to retrieve data in a simple list. As the structure of my JSON is complex and i can't change it now, so please help me in retrieving data from firebase database. Please help as i am not able to understand Firebase code. Following is my code and JSON database:

CategoryModel.xml

package com.example.firedb;

import android.os.Parcel;
import android.os.Parcelable;

import java.util.ArrayList;

/**
 * Created by Android on 5/31/2017.
 */

public class CategoryModel {

    private ArrayList<CategoryList> categoryList;

    public CategoryModel() {
    }

    public CategoryModel(ArrayList<CategoryList> categoryList) {
        this.categoryList = categoryList;
    }

    public ArrayList<CategoryList> getCategoryList() {
        return categoryList;
    }

    public void setCategoryList(ArrayList<CategoryList> categoryList) {
        this.categoryList = categoryList;
    }

    // CategoryList

    public  static class CategoryList {

        public int Category_id;
        public String Category_name;
        public ArrayList<String>Emails;
        public ArrayList<String>Epabx;
        public ArrayList<String>Category_Fax;
        public ArrayList<Persons> persons;

        public CategoryList() {
        }
        //constructor of CategoryList

        public CategoryList(int category_id, String category_name,
                            ArrayList<String> emails, ArrayList<String> epabx, ArrayList<String> category_Fax,
                            ArrayList<Persons> persons) {
            Category_id = category_id;
            Category_name = category_name;
            Emails = emails;
            Epabx = epabx;
            Category_Fax = category_Fax;
            this.persons = persons;
        }

        // getters and setters of CategoryList

        public int getCategory_id() {
            return Category_id;
        }

        public void setCategory_id(int category_id) {
            Category_id = category_id;
        }

        public String getCategory_name() {
            return Category_name;
        }

        public void setCategory_name(String category_name) {
            Category_name = category_name;
        }

        public ArrayList<String> getEmails() {
            return Emails;
        }

        public void setEmails(ArrayList<String> emails) {
            Emails = emails;
        }

        public ArrayList<String> getEpabx() {
            return Epabx;
        }

        public void setEpabx(ArrayList<String> epabx) {
            Epabx = epabx;
        }

        public ArrayList<String> getCategory_Fax() {
            return Category_Fax;
        }

        public void setCategory_Fax(ArrayList<String> category_Fax) {
            Category_Fax = category_Fax;
        }

        public ArrayList<Persons> getPersons() {
            return persons;
        }

        public void setPersons(ArrayList<Persons> persons) {
            this.persons = persons;
        }

    }

    //Persons

    public static class Persons {

        private int Person_ID;
        private String Name;
        private String Designation;
        private ArrayList<String> Office_Phone;
        private ArrayList<String> Residence_Phone;
        private String VOIP;
        private String Address;
        private ArrayList<String>Fax;
        private String Ext;
        private ArrayList<String>Extra_info;
        private String Category_name;

        public Persons() {
        }

        // Constructor of Persons
        public Persons(int person_ID, String name, String designation, ArrayList<String> office_Phone,
                       ArrayList<String> residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext,
                       ArrayList<String>extra_info, String category_name) {
            Person_ID = person_ID;
            Name = name;
            Designation = designation;
            Office_Phone = office_Phone;
            Residence_Phone = residence_Phone;
            this.VOIP = VOIP;
            Address = address;
            Fax = fax;
            Ext = ext;
            Extra_info=extra_info;
            Category_name=category_name;
        }

        // Getter and Setters of Persons

        public int getPerson_ID() {
            return Person_ID;
        }

        public void setPerson_ID(int person_ID) {
            Person_ID = person_ID;
        }

        public String getName() {
            return Name;
        }

        public void setName(String name) {
            Name = name;
        }

        public String getDesignation() {
            return Designation;
        }

        public void setDesignation(String designation) {
            Designation = designation;
        }

        public ArrayList<String> getOffice_Phone() {
            return Office_Phone;
        }

        public void setOffice_Phone(ArrayList<String> office_Phone) {
            Office_Phone = office_Phone;
        }

        public ArrayList<String> getResidence_Phone() {
            return Residence_Phone;
        }

        public void setResidence_Phone(ArrayList<String> residence_Phone) {
            Residence_Phone = residence_Phone;
        }

        public String getVOIP() {
            return VOIP;
        }

        public void setVOIP(String VOIP) {
            this.VOIP = VOIP;
        }

        public String getAddress() {
            return Address;
        }

        public void setAddress(String address) {
            Address = address;
        }

        public ArrayList<String> getFax() {
            return Fax;
        }

        public void setFax(ArrayList<String> fax) {
            Fax = fax;
        }

        public String getExt() {
            return Ext;
        }

        public void setExt(String ext) {
            Ext = ext;
        }

        public ArrayList<String> getExtra_info() {
            return Extra_info;
        }

        public void setExtra_info(ArrayList<String> extra_info) {
            Extra_info = extra_info;
        }

        public String getCategory_name() {
            return Category_name;
        }

        public void setCategory_name(String category_name) {
            Category_name = category_name;
        }

    }

}

CardviewActivity: Earlier i used an asset file but now i want to get data from firebase whose code is ambiguous online

package com.example.firedb;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.LoginFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import static android.R.attr.button;

public class CardViewActivity extends AppCompatActivity {
    Toolbar mActionBarToolbar;
    private RecyclerView mainRecyclerView;
    private RecyclerView.Adapter mainAdapter;
    private RecyclerView.LayoutManager mainLayoutManager;
    private static String LOG_TAG = "CardViewActivity";
    EditText inputSearchMain;
    private ArrayList<CategoryModel.CategoryList> categoryLists;
    TextView toolbar_title_main;
    ImageView back_cardviewActivity;
//    DatabaseHandler db;

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

//         db = new DatabaseHandler (CardViewActivity.this);

        mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
        toolbar_title_main=(TextView)findViewById(R.id.toolbar_title);

//        mActionBarToolbar.setTitle("Hry. Govt. Telephone Directory");
       // mActionBarToolbar.setLogo(R.drawable.logotoolbar);

//        mActionBarToolbar.setTitleMargin(5,2,2,2);
        setSupportActionBar(mActionBarToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar_title_main.setText("Hry. Govt. Telephone Directory");
        back_cardviewActivity=(ImageView)findViewById(R.id.back);
        back_cardviewActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        categoryLists=new ArrayList<CategoryModel.CategoryList>();
        categoryLists.addAll(getmcategoryset());
        mainRecyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
        mainRecyclerView.setHasFixedSize(true);
        mainLayoutManager=new LinearLayoutManager(this);
        mainRecyclerView.setLayoutManager(mainLayoutManager);
//        Log.d( "onCreate: ", "List Size: "+categoryLists.size());
        mainAdapter=new RecyclerViewAdapterMain(getmcategoryset());
        mainRecyclerView.setAdapter(mainAdapter);
        inputSearchMain = (EditText) findViewById(R.id.inputSearchMain);

        addTextListener();
    }

    public void addTextListener(){

        inputSearchMain.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {}

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            public void onTextChanged(CharSequence query, int start, int before, int count) {

                query = query.toString().toLowerCase();

                final ArrayList<CategoryModel.CategoryList> filteredList = new ArrayList<CategoryModel.CategoryList>();

                for (int i = 0; i < categoryLists.size(); i++) {

                    final String text = categoryLists.get(i).getCategory_name().toLowerCase();
                    if (text.contains(query)) {

                        filteredList.add(categoryLists.get(i));
                    }
                }

                mainRecyclerView.setLayoutManager(new LinearLayoutManager(CardViewActivity.this));
                mainAdapter = new RecyclerViewAdapterMain(filteredList);
                mainRecyclerView.setAdapter(mainAdapter);
                mainAdapter.notifyDataSetChanged();  // data set changed
            }
        });
    }

    private ArrayList<CategoryModel.CategoryList> getmcategoryset() {
//        JSONObject obj = new JSONObject(readJSONFromAsset());

        try {

            ArrayList<CategoryModel.CategoryList>categoryList = new ArrayList<CategoryModel.CategoryList>();
            JSONObject jsonObject = new JSONObject(readJSONFromAsset());

            JSONArray categoryArray = jsonObject.getJSONArray("Category");
            Log.d("getmcategoryset", "category count: "+categoryArray.length());
            for (int i = 0; i < categoryArray.length(); i++)
            {
                JSONObject job = categoryArray.getJSONObject(i);

                int categoryId = job.getInt("Category_id");
                String categoryName = job.getString("Category_name");

                //this is for email array
                ArrayList<String> emails = new ArrayList<>();
                JSONArray emailArray = job.getJSONArray("Emails");
                for (int j = 0; j< emailArray.length(); j++){
//                    JSONObject jobE = emailArray.getString(j);
                    emails.add(emailArray.getString(j));
                }

                //This i for Epabx array
                ArrayList<String> epabx = new ArrayList<>();
                JSONArray epabxArray = job.getJSONArray("Epabx");
                for (int j = 0; j < epabxArray.length(); j++){
//                    JSONObject jobE = epabxArray.getString(j);
                    epabx.add(epabxArray.getString(j));
                }

                //This i for Category_Fax array
                ArrayList<String> category_Fax = new ArrayList<>();
                JSONArray category_FaxJson = job.getJSONArray("Category_Fax");
                for (int j = 0; j < category_FaxJson.length(); j++){
//                    JSONObject jobE = category_FaxJson.getString(j);
                    category_Fax.add(category_FaxJson.getString(j));
                }

                //This i for Persons array
                ArrayList<CategoryModel.Persons> personsList = new ArrayList<>();
                JSONArray personsArray = job.getJSONArray("Persons");
                for (int j = 0; j < personsArray.length(); j++){
                    JSONObject jobIn = personsArray.getJSONObject(j);

                    int Person_ID = jobIn.getInt("Person_ID");
                    String Name = jobIn.getString("Name");
                    String Designation = jobIn.getString("Designation");

                    //this is for Office_Phone array
                    ArrayList<String>Office_Phone = new ArrayList<>();
                    JSONArray office_Phone = jobIn.getJSONArray("Office_Phone");
                    for (int k=0; k < office_Phone.length(); k++)
                    {
                        Office_Phone.add(office_Phone.getString(k));
                    }

                    //this is for Residence_Phone array
                    ArrayList<String>Residence_Phone = new ArrayList<>();
                    JSONArray residence_Phone = jobIn.getJSONArray("Residence_Phone");
                    for (int k=0; k < residence_Phone.length(); k++)
                    {
                        Residence_Phone.add(residence_Phone.getString(k));
                    }

                    String VOIP = jobIn.getString("VOIP");
                    String Address = jobIn.getString("Address");

                    //this is for Fax array
                    ArrayList<String>Fax = new ArrayList<>();
                    JSONArray fax = jobIn.getJSONArray("Fax");
                    for (int k=0; k < fax.length(); k++)
                    {
                        Fax.add(fax.getString(k));
                    }

                    String Ext = jobIn.getString("Ext");

                    //this is for Extra_info array
                    ArrayList<String>Extra_info = new ArrayList<>();
                    JSONArray extra_info = jobIn.getJSONArray("Extra_info");
                    for (int k=0; k < extra_info.length(); k++)
                    {
                        Extra_info.add(extra_info.getString(k));
                    }

                    personsList.add(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
                            VOIP, Address, Fax, Ext,Extra_info,categoryName));
//                    db.addPerson(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
//                            VOIP, Address, Fax, Ext,Extra_info));
                }

                //here your Category[] value store in categoryArrayList
                categoryList.add(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));

//                db.addCategory(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));

                Log.i("categoryList size = ", ""+categoryArray.length());
                Log.i("cat_name=",""+categoryName);
            }

            if (categoryList != null)
            {
                Log.i("categoryList size = ", ""+categoryArray.length());
            }
            return categoryList;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
//        ((RecyclerViewAdapterMain) mainAdapter).setOnItemClickListener(new RecyclerViewAdapterMain()
//                .CategoryClickListener() {
//            public void onItemClick(int position, View v) {
//                Log.i(LOG_TAG, " Clicked on Item " + position);
//            }
//        });
    }

}

RecyclerViewAdapter:

package com.example.firedb;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;

public class RecyclerViewAdapterMain extends RecyclerView.Adapter<RecyclerViewAdapterMain.CategoryObjectHolder> {
    private static String LOG_TAG = "categoryRecyclrVwAdptr";
    private  ArrayList<CategoryModel.CategoryList> mcategoryset;
    private static CategoryClickListener categoryClickListener;

    public static class CategoryObjectHolder extends RecyclerView.ViewHolder  {
        TextView category_name;
        /*TextView category_emails;
        TextView category_epabx;
        TextView category_fax;*/

        public CategoryObjectHolder(View itemView){
            super(itemView);
            category_name=(TextView)itemView.findViewById(R.id.category_name);
            /*category_emails=(TextView)itemView.findViewById(R.id.category_emails);
            category_epabx=(TextView)itemView.findViewById(R.id.category_epabx);
            category_fax=(TextView)itemView.findViewById(R.id.category_fax);*/
            Log.i(LOG_TAG, "Adding Listener");

        }
//        @Override
//        public void onClick(View v) {
//            categoryClickListener.onItemClick(getAdapterPosition(), v);
//        }
    }
//    public void setOnItemClickListener(CategoryClickListener categoryClickListener) {
//        this.categoryClickListener = categoryClickListener;
//    }

    public RecyclerViewAdapterMain(ArrayList<CategoryModel.CategoryList> myDataset) {
        mcategoryset = myDataset;
    }

    public CategoryObjectHolder onCreateViewHolder(ViewGroup parent,int viewType){
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_row_main_activity,parent,false);
        CategoryObjectHolder categoryObjectHolder=new CategoryObjectHolder(view);
        return categoryObjectHolder;
    }

    @Override
    public void onBindViewHolder(CategoryObjectHolder holder, final int position) {
        /*final StringBuilder stringBuilder_emails = new StringBuilder();
        for (String email : mcategoryset.get(position).getEmails()) {
            if (!stringBuilder_emails.toString().isEmpty()) {
                stringBuilder_emails.append(", ");
            }
            stringBuilder_emails.append(email);
        }

        final StringBuilder stringBuilder_Epabx = new StringBuilder();
        for (String epabx : mcategoryset.get(position).getEpabx()) {
            if (!stringBuilder_Epabx.toString().isEmpty()) {
                stringBuilder_Epabx.append(", ");
            }
            stringBuilder_Epabx.append(epabx);
        }

        final StringBuilder stringBuilder_Category_Fax = new StringBuilder();
        for (String category_Fax : mcategoryset.get(position).getCategory_Fax()) {
            if (!stringBuilder_Category_Fax.toString().isEmpty()) {
                stringBuilder_Category_Fax.append(", ");
            }
            stringBuilder_Category_Fax.append(category_Fax);
        }*/

        holder.category_name.setText(mcategoryset.get(position).getCategory_name());
        /*holder.category_emails.setText(stringBuilder_emails.toString());
        holder.category_epabx.setText(stringBuilder_Epabx.toString());
        holder.category_fax.setText(stringBuilder_Category_Fax.toString());*/
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent (v.getContext(), PeopleListActivity.class);
                i.putParcelableArrayListExtra("Persons",mcategoryset.get(position).getPersons());
                i.putStringArrayListExtra("emails",mcategoryset.get(position).getEmails());
                //i.putExtras(b);
                v.getContext().startActivity(i);

            }
        });
    }
    public void addItem(CategoryModel.CategoryList dataObj, int index) {
        mcategoryset.add(index, dataObj);
        notifyItemInserted(index);
    }

    public void deleteItem(int index) {
        mcategoryset.remove(index);
        notifyItemRemoved(index);
    }

    @Override
    public int getItemCount() {
        return mcategoryset.size();
    }

    public interface CategoryClickListener {
        public void onItemClick(int position, View v);
    }
}

Body:
The only way to get data from Firebase Database it's using a ValueEventListener.
Firebase work with asynchronous calls, so you can't call the function, get the data and use it. You have to set a ValueEventListener in a specific database reference.

For your actual problem, you have to create an array, set the Firebase Reference, add the ValueEventListener and inside add each occurrence of CategoryList in the array. Finally , still inside of the ValueEventListener, you can create your CategoryModel, with the CategoryList's array as parameter, and update your UI, to see the data in CategoryModel:

CategoryModel categoryModel;
ArrayList<CategoryList> array = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference categoryRef = database.getReference("Category");
categoryRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // This method is called once with the initial value and again
        // whenever data at this location is updated.
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            CategoryList categoryList = childSnapshot.getValue(CategoryList.class);
            array.add(categoryList);
        }
        categoryModel = new CategoryModel(array);
        // Method to show the data in category model,
        // usually populating an ListView or something
        updateUI()
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.w(TAG, "Failed to read value.", error.toException());
    }
});

For have this working, your CategoryList class has to implement all the setters of his members so "datasnapshot.getValue()" works.
Another approach can be, create a Constructor in CategoryList that recibe a DataSnapshot in this way:

public CategoryList(DataSnapshot snapshot){
    Category_id = snapshot.child("Category_id").getValue(int.class);
    Category_name = snapshot.child("Category_name").getValue(String.class);
    GenericTypeIndicator<List<String>> stringList = new GenericTypeIndicator<List<String>>() {};
    Emails = snapshot.child("Emails").getValue(stringList);
    Epabx= snapshot.child("Epabx").getValue(stringList);
    Category_Fax= snapshot.child("Category_Fax").getValue(stringList);
    GenericTypeIndicator<List<Persons>> personsList = new GenericTypeIndicator<List<Persons>>() {};
    persons = snapshot.child("Persons").getValue(personsList);
}

If you create the constructor, you have to replace this line:

CategoryList categoryList = childSnapshot.getValue(CategoryList.class);

with this:

CategoryList categoryList = new CategoryList(childSnapshot);

You can see that I use GenericTypeIndicator to work with collections of data, this is a helper class provide for Firebase to work with Lists, Maps, Sets or another Collection.


来源: stackexchange

问:
IntelliJ does not show project folders
I have an issue with IntelliJ. It doesn't show any folders in my project view on the left.
My setting is "View As: Project"
How can I manage it so that the folders and packages are shown again?
I don't have any clue because I didn't change any options!

I'm using IntelliJ 10.0.3.
I am working on a Maven Lift Project.

答:
I had this issue as well.
It is something do with <strong>.idea</strong> just delete it and restart IntelliJ </p>

ContentLicense: CC BY-SA 3.0

Title: IntelliJ does not show project folders

Body:
I had this issue as well.
It is something do with .idea just delete it and restart IntelliJ


问:
Make a tab-delimited file containing information from a file and part of a filename
I have many files containing:

```<code>>c_000000000288
abcdefg

>c_000000000270
abcdefg

>c_000000000062
abcdefg

*Note: continues for hundreds of lines
</code>```

The filenames are something like:

```<code>M07.compare.M010.info500.info2.1.txt
M07.compare.M010.info500.info2.2.txt
M07.compare.M010.info500.info2.3.txt
M07.compare.M010.info500.info2.word.txt
</code>```

Note: I would like the code to work for different number ranges (e.g. 1-10 or 1-3) and include "word" at the same time.

I want the result to be a tab-delimited file containing something like:

```<code>c_000000000288   1
c_000000000270   1
c_000000000062   1
c_000000000258   2
c_000000000191   3
c_000000000188   3
c_000000003713   3
c_000000000179   3
c_000000000162   word
c_000000000097   word
</code>```

I have tried to search many forums and have not been able to find a solution. So far, I have only been able to extract "name" into a tab-delimited file, but I have not figured out how to efficiently add the filename information.

Thank you for your help!

答:
All you need is:</p>

```<code>shopt -s extglob
awk -v OFS='\t' '
FNR==1 { n=split(FILENAME,f,/\./); ext=f[n-1] }
sub(/^>/,""){ print $0, ext }
' M07.compare.M010.info500.info2.{{1..10},word}.txt
</code>```

Body:
I have many files containing:

>c_000000000288
abcdefg

>c_000000000270
abcdefg

>c_000000000062
abcdefg

*Note: continues for hundreds of lines

The filenames are something like:

M07.compare.M010.info500.info2.1.txt
M07.compare.M010.info500.info2.2.txt
M07.compare.M010.info500.info2.3.txt
M07.compare.M010.info500.info2.word.txt

Note: I would like the code to work for different number ranges (e.g. 1-10 or 1-3) and include "word" at the same time.

I want the result to be a tab-delimited file containing something like:

c_000000000288   1
c_000000000270   1
c_000000000062   1
c_000000000258   2
c_000000000191   3
c_000000000188   3
c_000000003713   3
c_000000000179   3
c_000000000162   word
c_000000000097   word

I have tried to search many forums and have not been able to find a solution. So far, I have only been able to extract "name" into a tab-delimited file, but I have not figured out how to efficiently add the filename information.

Thank you for your help!

Body:
All you need is:

shopt -s extglob
awk -v OFS='\t' '
FNR==1 { n=split(FILENAME,f,/\./); ext=f[n-1] }
sub(/^>/,""){ print $0, ext }
' M07.compare.M010.info500.info2.{{1..10},word}.txt


问:
jQuery get rid of a:hover underline?
I'm just getting started with jQuery, having a little trouble.

Got a table of thumbnails, and I want each cell to be highlighted when I hover over the picture inside it. Got that part working. But I also want the picture inside the cell not to have an underline - this is inherited from the stylesheet a:hover{text-decoration:underline} . This is where I'm stuck, I don't think I'm setting the right thing.

I need to use inline styles, so my jQuery looks like:

```<code>$('[name*=thumb]').hover(
  function () {
    //as we hover over an item, change it's background, attempt to vaquish pesky underline
    $('#' + $(this).attr('id').replace('thumb', 'thumbcontainer')).css('background-color', '#cccccc');
    $('#' + this).css('text-decoration', 'none');  //doesn't work : (
  },
  function () {
    //fix bgs of items we're not hovering on
    $('#' + $(this).attr('id').replace('thumb', 'thumbcontainer')).css('background-color', '#ffffff');
  }
);
</code>```

My HTML looks like this :

```<code><td name="thumbcontainer8" id="thumbcontainer8"><a href="#" name="thumb8" id="thumb8"><img src="..." /></a></td>
<td name="thumbcontainer9" id="thumbcontainer9"><a href="#" name="thumb9" id="thumb9"><img src="..." /></a></td>
</code>```

答:
Wouldn't this rule in your stylesheet do the trick?</p>

```<code>a:hover img{text-decoration:none}
</code>```

ContentLicense: CC BY-SA 2.5

Title: jQuery get rid of a:hover underline?

Body:
I'm just getting started with jQuery, having a little trouble.

Got a table of thumbnails, and I want each cell to be highlighted when I hover over the picture inside it. Got that part working. But I also want the picture inside the cell not to have an underline - this is inherited from the stylesheet a:hover{text-decoration:underline} . This is where I'm stuck, I don't think I'm setting the right thing.

I need to use inline styles, so my jQuery looks like:

$('[name*=thumb]').hover(
  function () {
    //as we hover over an item, change it's background, attempt to vaquish pesky underline
    $('#' + $(this).attr('id').replace('thumb', 'thumbcontainer')).css('background-color', '#cccccc');
    $('#' + this).css('text-decoration', 'none');  //doesn't work : (
  },
  function () {
    //fix bgs of items we're not hovering on
    $('#' + $(this).attr('id').replace('thumb', 'thumbcontainer')).css('background-color', '#ffffff');
  }
);

My HTML looks like this :

Body:
Wouldn't this rule in your stylesheet do the trick?

a:hover img{text-decoration:none}


问:
Reverse Expanding Direction of after/before psuedo element
What I am doing: Have images going down a column odd divs with float left and right divs float right.
It all works fine, but I am having a bit of trouble with the sizing of the psuedo classes and such.
Issue in a nutshell: I have the psuedo element :after present information on hover of one of the images and with width:auto; it is fine and expands from the left as it should and text length no issue. Though when trying to do the same but for the opposite side, the text length will often overlap the image itself as it expands from the left.

Question: How do I change the direction of expansion of the psuedo element :after or :before (doesn't matter which) to expand auto from right to left rather than the default left to right with the width being auto.

Example of the issue here https://jsfiddle.net/fd0p537r/

```<code>.outer{display:inline-block;width:240px;background-color:Blue;}
.outer div{background-color:Red;margin:10px 50px;width:3em;height:3em;}
.outer div:after{visibility:hidden;position:absolute;width:auto;line-height:30px;background-color:cadetblue;}
.outer div:hover:after{visibility:visible;}
.outer div:nth-child(odd){float:left;}
.outer div:nth-child(even){float:right;}
.outer div:nth-child(odd):after{margin-left:3em;}
.outer div:nth-child(even):after{margin-left:-3em;}
.outer div:before{visibility:hidden;position:absolute;width:auto;line-height:30px;background-color:cadetblue;}
.outer div:hover:before{visibility:visible;}
.one:after{content:"oneoneoneone";}
.two:after{content:"Two";}
.three:after{content:"Three";}
.four:after{content:"FourFourFour";}

<div class="outer">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
</div>
</code>```

答:
Using :before, the ch measurement, a monospace font and margin-left

Making these changes at the end of your fiddle's CSS

```<code>/* use a monospace font */
.one, .two, .three, .four { font-family: Consolas, monospace; }

.one:after{content:"oneoneoneone";}

/* place the content before and */
/* make use of the monospace */
.two:before{content:"Two"; margin-left: -3ch }

.three:after{content:"Three";}

/* place the content before and */
/* make use of the monospace */
.four:before{content:"FourFourFour"; margin-left: -12ch }
</code>```

works, but is perhaps not as dynamic a solution as you'd like.

Body:
What I am doing: Have images going down a column odd divs with float left and right divs float right.
It all works fine, but I am having a bit of trouble with the sizing of the psuedo classes and such.
Issue in a nutshell: I have the psuedo element :after present information on hover of one of the images and with width:auto; it is fine and expands from the left as it should and text length no issue. Though when trying to do the same but for the opposite side, the text length will often overlap the image itself as it expands from the left.

Question: How do I change the direction of expansion of the psuedo element :after or :before (doesn't matter which) to expand auto from right to left rather than the default left to right with the width being auto.

Example of the issue here https://jsfiddle.net/fd0p537r/

.outer{display:inline-block;width:240px;background-color:Blue;}
.outer div{background-color:Red;margin:10px 50px;width:3em;height:3em;}
.outer div:after{visibility:hidden;position:absolute;width:auto;line-height:30px;background-color:cadetblue;}
.outer div:hover:after{visibility:visible;}
.outer div:nth-child(odd){float:left;}
.outer div:nth-child(even){float:right;}
.outer div:nth-child(odd):after{margin-left:3em;}
.outer div:nth-child(even):after{margin-left:-3em;}
.outer div:before{visibility:hidden;position:absolute;width:auto;line-height:30px;background-color:cadetblue;}
.outer div:hover:before{visibility:visible;}
.one:after{content:"oneoneoneone";}
.two:after{content:"Two";}
.three:after{content:"Three";}
.four:after{content:"FourFourFour";}

Body:
Using :before, the ch measurement, a monospace font and margin-left

Making these changes at the end of your fiddle's CSS

/* use a monospace font */
.one, .two, .three, .four { font-family: Consolas, monospace; }

.one:after{content:"oneoneoneone";}

/* place the content before and */
/* make use of the monospace */
.two:before{content:"Two"; margin-left: -3ch }

.three:after{content:"Three";}

/* place the content before and */
/* make use of the monospace */
.four:before{content:"FourFourFour"; margin-left: -12ch }

works, but is perhaps not as dynamic a solution as you'd like.


问:
Accessing a generic dictionary via casting at runtime
Our program has a dictionary of type:

```<code>Dictionary<TKey, TCache>();
</code>```

where TKey and TCache are whatever generic types the encompassing method is given, and TCache is a CacheBase.

In another method I need to reference this object (which is stored in another dictionary where it's stored as an object) and remove a key/value pair from it. At runtime I have the TKey object boxed as an 'object' class.

How would I go about this? I can't cast to Dictionary because this method is not generic and won't know at compile time what type of cache/key it is. These are passed as parameters.

Is there a way to use reflection to cast the dictionary from Dictionary to effectively

```<code>Dictionary<CacheBase<key.GetType()>, key.GetType()>
</code>```

I know this can easily fixed by not using the methods generics and instead making the Dictionary a Dictionary and making CaseBase extend an empty CacheBase, but my supervisor insisted I do it this way

答:
Managed to fix it on my own, but for future people,

Essentially, I had to flip the perspective. I can't cast an existing dictionary to another equivalent type via reflection, however the goal was to do so so I could modify the dictionary with Types at runtime.

So instead, I made a generic method that would communicate with the dictionary in the way it wanted (if it expects a TKey, I made my method take a TKey so it would work properly).

e.g.

```<code>public void RemoveFromCache<TCache, TKey>( Type type, TKeykey ) where TCache : CacheBase<TKey> {
  ((Dictionary<TKey, TCache>)m_caches[type]).Remove( key );
}
</code>```

After that, I simply used reflection to call my generic method at runtime with the types passed in as the appropriate generics

e.g.

```<code>var keyType = key.GetType();
var removeFromCache = GetType().GetMethod( nameof( RemoveFromCache ) ).MakeGenericMethod( type, keyType );
removeFromCache.Invoke( this, new object[] { type, key } );
</code>```

And that let me communicate with a Dictionary that was boxed into an object at runtime with only types available.

Body:
Our program has a dictionary of type:

Dictionary<TKey, TCache>();

where TKey and TCache are whatever generic types the encompassing method is given, and TCache is a CacheBase.

In another method I need to reference this object (which is stored in another dictionary where it's stored as an object) and remove a key/value pair from it. At runtime I have the TKey object boxed as an 'object' class.

How would I go about this? I can't cast to Dictionary because this method is not generic and won't know at compile time what type of cache/key it is. These are passed as parameters.

Is there a way to use reflection to cast the dictionary from Dictionary to effectively

Dictionary<CacheBase<key.GetType()>, key.GetType()>

I know this can easily fixed by not using the methods generics and instead making the Dictionary a Dictionary and making CaseBase extend an empty CacheBase, but my supervisor insisted I do it this way

Body:
Managed to fix it on my own, but for future people,

Essentially, I had to flip the perspective. I can't cast an existing dictionary to another equivalent type via reflection, however the goal was to do so so I could modify the dictionary with Types at runtime.

So instead, I made a generic method that would communicate with the dictionary in the way it wanted (if it expects a TKey, I made my method take a TKey so it would work properly).

e.g.

public void RemoveFromCache<TCache, TKey>( Type type, TKeykey ) where TCache : CacheBase<TKey> {
  ((Dictionary<TKey, TCache>)m_caches[type]).Remove( key );
}

After that, I simply used reflection to call my generic method at runtime with the types passed in as the appropriate generics

e.g.

var keyType = key.GetType();
var removeFromCache = GetType().GetMethod( nameof( RemoveFromCache ) ).MakeGenericMethod( type, keyType );
removeFromCache.Invoke( this, new object[] { type, key } );

And that let me communicate with a Dictionary that was boxed into an object at runtime with only types available.


问:
Regex to replace a part of string
I have a string like

```<code> "target:40,trg: tra:20,this:30"
</code>```

I want to replace trg:
or in other words, anything before colon followed by one empty space should be replaced.

I don't have any easy way to do it.
Any help will be great.

答:
I don't know what is your desired output, but you can try:

```<code>import re
s = "target:40,trg: tra:20,this:30"
print re.sub(r'[a-zA-Z0-9]+:\s', ' ', s)
</code>```

output:

```<code>target:40, tra:20,this:30
</code>```

If you want to just delete it without adding a space, use '' instead of ' '

Title: Regex to replace a part of string

Body:
I have a string like

 "target:40,trg: tra:20,this:30"

I want to replace trg:
or in other words, anything before colon followed by one empty space should be replaced.

I don't have any easy way to do it.
Any help will be great.

Body:
I don't know what is your desired output, but you can try:

import re
s = "target:40,trg: tra:20,this:30"
print re.sub(r'[a-zA-Z0-9]+:\s', ' ', s)

output:

target:40, tra:20,this:30

If you want to just delete it without adding a space, use '' instead of ' '


问:
ERR_INCOMPLETE_CHUNKED_ENCODING on angularjs - rest service returns an infinite json file using Advanced REST Client but error in postman
I have a very strange problem. In angular (app built with ionic v1) I call some REST call built in java, but something goes wrong and chrome advise me with this error:

The code interesting is this, a REST service in angular js:

bankaccountsbyuser: function(_getbauser, _error){
            var currentToken = _GetToken();

            if(currentToken!=null){
                var Headers = {
                    token: currentToken.tokenUser,
                };
            }

            _timerTokenControl(currentToken, _error);

            if (setupTime == null) {
                console.log("token scaduto");
                //modificare
                //$window.location.href="login.html";
            }

            if (currentToken !== null) {
            $http({
                        method : 'GET',
                        headers: Headers,
                        url : REST_URL+'bankaccount'
                    }).then(function successCallback(response) {
                        console.log(response)
                        _getbauser(response)
                    }, function errorCallback(response) {
                        console.log(response.statusText);
                    });
               }  else {
                   var alertPopup = $ionicPopup.alert({
                         title: 'Accesso negato!',
                         template: 'Devi essere un utente registrato, non sei loggato!'
                     });
                    console.log("NON SEI LOGGATO!!!");
            }
        },```
</div>
</div>
</p>

<p>debug:
<img src="https://i.stack.imgur.com/u7LYM.png" alt="debug"></p>

<p>How you can see, the get REST service returns an error, thus, let's see this REST service built in java:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>package it.jack.fdd.services;

import java.util.List;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import it.jack.fdd.dao.FactoryDao;
import it.jack.fdd.dao.impl.BankAccountDaoImpl;
import it.jack.fdd.dao.interfaces.BankAccountDao;
import it.jack.fdd.domain.BankAccount;
import it.jack.fdd.domain.User;
import it.jack.fdd.dto.TokenUserDto;
import it.jack.fdd.dto.UserDto;
import it.jack.fdd.util.ConverterDTO;

@Path("/bankaccount")
public class BankAccountServices {

 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public List<BankAccount> getBankAccountOfUser() {

  BankAccountDao baDao = new BankAccountDaoImpl();
  List<BankAccount> balist = baDao.getBAByUserId(1);
  return balist;

 }</code>```

I tryed to pass the number "1" in the method, just to simplify. The method is implemented below:

package it.jack.fdd.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import it.jack.fdd.dao.interfaces.BankAccountDao;
import it.jack.fdd.domain.BankAccount;
import it.jack.fdd.domain.Staff;
import it.jack.fdd.domain.User;
import it.jack.fdd.util.HibernateUtilLezione;

public class BankAccountDaoImpl extends BaseDaoImpl<BankAccount> implements BankAccountDao{

 public List<BankAccount> getBAByUserId(int id) {

  try{

   Session session = HibernateUtilLezione.openSession();
   Transaction tx = session.beginTransaction();

   @SuppressWarnings("unchecked")
   List<BankAccount> accounts = session.createQuery("from BankAccount b "
     + "where b.user= "+id).list();

   tx.commit();
   session.close();

   return accounts;
  }
  catch(HibernateException e){
   e.printStackTrace();
   return null;
  }
 }

}```

As you can see, the method ask for an id, and I put id 1 just to check, because in the database there is a field with that id. Trying in java, it returns me a list

[it.jack.fdd.domain.BankAccount@4f8d86e4]

And I checked also that the list has dimension 1 (thus, only one record, like in the database, only 1 record with that iduser)

Thus, trying to open this REST call using postman, the result is this:

The strange thing is that postman show me the same result to another REST call, that it worked before. But for this last REST call is not a problem, because strangely it works on my application, it doesn't work only in postman.
Thus, trying with Advanced REST Client I have a strange different result:

A strange, very big list that repeat every time the same field!! It is like a loop!
What happens? How I can solve?

答:
Solved. The problem was in java's domain classes: when a domain class has a one-to-many relationship it's mandatory to put the tag @JsonIgnore to avoid these recurrent records in json file

Entity class:

package it.jack.fdd.domain;
// Generated 30-nov-2016 0.17.09 by Hibernate Tools 4.3.1.Final

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * BankAccount generated by hbm2java
 */
@Entity
@Table(name = "bank_account", catalog = "fdd_dbproducts")
public class BankAccount implements java.io.Serializable {

 private Integer idbankAccount;
 private User user;
 private String iban;
 private String pin;
 private String society;
 private Date expiration;

 public BankAccount() {
 }

 public BankAccount(User user, String iban, String pin, String society) {
  this.user = user;
  this.iban = iban;
  this.pin = pin;
  this.society = society;
 }

 public BankAccount(User user, String iban, String pin, String society, Date expiration) {
  this.user = user;
  this.iban = iban;
  this.pin = pin;
  this.society = society;
  this.expiration = expiration;
 }

 @Id
 @GeneratedValue(strategy = IDENTITY)

 @Column(name = "idbank_account", unique = true, nullable = false)
 public Integer getIdbankAccount() {
  return this.idbankAccount;
 }

 public void setIdbankAccount(Integer idbankAccount) {
  this.idbankAccount = idbankAccount;
 }

 @ManyToOne(fetch = FetchType.EAGER)
 @JoinColumn(name = "fkuser_baccount", nullable = false)
 public User getUser() {
  return this.user;
 }

 public void setUser(User user) {
  this.user = user;
 }

 @Column(name = "iban", nullable = false, length = 45)
 public String getIban() {
  return this.iban;
 }

 public void setIban(String iban) {
  this.iban = iban;
 }

 @Column(name = "pin", nullable = false, length = 45)
 public String getPin() {
  return this.pin;
 }

 public void setPin(String pin) {
  this.pin = pin;
 }

 @Column(name = "society", nullable = false, length = 45)
 public String getSociety() {
  return this.society;
 }

 public void setSociety(String society) {
  this.society = society;
 }

 @Temporal(TemporalType.DATE)
 @Column(name = "expiration", length = 10)
 public Date getExpiration() {
  return this.expiration;
 }

 public void setExpiration(Date expiration) {
  this.expiration = expiration;
 }

}```

Body:
I have a very strange problem. In angular (app built with ionic v1) I call some REST call built in java, but something goes wrong and chrome advise me with this error:

The code interesting is this, a REST service in angular js:

bankaccountsbyuser: function(_getbauser, _error){
            var currentToken = _GetToken();

            if(currentToken!=null){
                var Headers = {
                    token: currentToken.tokenUser,
                };
            }

            _timerTokenControl(currentToken, _error);

            if (setupTime == null) {
                console.log("token scaduto");
                //modificare
                //$window.location.href="login.html";
            }

            if (currentToken !== null) {
            $http({
                        method : 'GET',
                        headers: Headers,
                        url : REST_URL+'bankaccount'
                    }).then(function successCallback(response) {
                        console.log(response)
                        _getbauser(response)
                    }, function errorCallback(response) {
                        console.log(response.statusText);
                    });
               }  else {
                   var alertPopup = $ionicPopup.alert({
                         title: 'Accesso negato!',
                         template: 'Devi essere un utente registrato, non sei loggato!'
                     });
                    console.log("NON SEI LOGGATO!!!");
            }
        },

debug:

How you can see, the get REST service returns an error, thus, let's see this REST service built in java:

package it.jack.fdd.services;

import java.util.List;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import it.jack.fdd.dao.FactoryDao;
import it.jack.fdd.dao.impl.BankAccountDaoImpl;
import it.jack.fdd.dao.interfaces.BankAccountDao;
import it.jack.fdd.domain.BankAccount;
import it.jack.fdd.domain.User;
import it.jack.fdd.dto.TokenUserDto;
import it.jack.fdd.dto.UserDto;
import it.jack.fdd.util.ConverterDTO;

@Path("/bankaccount")
public class BankAccountServices {

 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public List<BankAccount> getBankAccountOfUser() {

  BankAccountDao baDao = new BankAccountDaoImpl();
  List<BankAccount> balist = baDao.getBAByUserId(1);
  return balist;

 }

I tryed to pass the number "1" in the method, just to simplify. The method is implemented below:

package it.jack.fdd.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import it.jack.fdd.dao.interfaces.BankAccountDao;
import it.jack.fdd.domain.BankAccount;
import it.jack.fdd.domain.Staff;
import it.jack.fdd.domain.User;
import it.jack.fdd.util.HibernateUtilLezione;

public class BankAccountDaoImpl extends BaseDaoImpl<BankAccount> implements BankAccountDao{

 public List<BankAccount> getBAByUserId(int id) {

  try{

   Session session = HibernateUtilLezione.openSession();
   Transaction tx = session.beginTransaction();

   @SuppressWarnings("unchecked")
   List<BankAccount> accounts = session.createQuery("from BankAccount b "
     + "where b.user= "+id).list();

   tx.commit();
   session.close();

   return accounts;
  }
  catch(HibernateException e){
   e.printStackTrace();
   return null;
  }
 }

}

As you can see, the method ask for an id, and I put id 1 just to check, because in the database there is a field with that id. Trying in java, it returns me a list

[it.jack.fdd.domain.BankAccount@4f8d86e4]

And I checked also that the list has dimension 1 (thus, only one record, like in the database, only 1 record with that iduser)

Thus, trying to open this REST call using postman, the result is this:

The strange thing is that postman show me the same result to another REST call, that it worked before. But for this last REST call is not a problem, because strangely it works on my application, it doesn't work only in postman.
Thus, trying with Advanced REST Client I have a strange different result:

A strange, very big list that repeat every time the same field!! It is like a loop!
What happens? How I can solve?


问:
XML to MySQL check if XML field is empty
I'm learning a little about XML, MySQL and PHP by reading data from and XML file and using PHP to push that data to my MySQL table, the problem I'm running into is when an XML field is empty, it's returning an error: Notice: Trying to get property of non-object in C:\xampp\htdocs\Website\update-products.php on line 177.

How can I do a check to see if the field is empty for each object?

XML Code

```<code><?xml version="1.0"?>
<books>
  <book isbn="978-1594489501">
    <title></title>
    <author>Khaled Hosseini</author>
    <publisher>Riverhead Hardcover</publisher>
    <amazon_price></amazon_price>
  </book>
  <book isbn="978-1594489587">
    <title>The Brief Wondrous Life of Oscar Wao</title>
    <author>Junot Diaz</author>
    <publisher></publisher>
    <amazon_price>14.97</amazon_price>
  </book>
  <book isbn="978-0545010221">
    <title>Harry Potter and the Deathly Hallows</title>
    <author>J. K. Rowling</author>
    <publisher>Arthur A. Levine Books</publisher>
    <amazon_price>19.24</amazon_price>
  </book>
</books>```
```

<p><strong>Part of PHP Code</strong></p>

```$publisher = $xmlObject->item($i)->getElementsByTagName('publisher')->item(0)->childNodes->item(0)->nodeValue;
```

答:
It's hard to say exactly without seeing the code around line 177.
With that said, you'll need to check for the existence of potentially missing nodes before operating on them.

```<code>if(isset($document->node->child)){
   doStuff($document->node->child);
}
</code>```

This way you can skip missing nodes in the document without hitting an error.

Body:
I'm learning a little about XML, MySQL and PHP by reading data from and XML file and using PHP to push that data to my MySQL table, the problem I'm running into is when an XML field is empty, it's returning an error: Notice: Trying to get property of non-object in C:\xampp\htdocs\Website\update-products.php on line 177.

How can I do a check to see if the field is empty for each object?

XML Code

<?xml version="1.0"?>
<books>
  <book isbn="978-1594489501">
    <title></title>
    <author>Khaled Hosseini</author>
    <publisher>Riverhead Hardcover</publisher>
    <amazon_price></amazon_price>
  </book>
  <book isbn="978-1594489587">
    <title>The Brief Wondrous Life of Oscar Wao</title>
    <author>Junot Diaz</author>
    <publisher></publisher>
    <amazon_price>14.97</amazon_price>
  </book>
  <book isbn="978-0545010221">
    <title>Harry Potter and the Deathly Hallows</title>
    <author>J. K. Rowling</author>
    <publisher>Arthur A. Levine Books</publisher>
    <amazon_price>19.24</amazon_price>
  </book>
</books>```

Part of PHP Code

$publisher = $xmlObject->item($i)->getElementsByTagName('publisher')->item(0)->childNodes->item(0)->nodeValue;

Body:
It's hard to say exactly without seeing the code around line 177.
With that said, you'll need to check for the existence of potentially missing nodes before operating on them.

if(isset($document->node->child)){
   doStuff($document->node->child);
}

This way you can skip missing nodes in the document without hitting an error.


问:
CSS Multi Line ellipsis Cross Browser
There is a "div" in my webpage that has fixed width and height.

Following css only works with single line text:

```<code>overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
</code>```

How can I apply ellipsis on multiline text on the text inside that div using pure css with cross browser compatibility?

答:
To bad CSS doesn't support cross-browser multiline clamping, only WebKit seems to be pushing it. Any other hacky solutions don't really seem worth it at the moment because even they have their own issues.

I know how you want pure CSS and probably have your own Javascript alternative options but you could try and use a simple Javascript ellipsis library like Ellipsity on github the source code is very clean and small so if you do need to make any additional changes it should be quite easy.

https://github.com/Xela101/Ellipsity

I'm really wanting a pure CSS solution to this too to speed things up and make everything look more pretty without the need of external dependencies.

Title: CSS Multi Line ellipsis Cross Browser

Body:
There is a "div" in my webpage that has fixed width and height.

Following css only works with single line text:

overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;

How can I apply ellipsis on multiline text on the text inside that div using pure css with cross browser compatibility?


问:
Error with google sign in android
I'm trying to authenticate users on an app using firebase and google sign in Button, but it gives me the following error:

Status{statusCode=DEVELOPER_ERROR, resolution=null}

But I already have the google-service.json file because I used facebook's Button without problems. Therefore I don't know whats the problem with google's Button.

答:
In my experience The Google authentication process usually has these errors when the api credentials are not set up accurate. Make sure you have access clients containing your SHA-1 fingerprint for BOTH your debug and release keystore.
Make sure you add Google services sdk dependency in your build.Gradle and double check in your developer console if the corresponding api is enabled.
Refer this document</p>

Title: Error with google sign in android


问:
Angular Router not routing correctly with Absolute Path in subdirectory
I am trying to get Angular router to navigate to an absolute path when the site is hosted in a subdirectory.

Currently the site is hosted at:
www.example.com/ngSite/

As an example I have this code in a click event

```<code>onClick(primaryLink){
    let link: string = primaryLink.getAttribute('href');
    //I expect link to look like this: /ngSite/path/to/thing
    this.router.navigateByUrl([link]);
}
</code>```

This should navigate to:

www.example.com/ngSite/path/to/thing

But instead navigates to (notice the duplicate subdirectory):

www.example.com/ngSite/ngSite/path/to/thing

In the documentation on angular.io it says

Always specify the complete absolute path when calling router's navigateByUrl method.

Which is what I think I am doing. Perhaps I'm missing something obvious but any input would be appreciated.

答:
Do you have a redirect in your routes, like this:

RouterModule.forChild([
    { path: '', redirectTo: 'whatever' },
    { path: 'whatever', component: WhateverController },

Try replacing the redirectTo with the actual component.

RouterModule.forChild([
    { path: '', component: WhateverController },
    { path: 'whatever', component: WhateverController },

This helped my related issue with a wrong URL being produced.

Body:
I am trying to get Angular router to navigate to an absolute path when the site is hosted in a subdirectory.

Currently the site is hosted at:
www.example.com/ngSite/

As an example I have this code in a click event

onClick(primaryLink){
    let link: string = primaryLink.getAttribute('href');
    //I expect link to look like this: /ngSite/path/to/thing
    this.router.navigateByUrl([link]);
}

This should navigate to:

www.example.com/ngSite/path/to/thing

But instead navigates to (notice the duplicate subdirectory):

www.example.com/ngSite/ngSite/path/to/thing

In the documentation on angular.io it says

Always specify the complete absolute path when calling router's navigateByUrl method.

Which is what I think I am doing. Perhaps I'm missing something obvious but any input would be appreciated.


问:
Allow only one branch to be pushed to remote
We have a Git remote (for production), using OpenShift.

Locally, I want to ensure that only the master branch can be pushed to this remote. Are there any special steps I should take to ensure this happens, or should I just rely on Git defaults?

I am 99% certain that the production Git remote only looks at the master branch. So my understanding is that the only way we could push a different branch locally would be something like:

```<code>git push prod_remote a_feature_branch:master
</code>```

So my question is - is there a way to prevent someone on my team from doing that (without a force flag)?

答:
On the receiving side, the Git that is receiving commits has no notion of the branch names, if any, attached to commits on the sending Git.  All it knows is that it has received some set of objects, followed by a request to update some set of references.  If those references are spelled refs/heads/whatever, they are branch-name create, delete, or update operations for the branch named whatever.

Hence, on the receiving side, the answer is no: there is no way to prevent anyone from doing that.  If they can get commits delivered to the receiving Git at all, they can deliver whatever commits and whatever reference name updates they like.  You can use any authentication data left behind (e.g., from ssh or an access control system like Gitolite) to inspect the commits and/or the reference name updates, but you know nothing of their origin, you have only hash IDs and the names.

On the sending side, you can use a pre-push hook to do a great deal more.  A pre-push hook is run with:

$1: the name of the remote, if the push is using a named remote;

$2: the URL corresponding to $1

(if not using a named remote, the two command-line arguments are identical), and on standard input, a stream of lines, one line per push refspec, with each line having four items:

local ref (e.g., refs/heads/branch)

local hash ID

remote ref

remote hash ID

(see the githooks documentation for details).  However, the sending side hook is up to each sender, since each person has full control over her/his repository and, for that matter, whether to invoke any hooks.

If everyone who will push voluntarily opts in, you can provide them with a hook that will:

check the remote name ($1) and/or URL ($2);

if those match the repository you want protected, check whether any of the remote refs on the input stream match refs/heads/master;

if all those checks apply, check the corresponding local ref and/or hash in any way you like.

Body:
We have a Git remote (for production), using OpenShift.

Locally, I want to ensure that only the master branch can be pushed to this remote. Are there any special steps I should take to ensure this happens, or should I just rely on Git defaults?

I am 99% certain that the production Git remote only looks at the master branch. So my understanding is that the only way we could push a different branch locally would be something like:

git push prod_remote a_feature_branch:master

So my question is - is there a way to prevent someone on my team from doing that (without a force flag)?


问:
How to initialize msvcrt.dll?
If I do a LoadLibrary("msvcrt.dll") do I need to initialize the CRT somehow? Section 2 in the following document seems to say that I do, but I just get an undefined symbol error for _CRT_INIT when I try to call _CRT_INIT:

http://support.microsoft.com/kb/94248

Edit: I should have said that this is for a program that dynamically loads all the dlls that it uses, hence the call to LoadLibrary("msvcrt.dll").

答:
If you're working in C++, have you declared _CRT_INIT as extern "C"?

Have you tried using the DUMPBIN utility ( http://support.microsoft.com/kb/177429 -- if you haven't your PATH up yourself, you'll have to use the Visual Studio Command Prompt I think) with the /EXPORTS switch to see which functions are available from the CRT DLL, just to double check?

If you get stuck, VS2005 and earlier (and presumably later...) come supplied with the source code for the runtime library. For VS2005, this is in VC/crt/src, relative to the VS install folder. It looks like _CRT_INIT is the right name -- see crtdll.c and dllcrt0.c, and it's a C function.

Title: How to initialize msvcrt.dll?

OwnerDisplayName: please delete me


问:
Don't understand this Invalid argument error

Traceback (most recent call last):
  File "C:\Users\한찬희\Desktop\졸업작품\indexer_test1.py", line 191, in
<module>
    with open('./searchJson2.json/') as data_file:
OSError: [Errno 22] Invalid argument: './searchJson2.json/
```

答:
Because the path is not correct. Remove the trailing slash.

It should be:

with open('./searchJson2.json') as data_file:


问:
How to build Boost-Libraries for iPhone
Can someone tell me, where to find a detailed guide, how to build the Boost-Libraries for using it on the iPhone-Device.

I've allready build the libs for Mac and can use them in my project (only on iPhone-Simulator). While building the project for iPhone-Device, XCode haunts me a warning: "file is not of required architecture" ond some other errors.

Please Help

答:
We use boost too. To simplify its inclusion into new applications I have created a Xcode project you can drop into your workspace to include boost. It is based on a Makefile so you need the Xcode commandline tools installed.

The project is here https://github.com/Cogosense/iOSBoostFramework.

Clone the project into your workspace, then click on Menu File->"Add Files to workspace". Select iOSBoostFramework/iOSBoostFramework.xcodeproj in the file finder and click add.

The Makefile in the iOSBoostFramework directory controls what is built and how it is built. There is support for Xcode workspace dependencies, bitcode generation, and only the target architectures selected by Xcode are built.

The following libraries are built test, thread, atomic, signals, filesystem, regex, program_options, system date_time, serialization, exception, locale, and random.

All the separate libraries and architectures are combined, the final build output is a FAT boost.framework Framework bundle which can be linked into the application.

The version of boost is specified in the Makefile (currently 1.64.0), it is downloaded, built for all active architectures and installed in the BUILT_PRODUCTS_DIR specified by xcode.

Title: How to build Boost-Libraries for iPhone


问:
insert into a List alphabetically C#
Could anyone please teach me how to insert item into list in alphabetical order in C#?

So every time I add to the list I want to add an item alpabetically, the list could become quite large in theory.

Sample Code:

```<code>Public Class Person
{
     public string Name { get; set; }
     public string Age { get; set; }
}

Public Class Storage
{
    private List<Person> people;

    public Storage
    {
        people = new List<Person>();
    }

    public void addToList(person Person)
    {
        int insertIndex = movies.findindex(
            delegate(Movie movie)
            {
              return //Stuck here, or Completely off Track.

            }
        people.insert(insertIndex, newPerson);
    }

}
</code>```

答:
Old thread, but the answers in this thread IMO are ignoring OP's actual question.  The question is straightforward - how do you insert into a list in sorted order.  That's not the same as "just use a SortedSet / SortedList".  There will be different characteristics and implications based on using the below vs. using a SortedList.

SortedSet and SortedList are both based off of Dictionary, and won't allow you to add two items with the same key AFAIK.

So how do you account for a list such as, { a, b, c, c, d }?

Here is the correct way to insert into an ordered list so that the items remain ordered:

```<code>var binarySearchIndex = list.BinarySearch(item, itemComparer);
//The value will be a negative integer if the list already
//contains an item equal to the one searched for above
if (binarySearchIndex < 0)
{
    list.Insert(~binarySearchIndex, item);
}
else
{
    list.Insert(binarySearchIndex, item);
}
</code>```

Answer via this great article from 2010: https://debugmode.net/2010/09/18/inserting-element-in-sorted-generic-list-list-using-binary-search/

Title: insert into a List alphabetically C#

Body:
Could anyone please teach me how to insert item into list in alphabetical order in C#?

So every time I add to the list I want to add an item alpabetically, the list could become quite large in theory.

Sample Code:

Public Class Person
{
     public string Name { get; set; }
     public string Age { get; set; }
}

Public Class Storage
{
    private List<Person> people;

    public Storage
    {
        people = new List<Person>();
    }

    public void addToList(person Person)
    {
        int insertIndex = movies.findindex(
            delegate(Movie movie)
            {
              return //Stuck here, or Completely off Track.

            }
        people.insert(insertIndex, newPerson);
    }

}

Body:
Old thread, but the answers in this thread IMO are ignoring OP's actual question.  The question is straightforward - how do you insert into a list in sorted order.  That's not the same as "just use a SortedSet / SortedList".  There will be different characteristics and implications based on using the below vs. using a SortedList.

SortedSet and SortedList are both based off of Dictionary, and won't allow you to add two items with the same key AFAIK.

So how do you account for a list such as, { a, b, c, c, d }?

Here is the correct way to insert into an ordered list so that the items remain ordered:

var binarySearchIndex = list.BinarySearch(item, itemComparer);
//The value will be a negative integer if the list already
//contains an item equal to the one searched for above
if (binarySearchIndex < 0)
{
    list.Insert(~binarySearchIndex, item);
}
else
{
    list.Insert(binarySearchIndex, item);
}

Answer via this great article from 2010: https://debugmode.net/2010/09/18/inserting-element-in-sorted-generic-list-list-using-binary-search/


问:
getting the most 32 significant bits from unsigned long long error
I am trying to store the most significant 32 bits that is stored in unsigned long long into unsigned int.
I can simply use the code below I got from Stack Overflow:

```<code>uint64_t temp;
uint32_t msw, lsw;
msw = (temp & 0xFFFFFFFF00000000) >> 32;
lsw = temp & 0x00000000FFFFFFFF;
</code>```

However, I've used an array to do a similar thing:

```<code>unsigned long long * bits64 = new unsigned long long[1];
*(bits64 + 0) = 18446744073709551615;
unsigned int * first32 = (*(bits64 + 0) & 0xFFFFFFFF00000000) >> 32;
</code>```

Why am I getting

'Cannot initialize a variable of type 'unsigned int *' with an rvalue
  of type unsigned long long'

How do I fix this?

答:
In the statement

```<code>unsigned int * first32 = (*(bits64 + 0) & 0xFFFFFFFF00000000) >> 32;
</code>```

the LHS is of type unsigned int* while the RHS is of type unsigned long long. That's what the compiler is complaining about.

You can use:

```<code>unsigned int first32 = (*(bits64 + 0) & 0xFFFFFFFF00000000) >> 32;
</code>```

If you must use dynamically allocated memory you can use:

```<code>unsigned int * first32 = new unsigned int[1];
*first32 = (*(bits64 + 0) & 0xFFFFFFFF00000000) >> 32;
</code>```

Body:
I am trying to store the most significant 32 bits that is stored in unsigned long long into unsigned int.
I can simply use the code below I got from Stack Overflow:

uint64_t temp;
uint32_t msw, lsw;
msw = (temp & 0xFFFFFFFF00000000) >> 32;
lsw = temp & 0x00000000FFFFFFFF;

However, I've used an array to do a similar thing:

unsigned long long * bits64 = new unsigned long long[1];
*(bits64 + 0) = 18446744073709551615;
unsigned int * first32 = (*(bits64 + 0) & 0xFFFFFFFF00000000) >> 32;

Why am I getting

'Cannot initialize a variable of type 'unsigned int *' with an rvalue
  of type unsigned long long'

How do I fix this?

Body:
In the statement

unsigned int * first32 = (*(bits64 + 0) & 0xFFFFFFFF00000000) >> 32;

the LHS is of type unsigned int* while the RHS is of type unsigned long long. That's what the compiler is complaining about.

You can use:

unsigned int first32 = (*(bits64 + 0) & 0xFFFFFFFF00000000) >> 32;

If you must use dynamically allocated memory you can use:

unsigned int * first32 = new unsigned int[1];
*first32 = (*(bits64 + 0) & 0xFFFFFFFF00000000) >> 32;


问:
Alternative word delimiter than underscore (_) for PostgreSQL objects (fields, tables, etc.) which doesn't require me to use quotes ("") to query?
Is there any alternative word delimiter other than underscore (_) for PostgreSQL objects (fields, tables, etc.) which doesn't require me to use quotes ("") to query?

The special delimiter will be used to separate identically named field names based on their source table. I don't want to use schemas or different tables for this. Some dummy example field names would be:

```<code>product_line^product_name
product_line^product_description
service_station^station_name
</code>```

I've tested out hat (^) and pipe (|), and they don't work.

```<code>CREATE TABLE "my^test^table" ( "my^test^field" text )
</code>```

(I used a GUI to build the tables, and I just now notice that you have to quote the names to even create the table/field.)

Here is what I have to do to query it:

```<code>SELECT "my^test^field" FROM "my^test^table"
</code>```

... while I'd like to do:

```<code>SELECT my^test^field FROM my^test^table
</code>```

... which is possible if I've used underscores (_):

```<code>SELECT my_test_field FROM my_test_table
</code>```

Are there any alternative delimiters other than underscore (_) which could work? Preferably a normal ASCII character which isn't alphanumeric.

Edit: My best alternative at the moment is to use double underscore. But, I'd prefer something else.

答:
Based on the answers here I've decided not to use a different character as a prefix delimiter. I'm going with a double underscore (__), which is nicely parsable.

I should have been more clear on why I ultimately wanted this. The various comments I've left here explain it.

Here is an example which is pretty close to what we're probably ending at:

```<code>CREATE VIEW flat_data AS
SELECT
    hub.id,
    idx_dly.ror_sd AS idx_dly__ror_sd,
    fx_dly.ror_sd AS fx_dly__ror_sd
FROM
    hub
JOIN
    index_daily_movement AS idx_dly ON hub.id = idx_dly.hub_id
JOIN
    forex_daily_movement AS fx_dly ON hub.id = fx_dly.hub_id
...
</code>```

In the application layer it is now possible to do things like

```<code>field_name = ... e.g. 'idx_dly__ror_sd'
table_abr, base_field_name = field_name.split('__')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is there any alternative word delimiter other than underscore (_) for PostgreSQL objects (fields, tables, etc.) which doesn't require me to use quotes ("") to query?

The special delimiter will be used to separate identically named field names based on their source table. I don't want to use schemas or different tables for this. Some dummy example field names would be:

product_line^product_name
product_line^product_description
service_station^station_name

I've tested out hat (^) and pipe (|), and they don't work.

CREATE TABLE "my^test^table" ( "my^test^field" text )

(I used a GUI to build the tables, and I just now notice that you have to quote the names to even create the table/field.)

Here is what I have to do to query it:

SELECT "my^test^field" FROM "my^test^table"

... while I'd like to do:

SELECT my^test^field FROM my^test^table

... which is possible if I've used underscores (_):

SELECT my_test_field FROM my_test_table

Are there any alternative delimiters other than underscore (_) which could work? Preferably a normal ASCII character which isn't alphanumeric.

Edit: My best alternative at the moment is to use double underscore. But, I'd prefer something else.

Body:
Based on the answers here I've decided not to use a different character as a prefix delimiter. I'm going with a double underscore (__), which is nicely parsable.

I should have been more clear on why I ultimately wanted this. The various comments I've left here explain it.

Here is an example which is pretty close to what we're probably ending at:

CREATE VIEW flat_data AS
SELECT
    hub.id,
    idx_dly.ror_sd AS idx_dly__ror_sd,
    fx_dly.ror_sd AS fx_dly__ror_sd
FROM
    hub
JOIN
    index_daily_movement AS idx_dly ON hub.id = idx_dly.hub_id
JOIN
    forex_daily_movement AS fx_dly ON hub.id = fx_dly.hub_id
...

In the application layer it is now possible to do things like

field_name = ... e.g. 'idx_dly__ror_sd'
table_abr, base_field_name = field_name.split('__')