Understanding Minikube and the local IP address

Question: I am very new to kubernetes. I'm using minikube to run a k8 cluster on local machine and deploy a Redis based docker image to it. I have the following question:

After starting the minikube. I get the following output when I run cluster info. I don't understand what this IP : 192.168.49.2:8443 is and where it is coming from ?

I read up online on minikube and have understood that it spins up a cluster by creating various vm's out of local machine. So I'm guessing the IP addr that I get here is a virtual IP address.
Answer: 192.168.49.0/24 is used by the Minikube Docker driver as the default subnet. In greater detail, Minikube creates a bridge network on which the pods run; this network has this default subnet 192.168.49.0/24 with NAT. The subsequent Minikube container is on 192.168.49.2 IP.


The best overloaded method match for 'System.IO.File.WriteAllLines(string, string[], System.Text.Encoding)' has some invalid arguments

Question: I save the file to text. I read on this blog.
I don't know why this error is showing bellow.
I inserted Encode.Default. But it also fail.
How to fix this error?
The best overloaded method match for 'System.IO.File.WriteAllLines(string, string[], System.Text.Encoding)' has some invalid arguments
Argument 2: cannot convert from 'System.Collections.Generic.IEnumerable<string>' to 'string[]
Here is code in Save and Load method:
public string Serialize()`
{
    return String.Format("{0}\t{1}\t{2}", reportName, eMail, time);
}

public static void Save(List<DTOSaveFromFile> Items)
{
    File.WriteAllLines(dataPath, (from i in Items select i.Serialize()), Encoding.Default);
}

Is List<> save all data:
public class DTOSaveFromFile : List<string>
{
    public string reportName { get; set; }
    public string eMail { get; set; }
    public string time { get; set; }

    public DTOSaveFromFile(string _reportname, string _email, string _time)
    {
        reportName = _reportname;
        eMail = _email;
        time = _time;
    }

    public DTOSaveFromFile(string str)
    {
        reportName = "";
        eMail = "";
        time = "";

        try
        {
            string[] parts = str.TrimEnd().Split('\t');

            reportName = parts[0];
            eMail = parts[1];
            time = parts[2];
        }
        catch {}
    }

    public string Serialize()
    {
        return String.Format("{0}\t{1}\t{2}", reportName, eMail, time);
    }
}

Update:

Thanks all awesome people.
I resolved my problem. But I have problem when call Save() method.
I have method like:
DTOSaveFromFile file = new DTOSaveFromFile(obj.ReportName, obj.Email, obj.Time);
This is Data transfer object.
I want using Save() to save this DTO(file).
I using DiskFile.Save(file) but it show error:
The best overloaded method match for 'STU.Email.DiskFile.Save(System.Collections.Generic.List<STU.Email.DTOSaveFromFile>)' has some invalid arguments
And
Argument 1: cannot convert from 'STU.Email.DTOSaveFromFile' to 'System.Collections.Generic.List<STU.Email.DTOSaveFromFile>'
Comment: As exception said: Argument 1: cannot convert from 'STU.Email.DTOSaveFromFile' to 'System.Collections.Generic.List' - you pass instance of DTOSaveFromFile but should pass list of DTOSaveFromFiles.
Comment: Please share the `DiskFile.Save()` code
Comment: Here is DiskFile.Save(): http://pastebin.com/r0aW2gFF
and DTOSaveFromFile. http://pastebin.com/E0BwX4DL. Thank you very much.
Comment: And how do you call it? Including the `file` parameter creation
Comment: I call it with: `DTOSaveFromFile file = new DTOSaveFromFile(obj.ReportName, obj.Email, obj.Time);`
Comment: I edited my answer below.
Comment: Sorry, but I assign file[0] to obj.ReportName, file[1] to obj.Email,.... But obj is DTO of other class. Here is my full code Insert(). http://pastebin.com/nu8haJm1
Comment: Your DiskFile.Save expects collection of DTO's and you pass a single element. There are many ways to fix it. 1. Change signature to public static `void Save(params DTOSaveFromFile[] Items)`. 2. Change method invocation to `DiskFile.Save(new [] {file})` 3. Add an overload method with signature `void Save(DTOSaveFromFile Item)`.
Comment: I edited my answer again, is that what you meant?
Comment: @VadimMartynov, 1. I changed `Save(params List Items)` but not success. 2. I also change to `DiskFile.Save(new [] {file}` and 3. `void Save(DTOSaveFromFile Item)`. But all 3 method don't pass error.
Comment: Oh, 2nd solution is not right. 2. `DiskFile.Save(new List() {file});`My fault. Also 3rd solution suggests to change method body to process single dto instead of collection.
Answer: Your Save(List<DTOSaveFromFile> Items) is accepting List but you are sending a single instance of DTOSaveFromFile. Try
DTOSaveFromFile file = new DTOSaveFromFile(obj.ReportName, obj.Email, obj.Time);
File[0] = obj.ReportName;
File[1] = obj.Email;

List<DTOSaveFromFile> files = new List<DTOSaveFromFile>(1);
files.Add(file);

DiskFile.Save(files);

Comment: I was edited follow your code. It work but file[0] and file[1] cannot read data from obj.Reportname. That show error:
`Index was out of range. Must be non-negative and less than the size of the collection.

Parameter name: index`
Comment: You said you are doing that
Comment: I only copy all code and paste to my application. It's run perfect but when debug into line `file[0] = obj.ReportName;` it shows this error.
Comment: Try `file.eMail = obj.Email;`
Comment: Hey @guy, you can help me how to insert data into file text many rows? I using File.WriteAllLines() - it auto delete all rows and insert only 1 rows in text file.
Comment: I'm not familiar with this method, try [this](http://stackoverflow.com/questions/13242974/write-to-a-text-file-skipping-the-first-line). If it doesn't work try to search another solution.
Answer: You pass IEnumerable<string> to the WriteAllLines method which expect a string array as second parameter. You can add ToArray() method to execute your LINQ query and save it to C# array.
File.WriteAllLines(dataPath, (from i in Items select i.Serialize()).ToArray(), Encoding.Default);

When you are using LINQ query it doesn't evaluate immediately and allocate memory for result. You can read more about Deferred Execution on MSDN. Arrray implements IEnumerable but its implementation enumerate already calculated values in memory.
Comment: Thank you very much. I have error I updated. Can you help me?


How to send value from one fragment to another fragment from Recyclerview Adapter. Then close the first fragment and open the new Fragment

Question: I need to send a value when i click on a row in recyclerview to another fragment (I thin on OnBind in the adapter). Then i need to close the fragment that contain the recyclerview and open the receiver fragment. I read somewhere that we can use bundle, but I am pretty new to android programming so I am confused.
This is the Fragment that contain RecyclerView
public class PasienFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private OnPasienFragmentInteractionListener mPasienListener;

    public PasienFragment() {
        // Required empty public constructor
    }
    int countICU=0;
    int countINAP=0;
    int countUMUM=0;
    int countBPJS=0;

    RequestQueue queue;
    String jenisAsuransi,jenisKamar;
    String id="C0E0607E";
    ImageView ivTotal,ivIcu,ivInap,ivBpjs,ivUmum;
    TextView tvTOTAL,tvICU,tvINAP,tvBPJS,tvUMUM;

    public static final String URL_JUMLAH = "http:";

    public static PasienFragment newInstance(String param1, String param2) {
        PasienFragment fragment = new PasienFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        queue = Volley.newRequestQueue(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_pasien, container, false);
        ivTotal = (ImageView) view.findViewById(R.id.ivTotal);
        ivIcu = (ImageView) view.findViewById(R.id.ivICU);
        ivBpjs = (ImageView) view.findViewById(R.id.ivBPJS);
        ivInap = (ImageView) view.findViewById(R.id.ivINAP);
        ivUmum = (ImageView) view.findViewById(R.id.ivUMUM);

        tvTOTAL = (TextView) view.findViewById(R.id.tvTotal);
        tvICU = (TextView) view.findViewById(R.id.tvICU);
        tvBPJS = (TextView) view.findViewById(R.id.tvBPJS);
        tvINAP = (TextView) view.findViewById(R.id.tvINAP);
        tvUMUM = (TextView) view.findViewById(R.id.tvUMUM);

        ivTotal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPasienListener.onPasienFragmentInteraction("Daftar Pasien");
            }
        });

        ivIcu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPasienListener.onPasienFragmentInteraction("Daftar Pasien ICU");
            }
        });

        ivBpjs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPasienListener.onPasienFragmentInteraction("Daftar Pasien BPJS");
            }
        });

        ivInap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPasienListener.onPasienFragmentInteraction("Daftar Pasien INAP");
            }
        });

        ivUmum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPasienListener.onPasienFragmentInteraction("Daftar Pasien UMUM");
            }
        });

        String url1 = URL_JUMLAH+id;
        JsonObjectRequest req = new JsonObjectRequest(url1, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        JSONArray users = null;
                        try {
                            users = response.getJSONArray("result1");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        for (int i = 0; i < users.length(); i++) {
                            try {
                                JSONObject obj = users.getJSONObject(i);
                                jenisAsuransi = (String) obj.get("Jenis_Asuransi");
                                jenisKamar = (String) obj.get("Jenis_Kamar");
                                if(jenisAsuransi.equals("BPJS")){
                                    countBPJS++;
                                }
                                if(jenisAsuransi.equals("UMUM")){
                                    countUMUM++;
                                }
                                if(jenisKamar.equals("INAP")){
                                    countINAP++;
                                }
                                if(jenisKamar.equals("ICU")){
                                    countICU++;
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        tvTOTAL.setText(String.valueOf(users.length()));
                        tvBPJS.setText(String.valueOf(countBPJS));
                        tvUMUM.setText(String.valueOf(countUMUM));
                        tvINAP.setText(String.valueOf(countINAP));
                        tvICU.setText(String.valueOf(countICU));
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //Toast.makeText(Home.this,"Terjadi Kendala Koneksi",Toast.LENGTH_LONG ).show();
            }
        });
        queue.add(req);

        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(String sentence) {
        if (mPasienListener != null) {
            mPasienListener.onPasienFragmentInteraction(sentence);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnPasienFragmentInteractionListener) {
            mPasienListener = (OnPasienFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mPasienListener = null;
    }

    public interface OnPasienFragmentInteractionListener {
        // TODO: Update argument type and name
        void onPasienFragmentInteraction(String sentence);
    }
}

This is the RecyclerView adapter
public class ListPasienAdapter extends RecyclerView.Adapter<ListPasienAdapter.PasienViewHolder> {

    private List<Pasien> pasienList;
    public int count = 0;
    public ListPasienAdapter(List<Pasien> pasienList) {
        this.pasienList = pasienList;
    }

    @Override
    public void onBindViewHolder(final PasienViewHolder pasienViewHolder, int i) {

        final Pasien pi = pasienList.get(i);
        pasienViewHolder.tvTanggal.setText(pi.Tgl_Masuk);
        pasienViewHolder.tvNama.setText(pi.Nama_Pasien + "/" + pi.Gender);
        pasienViewHolder.tvKamar.setText(pi.No_Kamar);

        if (pi.Perawatan.toString().equals("Merah")) {
            pasienViewHolder.ivRambu.setImageResource(R.drawable.merah);
        } else if (pi.Perawatan.toString().equals("Kuning")) {
            pasienViewHolder.ivRambu.setImageResource(R.drawable.kuning);
        } else if (pi.Perawatan.toString().equals("Hijau")) {
            pasienViewHolder.ivRambu.setImageResource(R.drawable.hijau);
        }

        pasienViewHolder.ivRambu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });

    }

    @Override
    public ListPasienAdapter.PasienViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view_pasien, viewGroup, false);
        return new ListPasienAdapter.PasienViewHolder(itemView);
    }

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

    public static class PasienViewHolder extends RecyclerView.ViewHolder {
        protected TextView tvTanggal;
        protected TextView tvNama;
        protected TextView tvKamar;
        protected TextView tvGender;
        protected ImageView ivRambu;
        protected ImageView ivDown;
        protected ImageView btnIngat;
        protected ImageView btnTerkirim;
        protected TextView tvPeringatan;
        protected LinearLayout btnDetail;

        public PasienViewHolder(View v) {
            super(v);
            tvTanggal = (TextView) v.findViewById(R.id.tvTanggal);
            tvNama = (TextView) v.findViewById(R.id.tvNama);
            tvKamar = (TextView) v.findViewById(R.id.tvKamar);
            ivRambu = (ImageView) v.findViewById(R.id.ivRambu);
            ivDown = (ImageView) v.findViewById(R.id.ivDown);
            //btnIngat = (ImageView) v.findViewById(R.id.btnIngat);
            //btnTerkirim = (ImageView) v.findViewById(R.id.btnTerkirim);
            btnDetail = (LinearLayout) v.findViewById(R.id.btnDetail);
            //tvPeringatan = (TextView) v.findViewById(R.id.tvPeringatan);
        }
    }
}

This is the receiver Fragment
public class ListAktivitas extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public ListAktivitas() {
        // Required empty publtic constructor
    }

    public static final String URL_LIST_Aktivitas = "http";
    public static final String URL_Pasien = "http://";
    String id="3";
    RequestQueue queue;
    List<Aktivitas> resultAktivitas = new ArrayList<>();
    List<Pasien> resultPasien = new ArrayList<>();
    Aktivitas a = new Aktivitas();
    ListAktivitasAdapter laa;

    RecyclerView cardListAktivitas;

    Integer Urut;
    String Nama_Prosedur;
    String Id_Prosedur;
    String Id_Aktivitas;
    String Status;
    String Nama_Pasien, No_Kamar, Gender;
    Context context;

    TextView tvNamaPasien,tvKamar;

    public static ListAktivitas newInstance(String param1, String param2) {
        ListAktivitas fragment = new ListAktivitas();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        queue = Volley.newRequestQueue(getActivity());
        context = getActivity();
       }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view  = inflater.inflate(R.layout.fragment_list_aktivitas, container, false);

        cardListAktivitas = (RecyclerView) view.findViewById(R.id.cardListAktivitas);
        cardListAktivitas.setHasFixedSize(true);
        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        cardListAktivitas.setLayoutManager(llm);

        tvNamaPasien = (TextView) view.findViewById(R.id.tvNamaPasien);
        tvKamar = (TextView) view.findViewById(R.id.tvKamar);

        String url2 = URL_Pasien+id;
        JsonObjectRequest req2 = new JsonObjectRequest(url2, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        JSONArray users = null;
                        try {
                            users = response.getJSONArray("result1");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                            try {
                                JSONObject obj = users.getJSONObject(0);
                                Nama_Pasien = (String) obj.get("Nama_Pasien");
                                No_Kamar = (String) obj.get("No_Kamar");
                                if(obj.get("Gender").toString().equals("Laki-laki")){
                                    Gender = "L";
                                }else if (obj.get("Gender").toString().equals("Perempuan")){
                                    Gender = "P";
                                }
                                resultPasien.add(new Pasien(Nama_Pasien, No_Kamar,Gender));

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        tvNamaPasien.setText(Nama_Pasien+"/"+Gender);
                        tvKamar.setText("kamar:"+No_Kamar);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //Toast.makeText(Home.this,"Terjadi Kendala Koneksi",Toast.LENGTH_LONG ).show();
            }
        });
        queue.add(req2);

        String url1 = URL_LIST_Aktivitas+id;
        Toast.makeText(getActivity(), url1, Toast.LENGTH_SHORT).show();
        JsonObjectRequest req = new JsonObjectRequest(url1, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        JSONArray users = null;
                        try {
                            users = response.getJSONArray("result1");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Toast.makeText(getActivity(), "yes", Toast.LENGTH_SHORT).show();
                        Toast.makeText(getActivity(), String.valueOf(users.length()), Toast.LENGTH_SHORT).show();
                        for (int i = 0; i < users.length(); i++) {
                            try {
                                JSONObject obj = users.getJSONObject(i);
                                Urut = (Integer) obj.get("Urut");
                                Nama_Prosedur= (String) obj.get("Nama_Prosedur");
                                Id_Prosedur = (String) obj.get("Id_Prosedur");
                                Id_Aktivitas = String.valueOf(obj.getInt(Id_Aktivitas));
                                Status = (String) obj.get("Status");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            Toast.makeText(context,Nama_Prosedur, Toast.LENGTH_SHORT).show();
                            resultAktivitas.add(new Aktivitas(Urut, Nama_Prosedur, Id_Prosedur, Id_Aktivitas, Status));
                            laa = new ListAktivitasAdapter(resultAktivitas);
                            cardListAktivitas.setAdapter(laa);
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(),"Terjadi Kendala Koneksi",Toast.LENGTH_LONG ).show();
            }
        });
        queue.add(req);

        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    /*
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

*/
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

This is the activity that contain the 2 fragment
public class PasienActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,PasienFragment.OnPasienFragmentInteractionListener {

    PasienFragment pasienFragment;
    ListPasienFragment listPasienFragment;
    ListAktivitas listAktivitasFragment;

    RequestQueue queue;

    String Nama_Dokter,Nama_RS;

    public static final String URL_LIST = "http:";
    String id="vvvv";

    View navHeaderView;
    TextView tvNavDokter, tvNavRS;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pasien);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        queue = Volley.newRequestQueue(this);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        listPasienFragment = new ListPasienFragment();
        listPasienFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction().add(R.id.listPasienContainer, listPasienFragment).commit();

        pasienFragment = new PasienFragment();
        pasienFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction().add(R.id.pasienFragmentContainer,pasienFragment).commit();

        listAktivitasFragment = new ListAktivitas();
        listAktivitasFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction().add(R.id.listAktivitasContainer, listAktivitasFragment).commit();

        View navHeaderView = navigationView.getHeaderView(0);
        tvNavDokter = (TextView) navHeaderView.findViewById(R.id.tvNavDokter);
        tvNavRS = (TextView) navHeaderView.findViewById(R.id.tvNavRS);

        String url1 = URL_LIST+id;
        JsonObjectRequest req = new JsonObjectRequest(url1, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        JSONArray users = null;
                        try {
                            users = response.getJSONArray("result1");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                            try {
                                JSONObject obj = users.getJSONObject(0);
                                Nama_Dokter = (String) obj.get("Nama_Dokter");
                                Nama_RS = (String) obj.get("Rumah_Sakit");

                                tvNavDokter.setText(Nama_Dokter);
                                tvNavRS.setText(Nama_RS);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //Toast.makeText(Home.this,"Terjadi Kendala Koneksi",Toast.LENGTH_LONG ).show();
            }
        });
        queue.add(req);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        /*
        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }
        */

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onPasienFragmentInteraction(String sentence) {
        if(listPasienFragment!=null)
            listPasienFragment.updateSentence(sentence);
    }

}

Comment: [Communicating with Other Fragments](https://developer.android.com/training/basics/fragments/communicating.html)
Answer: You can send data using bundle to fragment.
EG. `Bundle data = new Bundle();
            data.putString("key", "value");
NewFragment newFragment = new NewFragment ();
newFragment.setArguments(eventDetailsData);`
Then load fragment.
To kill/remove current fragment execute below code
getActivity().onBackPressed();


Is it better to memorise each scale, or just memorise the patterns?

Question: People seem to learn different scales, each as a separate piece of knowledge - maybe for a grade 1 exam you have to know C major and A minor, then for grade 2 add E major and G major.
But isn't it better to just learn the pattern and the piano keyboard well enough you can automatically apply the pattern (major, harmonic minor, whatever) from any starting key? I don't find it very hard to do this on piano/flute/guitar - easier than memorising dozens of things like learning your multiplication tables at school!
Or, does learning each scale specifically help you when playing in the key based on that scale, i.e. you 'see' the scale notes 'highlighted' in your brain?
Comment: Learning by rote takes away the thinking process, which one hardly has time to use in the middle of an impromptu solo.I certainly can't think that fast.
Answer: It's way better to know (not memorize) what notes each scale is made of. While the pattern will help you build the scale a song won't tell you what scale you are playing in a passage, but it is typical that a passage comes directly from some scale and sometimes multiple if the song modulates to different keys or borrows concepts from different scales. Being able to identify these patterns will help your playing immensely.
Also note that on the piano, fingerings typically varies from scale to scale as the optimal fingering changes so knowing and practicing the scales in beneficial. I included a chard that demonstrates how fingers differ from scale to scale and this is just the major keys.
Comment: I would argue that whether or not entire scales or the need to use the fingerings through more than one position are very common, the idea is more about mobility on an instrument.  Learning how to quickly transition with different patterns is invaluable.  So you may not be playing a whole scale but it will teach your fingers how to move efficiently across your instrument, allowing you to more easily identify how to best play a musical passage.
Comment: @Tim I would strongly disagree that "few" tunes use longer runs from scales.
Comment: Your last para - fingering whilst playing a scale doesn't really give a lot of help. It's hardly transferrable, as few tunes use more than 3 or 4 notes consecutively straight from a scale.E.g. playing the first 5 notes from C scale, you thumb on C and F. Playing a run of CDEFG in a tune will hardly necessitate using thumb on anything apart from C, especially if the tune turns round after the G.
Comment: @MatthewRead - from all the thousands I've played - baroque, classical, romantic, popular, jazz, I reckon it's way less than 10%.But the point was more that there aren't many pieces that whole scale runs would feature in, using scales and their fingerings as found in exams,which do favour scales as part of the test.
Answer: Edit:

I have realized that you could appear to be, in part, asking for permission to escape traditional fingerings and finger patterns.
I liken this to learning to type. Many people type with just one or two fingers very quickly, but the facility of typing with ten fingers represents a speed and power that the two fingers. (no offence to those who are missing fingers.) On the one hand if you are missing fingers, you should be encouraged that great skill is still possible. On the other hand if you have all fingers but only use one or two you are definitely missing out on something that could improve your skill. Even if you are using all your fingers, there is more to it than that. You need/should try to use the correct ones for the correct keys/ strings/ frets.
There are different finger patterns possible to learn and use, but there is a standard that should be respected. It represents a great deal of study and practice and learning over the many centuries. You should not toss them aside lightly. They give you an extra benefit that automatically lifts your skill level when you use them, without the centuries of study and practice.
I was thinking in the text below, that I will leave, that you were conflicted as to what part of the study or practice of scales is essential and which can you ignore.
While all that above and below being said is true, there is a pattern to the fingering knowledge, as you suggest. On the different instruments you mentioned the patterns and the ways that they are easily recognisable are different, but there is no problem or fault in understanding and reproducing the patterns that are there rather than memorizing them by rote. If that is what you are suggesting than that is perfectly fine. Who cares how you know something if the knowledge is correct? Different people sometimes need to learn the same knowledge differently. Realize, however, that in the end if you are practising the scales and patterns and instrument(s) enough and correctly, you will memorize them by rote anyway. So there is really nothing to escape.

Study both patterns, fingerings, muscle memory, and the intellectual knowledge of the notes your playing. Did I say both. Study more than that and less than that at different moments in your practice, study in every way you can stand. Study them together and separately. The more ways you know it, he more ways you exercise and challenge your brain the better the result and benefit. Consider, for an advanced practice, to sing the notes in solfege as you play them. Also Hands together hands separately. Practice slow sometimes, and fast other times in the same session. Spend some time focusing on the metronome, and then less often without the metronome. Be able to recite the notes of the scales by rote. Be able to think about the notes of the scales and understand them. Be able to play the scales by rote. Improvise with the scale, have fun with playing the notes out of order. Play the notes out of order, in patterns like what is suggested in the Hannon studies (Hannon as a web site or Hannon as a book). Be able to play the notes of the scales and know what they are. Each way of knowing is different, and if you work it as many ways as you can, you intensify the power of your understanding. It is also possible that you engage different parts of your brain. and yet each part of the practice and study flows towards a unified understanding of the single scale.
I have found in life that when faced with a difficult decision, it turns out it is difficult because you know that the correct decision is the hardest one to do.
This is a life long study. Clearly many get by through one piece of this set of scale study and create great music, but by studying all you:

Discover your strengths and exploit them.
Improve the weakest parts of your understanding to raise your own personal bar.
You multiply the power and intensity of your practice.
Answer: You won't find it as hard on guitar, the patterns are the same! As in a maj. scale over two octaves will have exactly the same pattern on A as it will on Bb. Just move up a fret! Flute is obviously different, and piano substantially different. Each maj. scale, for example, has a different pattern from any other. So: 12 patterns for maj. 12 for minor (or is that 36...) and so on.
If you are thinking along the lines of, say, TTSTTTS for majors, it's not going to help much, if at all, as you'll play each subsequent note in relation to the last. C+T=D, D+T=E, etc.
Since lots of tunes are in one key, mostly, it will help to be able to think which set of notes work in that specific key. Like Dmaj will have all white keys except F and C, 'cos they're sharp in D. So that's the set of notes. Put them in order, like humans seem to want to do, you've got a scale.Not that many tunes actually use those notes in the scalar order, though, so just playing up and down scales isn't going to do much, except warm up the fingers, and cement the fact that those 7 notes 'belong in the same family'.
Answer to last bit : yes!
Answer: I think you should always be identifying patterns.
All scales can be broken up into groups of 3 and 4 fingers. Without understanding this critical pattern learning all the scales will seem especially difficult.

C major and scales starting on white keys using sharps in the key signature G, D, A, E, B in the right hand all use the same finger pattern 123,1234,1.
F major and scales starting on black keys Bb, Eb, Ab, Db, Gb in the right hand also use a regular permutation of 123,1234,1 like this...

    R.H. 1234,123,1234,123,1234,123,1234
    ------------------------------------
    ---F:1234,123,1---------------------
    -----Bb:4,123,1234------------------
    ---------Eb:3,1234,123--------------
    -------------Ab:34,123,123----------
    -----------------Db:23,1234,12------
    ---------------------Gb:234,123,12--
    ------------------------------------

Another way to understand the pattern of fingering for the 'flat' keys is start with the right hand fingering for C major 123,1234,1. Keep your hand in this "C" position and then add the flats for the 'flat' keys. First add the Bb then Eb, Ab, Db, Gb, Cb. As you add the flats maintain the fingering 123,1234,1. This fingering then covers all the standard fingerings for flat keys.

    R.H. 1   2   3   1   2   3   4   1

    F  : C   D   E  [F]  G   A   Bb  C

    Bb : C   D   Eb  F   G   A  [Bb] C

    Eb : C   D  [Eb] F   G   Ab  Bb  C

    Ab : C   Db  Eb  F   G  [Ab] Bb  C

    Db : C  [Db] Eb  F   Gb  Ab  Bb  C

    Gb : Cb  Db  Eb  F  [Gb] Ab  Bb  Cb

    * tonic for each scale is given in brackets

similar patterns are found in the left hand.
except for a few exceptions the fingerings do not change between major and the various minor scales.

Some methods explain these patterns, like this one...

http://ks4.imslp.info/files/imglnks/usimg/b/bf/IMSLP310820-PMLP502142-Knott_Scale_and_Arpeggio_Manual_Part1.pdf

...but IMO too many don't show crucial patterns and just notate endless scales.
If we return to part of your original question...

...learn each [scale] as a separate piece of knowledge... [or] memorize the patterns?

...it seems clear the scales are not separate and unrelated, but rather follow patterns. It's counterproductive to not seek out these patterns.
There are other patterns regarding the position of the black and white keys. Things like major 2nds and major 3rds will be keys of the same color except when crossing the B,C and E,F half steps. Perfect 4th and 5th are always the same color keys except when the the combination B and F.
Regarding memorization, I'm not sure if that's the best word. It may suggest too much conscience thought. Awareness of patterns and development of reflexive motion is maybe a better way to think about it.
Whichever way you think about it recognizing patterns should not be twisted to mean something like you do not need to practice all the scales. That would be wrong. Despite the repeating patterns the specific, physical "shape" of each scale is unique. The fingers and wrist make small adjustments to reach the changing key positions. They should all be practiced.


Change the default ErrorMessage of model validation attribute asp.net core 3.1

Question: How to avoid writing [Required(ErrorMessage="My custom error message")] every time and set the default ErrorMessage for whole project?
Comment: You could create a new public class with a static public property that contains `"My custom error message"`. However, you will need to set [Required(ErrorMessage=class.property")] everywhere instead, but it's an improvement over the string.
Answer: After some research I have found the only way to use some sort of localization and resource files. You still need to write [Required(ErrorMessage="<Resource Key Goes Here>")]. But the advantage of just using constant messages like this [Required(ErrorMessage=Class.Property)] is that you can access attribute variables in resource file.
This is how I did it:

Create a folder in root named Resources
Create an empty class in Resources folder named ValidationMessages.cs
Create an empty file in Resources folder named ValidationMessages.resx
Edit the .resx file with VisualStudio editor
Example key,value pair for [StringLength] attribute: "StringLength","Min length {2}, max length {1}"
In model use attribute [StringLength(20, MinimumLength = 10, ErrorMessage = "StringLength")]
Add this code to Startup.cs

    using MyProject.Resources;
    ...
    public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
                .AddDataAnnotationsLocalization(options => {
                    options.DataAnnotationLocalizerProvider = (type, factory) =>
                        factory.Create(typeof(ValidationMessages));
                });
        ...

It's done.
Comment: This doesn't seems to work, I've even tried to create a custom StringLocalizer to pass as a  DataAnnotationLocalizerProvider but it never gets called!
Comment: For this to work  I have to specify the ErrorMessage key with: Required(ErrorMessage = "Required")
Answer:
How to avoid writing [Required(ErrorMessage="My custom error
message")] every time and set the default ErrorMessage for whole
project?

You can create custom attributes to automatically generate error messages, but you inevitably need to add attributes to the corresponding fields to represent your constraints on the fields.

Update
If you have multiple different validation requirements, then you can merge them into a custom attribute, and inherit the ValidationAttribute class.
The premise is that you need to pass parameters to distinguish them.
Here is a case:
public class CustomRequired : ValidationAttribute
    {
        public CustomRequired(string sepcialType)
        {
            this.SepcialType = sepcialType;
        }
        public string SepcialType { get; private set; }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            string errorType;
            if (value == null)
            {
                errorType = "required";
            }
            else if (!string.IsNullOrEmpty(SepcialType) && !IsValidEmail(value.ToString()))
            {
                errorType = "not valid";
            }
            else
            {
                return ValidationResult.Success;
            }
            ErrorMessage = $"{validationContext.DisplayName}  field is {errorType}.";
            return new ValidationResult(ErrorMessage);
        }
        bool IsValidEmail(string email)
        {
            try
            {
                var addr = new System.Net.Mail.MailAddress(email);
                return addr.Address == email;
            }
            catch
            {
                return false;
            }
        }
    }

Class:
 public class ThemTest
    {
        public int Id { get; set; }
        [CustomRequired("")]
        public string Name { get; set; }
        [CustomRequired("")]
        public string Theme { get; set; }
        [CustomRequired("Email")]
        public string Email { get; set; }
    }

Validate view:
@model ThemTest
@{
    ViewData["Title"] = "TestAttr";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

TestAttr

<form method="post">

        <input asp-for="Name" type="text" class="form-control" />

        <input asp-for="Theme" type="text" class="form-control" />

        <input asp-for="Email" type="text" class="form-control" />

    <input id="Submit1" type="submit" value="submit" class="btn btn-primary" />
</form>

Here is the test result:
Comment: Good workaround but not all attributes can be inherited. For example, `EmailAddressAttribute` cannot be.
Comment: @VladislavKosovskikh, i have updated my reply, hope it can help you.
Answer: Here's how I do it.
In Startup.cs -> Configure(), set up your exception handler middleware:
app.UseExceptionHandler("/Home/Error");

This redirects all exceptions to the home controller error method.
Now set up your viewmodel for Home/Error.
In ErrorViewModel.cs:
public class ErrorViewModel
{
    public string RequestId { get; set; }
    public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
    public string ExceptionMessage { get; set; }
    public bool ShowExceptionMessage => !string.IsNullOrEmpty(ExceptionMessage);
}

In HomeController:
[AllowAnonymous]
public IActionResult Error()
{
    ErrorViewModel errorViewModel = new ErrorViewModel();
    errorViewModel.RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;

    string message = "your message";
    errorViewModel.ExceptionMessage = message;
    _logger.LogError(message);
    return View(errorViewModel);
}

At this point your custom error message will be accessible in the model of your Error view page.
Comment: I don't use views. I actually have an api server. Also, I need a separate message for every property of model. Can't see how it may help.
Comment: An API server should still work the same way. Route the exception to an error controller with middleware, then in the error controller do a switch case on the property and return that property's custom message. Please visit this link: https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-3.1


How to cache authentication in Linux using PAM/Kerberos authentication (for CVS)?

Question: We have several Linux servers that authenticate Linux user passwords on our Windows Active Directory Server using PAM and Kerberos 5. The Linux distro we use is CentOS 6.
On one system, we have several Version Control Systems like CVS and Subversion, both of which authenticate users throug PAM, such that users can use their normal Unix resp. Windows AD accounts.
Since we started using Kerberos for password authentication, we experienced that CVS on a client machine is often much slower in establishing a connection. CVS authenticates the user on every request (eg. cvs diff, log, update...).
Is is possible to cache the credentials that kerberos uses, sucht that is does not need to ask the Windows AD server every time a user executes a cvs action?
Our PAM config /etc/pam.d/system-auth looks like the following:
<code>auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        sufficient    pam_krb5.so use_first_pass
auth        required      pam_deny.so

account     required      pam_unix.so broken_shadow
account     sufficient    pam_succeed_if.so uid < 500 quiet
account     [default=bad success=ok user_unknown=ignore] pam_krb5.so
account     required      pam_permit.so

password    requisite     pam_cracklib.so try_first_pass retry=3
password    sufficient    pam_unix.so md5 shadow nullok try_first_pass use_authtok
password    sufficient    pam_krb5.so use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_krb5.so
</code>
Comment: Nscd should solve your problem.
Comment: @MateuszKwiatkowski, no it won't. nscd stands for 'Name Service Caching Daemon', it does not cache Kerberos passwords.
Answer: A program called 'sssd' can cache (Kerberos) credentials for offline (and cached) logins. I am not sure whether sssd will use cached Kerberos credentials when it's operating normally (i.e. when it's not offline), you would have to try that out.
More information about sssd here.
Comment: yes, for that in redhat 6 sssd is the default
Answer: Any authentication via PAM will always have this problem. The only way to avoid it is to kerberize the service itself, rather use a pam stack to implement authentication.
One way to do this would be to use ssh to access the cvs repository and use kerberos to authenticate to ssh. ( google ssh GSSAPI ).
There are kerberized versions of the CVS server if you don't want to allow ssh acccess to the servers hosting the cvs repository. For an example, see
http://compbio.soe.ucsc.edu/cvsdoc/cvs-manual/cvs_28.html


Completar casas decimais ",00" JavaScript

Question: Gente eu tenho a seguinte função que estou utilizando pra usar mascara de Moeda

<input class="valr-parc" type="text" name="valr-parc" />

Só que eu queria implementar nessa função .Moeda o seguinte: Quando eu digitar apenas um número (ex: 1) ele retornar "R$ 1,00" (atualmente retorna "R$ 1") e quando eu digitar 2 números (ex: 11) ele retornar "R$ 1,10" (atualmente retorna "R$ 1,1) daí a partir dessas duas condições ele já pode começar a rodar do jeito que está (ex: se digitar "111" retorna "R$ 1,11"; digitar "1111" > "R$ 11,11").
Ah, caso tenham uma função diferente (que sirva do mesmo jeito), pode mandar, mas por favor mande algum exemplo online pra testar via input (sem ser pelo "alert" ou "console", manda nesse mesmo esquema que eu mandei) pq eu eu não sei chamar a função em outros moldes (tipo "function (numero) {...")
Answer: A solução mais simples seria a utilização da função toFixed.
Segue um exemplo:

var numero = 1;

console.log(numero.toFixed(2));

Atenção que esta função arredonda os números em alguns casos.
Veja este exemplo.

var numero = 1.567;
console.log(numero.toFixed(2));
Answer: Convertendo números para moeda sem framework
É possível converter Number para String currency nativo, usando apenas a função toLocaleString(). Veja:
(10.9).toLocaleString(); // "10,90"
(1002.5).toLocaleString("pt-BR"); // "1.002,50"
(5.55).toLocaleString("pt-BR", {
  // Ajustando casas decimais
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});

O melhor disso, é que dessa forma você evita fazer as gambiarras clássicas em usar Math.abs() ou Number.prototype.toFixed() do JavaScript.
E outro detalhe legal, esta seguro contra o bug do ponto flutuante:
// Resultado bugado
0.1+0.2 // 0.30000000000000004
// Resultado sem bugs
(0.1+0.2).toLocaleString(); // "0.3"

Exemplo funcional para seu código:

$( document ).ready(function() {
    $("#verifica").on('click', function(){
      var val = new Number ($(".valr-parc").val());
        alert((val).toLocaleString("pt-BR", {
           minimumFractionDigits: 2,
           maximumFractionDigits: 2
        }));
    })
});

<input class="valr-parc" type="text" name="valr-parc" />
<button id="verifica">Verificar</button>

Fiddle
Veja mais em Number.prototype.toLocaleString()
Comment: Man, n sei como usar isso aí (tentei e não consegui) :/ Manda um exemplo com input igual está no meu atualmente, daí vc manda com as alterações


When gluing maps are isotopic?

Question: Let $M$ and $M'$ be compact orientable connected topological 3-manifolds. (One may need more conditions to answer the question.)
Suppose we have two homeomorphisms $f$ and $g$ from the boundary surface $\partial M$ to the boundary surface $\partial M'$. Consider the gluings of $M$ and $M'$ along $f$ and $g$ respectively.
Assume that the resulting manifolds $M\cup_f M'$ and $M\cup_g M'$ are homeomorphic.
Question: What can we say about a relation of $f$ and $g$? Are they isotopic?
Comment: This is false even for solid tori.
Answer: To give one possible elaboration of studiosus's counterexample, let $M = M' = S^1 \times D^2$, let $f,g\colon \partial M \to \partial M'$ be given by $(x,y) \mapsto (x,y)$ and $(-x,y) \mapsto (x,-y)$. These maps are not isotopic (think what they do to the fundamental group of $\partial M$), but both $M \cup_f M'$ and $M \cup_g M'$ are $S^1 \times S^2$.
Comment: Even easier: glue two $3$-balls along their boundary $S^2$ via either the identity not antipodal map.

When gluing maps are isotopic?


How to convert field labels to search boxes in views

Question: I have a requirement where I need to convert the labels of specific/all fields of a view to search boxes on user click. The search box will be an autocomplete field.
Here, say for eg. the label TITLE gets converted to a search box on user click and provides suggestions(from the title field) as the user types characters
Answer: Since these are completely different things you may want to add the autocomplete fields as exposed filters from the view and then add them to the label using javascript. You could use jQuery .append into the label tag with a click listener.
Comment: that's a good suggestion Miquel, let me give it a try


How to solve this radical equation for x?

Question: Question:
$$\frac{x}{\sqrt{x^2+1}} = x^4 - x$$
I tried:
$$\rightarrow \frac{1}{\sqrt{x^2+1}} = x^ 3 - 1$$
$$\to\frac{\sqrt{x^2 + 1}+1}{\sqrt{x^2+1}} = x^3$$
Now rationalising it
$$\to \frac{x^2 +1-1}{x^2+1-\sqrt{x^2+1}} = x^3$$
$$\frac{1}{x^2+1-\sqrt{x^2+1}} = x$$
Can we do anything with this? How to solve? Please help me.
Comment: from the first line to the second, you can't just simplify by $x$. What if $x = 0$!
Comment: Yes, if we simplify by $x$ we lose the fact that $0$ is a obvious solution.
Comment: $\rightarrow \frac{1}{\sqrt{x^2+1}} = x^ 3 - 1$,After this square on both sides and then cross multiply,you will get degree 6 polynomial..
Comment: Yeah that 's true.,but that seems more solvable than the current state i guess.
Comment: Not sure it helps a lot... but by monotonicity arguments, you can notice that the equation has a unique non-zero real solution.
Comment: @Anonymous Where is the problem coming from?
Comment: @Anonymous:  you use the various comments: $x=0$ is an obvious solution, and the other is between $1$ and $2$ and the root of a degree $6$ polynomial (you need to be slightly careful, as squaring introduces a spurious root between $0$ and $1$).  You can find a value for the second solution using numerical methods
Answer:
From the graph of the function :
$$f(x) = \dfrac{1}{x^2 + 1 - \sqrt{x^2 + 1}} - x$$
we see that there is only one other solution $x = 1.181$.
We deduce that solutions of the equation are $0$ and $1.181$.
Comment: It's not always possible to solve equations by elementary tools. In your case solving polynomial of high degree is impossible in general, that's why we use numerical approach. Like plotting the graph.
Comment: As was mentioned in the comments of the question, the only solutions are not this one. First you need to consider $x=0$ when you divide by $x$. But $0$ is one solution. Then, for simplicity,  just square both side of the equation instead of doing all your work here. You will need to check after your calculus which solutions fits the initial one, but it is simpler in my opinion (as stated again in the comments of the question).


If G is a group of order 6, Show that it is ismorphic to S3 or C6

Question: How can i proccess to show that G is isomorphic to S3? espetially i'am blocking in showing that if we don't have a element of order 6, then we must have an element of order 2 and 3.
thank u.
Comment: What have you tried?
Comment: Such a small group can really be taken care of by writing out all possible multiplication tables. There will be precisely two. Alternatively, take $C_2, C_3$ and see what you can do by taking their semidirect product. When doing that, one acts on the other. Check how that affects the whole thing.
Comment: Since the order of elements must divide 6, the non-identity elements must have order 2 or 3. Use this in conjunction with filling in a multiplication table as Nelli Kuukeri suggests.
Comment: Okey i see, i will try the hard way then!
Answer: Well   (and it's "or", not "and"), by Cauchy we have  elements of order $2$ and $3$.  Then since  $2\mid3-1$, you get $C_3\rtimes C_2$, which is $S_3$, or, if the action is trivial,  $C_6$.

Allow me to try to argue without Cauchy.
Suppose there are no elements of order three.  But then the group has exponent two, so is abelian. We're essentially done.
Just note that the elements of order  $3$ come in pairs.   By counting we now come up with the element of order  $2$.
Comment: thank u for the correction, english it's not my main language ^^.
Comment: but we don't have to use the cauchy theoreme, sry for not telling this earlier, so how we could proceed?
Comment: also what u mean with 2∣3−1?
Comment: Right you don't need Cauchy.  $2$ divides $3-1$.
Comment: You can use Lagrange and argue...


Converting python list of delimited items in to a pandas data frame

Question: I have a list like this where items are separated by ":".
   x=['john:42:engineer',
      'michael:29:doctor']

Is there an way to change this in to a data frame like below by defining columns Name, Age and Occupation?
    Name    Age Occupation
0   john    42  engineer
1   michael 29  doctor

Answer: You can just use split:
pd.DataFrame([y.split(':') for y in x], columns = ['Name','Age', 'Occupation'])

Output:
      Name Age Occupation
0     john  42   engineer
1  michael  29     doctor

Answer: I will do
df = pd.Series(x).str.split(':',expand=True)
df.columns = ['Name','Age', 'Occupation']
df
Out[172]:
      Name Age Occupation
0     john  42   engineer
1  michael  29     doctor

Comment: @anon01 Most of string operations in pandas/numpy are not vectorized. Converting to pandas series, if anything, only creates extra overhead.
Comment: @BEN_YO not my down vote either. Your answer is somewhat more readable than mine. List comprehension is not really reader-friendly to many people.
Comment: this is nice :).  This will likely be more performant than putting a comprehension in the constructor?
Comment: @anon01 I think so ~
Comment: looks like performance is ~ the same.  Compared execution time of this with Quang Hoang's answer using `x = x*1000000`.  Both took ~4 sec on my machine
Comment: @anon01 ah , ok ~ :-)
Comment: @QuangHoang no worry , just some random people ~ :-) I figure it out, that is why I upvote your answer and remove my comment ~~
Answer: Not sure this is the best approach, but...
x = ['john:42:engineer', 'michael:29:doctor']
x = [i.split(':') for i in x]
pd.DataFrame({'name': [i[0] for i in x], 'age': [i[2] for i in x], 'occupation': [i[1] for i in x]})

Output:

    name    age occupation
0   john    42  engineer
1   michael 29  doctor

Comment: @Quang Hoang's is better


Array usando useState React.Js Hooks

Question: Estou tendo um problema com um projeto que estou utilizando React.js, e axios para consumo da API
const [id, setId] = useState('');
const [image, setImage] = useState('');
const [att, setAtt] = useState(0);
const [nameCorrect, setNameCorrect] = useState('');
const [type, setType] = useState([])

useEffect(() => {
    api.get(props.name)
        .then(res => {
            setId(res.data.id);
            setImage(res.data.sprites.front_default);
            setType(res.data.types)
            setNameCorrect(props
               .name
               .substring(0,1)
               .toUpperCase()
               .concat(props.name.substring(1))
            );
        })

Na linha do setType(res.data.types) basicamente não está guardando a array com os dados na constante type
Esse é o link da api que estou usando, se repararem tem o types dentro do data que estou buscando https://pokeapi.co/api/v2/pokemon/1/
Observação: quando dou um console.log no types ele retorna arrays vazias.
Comment: Depende aonde você está dando console.log em `type`, se for dentro do `useEffect` que é executado sem parar nunca vai ver nenhuma atualização.
Answer: Fiz um teste no CodeSandbox e aparentemente funcionou, estou presumindo que seu
useEffect é executado apenas uma vez, com useEffect(() => {}, []). Note para o [] (array vazio) como segundo parâmetro.

Deixei o método setNameCorrect comentado, pois depende das props de seu componente.

import React, { useEffect, useState } from "react";
import "./styles.css";
import * as api from "axios";

export default function App(props) {
  const [id, setId] = useState("");
  const [image, setImage] = useState("");
  const [att, setAtt] = useState(0);
  const [nameCorrect, setNameCorrect] = useState("");
  const [type, setType] = useState([]);

  useEffect(() => {
api
  .get("https://pokeapi.co/api/v2/pokemon/1/")
  .then(({ data }) => {
    setId(data.id);
    setImage(data.sprites.front_default);

    setType(data.types);

    // setNameCorrect(
    //   props.name.substring(0, 1).toUpperCase().concat(props.name.substring(1))
    // );
  })
  .catch((err) => console.error(err));
  }, []);

  useEffect(() => {
console.log("Type value", type);
  });

  return (

{type && type.length} types

  );
}

Adicionei destructuring no retorno da Promise para melhorar a sintaxe, porém o resultado será o mesmo.
Comment: Eu tentei utilizando seu código, copiei igualzinho, mas continua dando problemas, quando eu salvo ele traz as informações, mas assim que dou um F5 ou reinicio o servidor, ele para de trazer o resultado para mim, simplismente me devolve as arrays vazias. Apenas no momento que salvo o código depois de alterado que ele me traz os dados.
Comment: O que está causando confusão para você é o `console.log` abaixo da obtenção dos dados. Ele está logando como array vazio, mas na verdade sua view já possui o valor. Não necessariamente no momento em que você realiza o log o `setType` terminou de ser executado, esta é a sacada de utilizar hooks. Editei minha resposta adicionando um outro hook para assincronamente mostrar o resultado do log e para melhor entendimento.

Array usando useState React.Js Hooks


Java applet displays itself multiple times

Question: I am making a Java applet for school whose function is to randomly select six numbers for coordinates of three points and connect them to make a triangle. It is only supposed to draw one triangle and find the "length of the sides". However when I put it on my website it will redraw itself multiple times.

I made another applet, simpler, that only selects 4 random numbers for coordinates to draw a line. Same problem.
The redrawing problem seems to happen when the user moves the screen, e.g. when I scroll or when I resize the applet viewer in Eclipse. My source code is posted here.
I appreciate any help! Thanks!
import javax.swing.JApplet;
import java.awt.*;

@SuppressWarnings("serial")
public class LineApplet extends JApplet {

    /**
     * Create the applet.
     */

    static int width;
    int height;

    public void init() {

          width = getSize().width;
          height = getSize().height;

       }

    public static int[] randomLine() {
        int[] pointArray = new int[4];
        int x;
        for (int i = 0; i < 4; i++) {
            x = ((int)(Math.random()*(width/10-2)))*20+10;
            pointArray[i] = x;
        }
        return pointArray;
    }

    public void paint(Graphics g) {
        g.setColor(Color.blue);
        int[] coords = new int[4];
        coords = randomLine();
        g.drawLine(coords[0], coords[1], coords[2], coords[3]);
        g.drawString(coords[0]/10 + ", " + coords[1]/10, coords[0], coords[1]);
        g.drawString(coords[2]/10 + ", " + coords[3]/10, coords[2], coords[3]);
        int midpointx = (coords[0] + coords[2])/2;
        int midpointy = (coords[1] + coords[3])/2;
        g.drawString(midpointx/10 + ", " + midpointy/10, midpointx, midpointy);
    }
}

Comment: Please, please, PLEASE call `super.paint(g)`.  This method does a lot of important work for you that will cause you problems in the long term if you don't respect it.
Answer: You are calculating new co-ordinates every time paint() is called.
paint() is called every time the applet window is resized or regains focus.
To fix, you could make
int[] coords = new int[4];

a class member variable and move
coords = randomLine();

to your init() method, which will only be called once upon initialization.
Addendum:

Always call super.paint(g); when overriding paint().
For custom painting using Swing, the preferred approach is to extends a JComponent component leveraging the enhanced paint functionality offered by using paintComponent.

For more see: Performing Custom Painting.
Comment: This is only masking the actual problem, while still an excellent suggestion, the OP is not respecting the component `paint` chain
Comment: Yes, while I would _strongly_ recommend to call `super.paint(g);`, this (the lack of this call) is not the reason why multiple co-ordinates are being generated.
Comment: True, but failing to call `super.paint` is going to result in the previous state begin re-generated.  So the two are related in this case - IMHO
Comment: Previous state won't really affect what is painted (as co-ords fixed from start when code fixed) but paint performance will be lousy :)
Comment: In this context, this is true, but you are still getting a dirty graphics context, if Swing has painted anything else to it, it will show up here.  Given the fact that's a top level container that has being overridden (yet another problem), it is very unlikely that this problem will present it self, but it's demonstrating bad practices (overriding a top level container's `paint` method and not calling `super.paint`) that will lead the OP down a slippery slope of probems... IMHO
Comment: I agree with everything you just said there :)
Comment: So to clarify- anything I put within the init() function will only run once, at the beginning, while everything I put in paint() will run every time it is resized?

In any case, I moved the functions to init() as suggested, thank you all so much for the help! I'm still learning, hopefully more of this will make sense later on!
Comment: Yes, that is correct. For more follow the trail [Java Applets](http://docs.oracle.com/javase/tutorial/deployment/applet/).
Answer: As pointed out by Reimues, you are re-generating your coords each time the applet is repaint.
The other problem with your paint method is actually you're not clear the previous state of the graphics context (this would have being done by paint, but you failed to respect it's functionality when you overrode it).
You have two choices.

call super.paint(g)
call super.paint(g) and call Graphics#clearRect(int, int, int, int) or Graphics#fillRect(int, int, int, int)

You should also, very rarely, need to override the paint method of top level containers.  One of the reasons is that they're not double buffered, the other is the paint chain is complex and easily broken...
You're better off using a JPanel (or such) and overriding the paintComponent method instead...
UPDATED
I updated your code to demonstrate the issues.
public class TestBadApplet extends JApplet {

    public void init() {
    }

    @Override
    public void start() {

        final LinePane linePane = new LinePane();

        setLayout(new BorderLayout());
        JButton update = new JButton("Update");
        add(linePane);
        add(update, BorderLayout.SOUTH);

        update.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                linePane.regenerate();
            }
        });

    }

    protected class LinePane extends JPanel {

        private int[] coords = new int[4];

        public void regenerate() {
            coords = randomLine();
            repaint();
        }

        public int[] randomLine() {
            int[] pointArray = new int[4];
            int x;
            for (int i = 0; i < 4; i++) {
                x = ((int) (Math.random() * (Math.min(getWidth(), getHeight()) / 10 - 2))) * 20 + 10;
                pointArray[i] = x;
            }
            return pointArray;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.blue);
            g.drawLine(coords[0], coords[1], coords[2], coords[3]);
            g.drawString(coords[0] / 10 + ", " + coords[1] / 10, coords[0], coords[1]);
            g.drawString(coords[2] / 10 + ", " + coords[3] / 10, coords[2], coords[3]);
            int midpointx = (coords[0] + coords[2]) / 2;
            int midpointy = (coords[1] + coords[3]) / 2;
            g.drawString(midpointx / 10 + ", " + midpointy / 10, midpointx, midpointy);
        }
    }
}

With super.paintComponent

Without super.paintComponent
Answer: The trouble seems to be that paint() is called every time the component needs repainting.
paint() methods should be written in a way that doesn't produce side effects and they shouldn't change the internal state of the applet. paint() must be restricted to doing just that: painting.
Comment: *"The trouble seems to be that paint() is called every time the component needs repainting"*, that's not a problem, that's how it works, but I understand what you're trying to say ;)
Comment: @MadProgrammer Haha, fair enough. It should read "The trouble with your code..."


Difference between 10.5f and (float)10.5

Question: I tried doing the following:
float a = 10.5;
//compile error (required float, provided double)

Meaning the default decimal is always double, which is 64-bit long, whereas float is 32-bit long. So technically I can't put something big in a smaller 'cup'.
Then I did some corrections, that both work. I am curious what is the difference (if there is any) between these two approaches:
float a = 10.5f;
float a = (float)10.5;

Comment: Here: `float a = 10.5f` you explicitly declare the variable a as a 32 bit containing a float value. In your second example, you're casting `10.5` (which is, by default, a double) to a float, meaning you're losing precision by doing so.
Comment: Have you seen [this](https://stackoverflow.com/questions/33163772/what-is-the-difference-between-casting-to-float-and-adding-f-as-a-suffix-whe) answer, might be it can help for you to understand the same.
Comment: @kali Makes sense. One follow up thing. Why do byte and short don't have the possibility of doing this? The only thing I can do there is cast like `byte a = (byte)10000`. Doing something like `byte a = 10000b` is impossible.
Comment: @VivekJain It helped :)
Comment: I don't know why, but it doesn't matter a whole lot since you're not losing precision
Comment: @Markus there isn't such a thing as a byte literal (the b at the end if a digit)
Answer: It is the difference between casting a double to a float or just declaring a float variable. In this instance it would be better to just declare the variable as a float as there is little point in casting a literal. Additionally, you lose precision when casting a double to a float.


Como saber quais servidores estão esperando conexão em minha rede?

Question: Estou desenvolvendo um jogo multiplayer (LAN) com Sockets em JAVA. Os jogadores irão iniciar um lobby, e nesse lobby haverá uma lista de servidores (salas de jogo) esperando por conexões.
Como posso listar os servidores que estão na minha rede para que os jogadores possam conectar-se?
Answer: Boa noite, João
A forma de fazer isso poderia ser tentando conexões com os servidores da sua faixa de IP na porta escolhida. Não recomendo que adote essa ideia, pois você precisaria conhecer os IP's da máquina (uma máquina pode responder a vários IP's), a faixa dentro da máscara de rede que eles usam e iterar sobre uma quantidade enorme de IP's para obter essa lista. Você tentaria a conexão e, se houver um "Connection Refused" significa que a outra máquina não está esperando receber nada naquela porta.
Uma forma mais interessante seria que um dos servidores centralizasse a lista com os IP/hostnames dos outros servidores de jogo. Sempre que um servidor de jogo iniciasse ele enviaria uma mensagem ao servidor centralizador informando seu IP atual.
Todos os lobbys então sempre perguntariam a esse servidor centralizador quais servidores de jogo existe e estão ativos, obteria o IP e então faria a conexão para o jogo.
Com essa técnica você as requisições de uma forma colossal e estabelece um processo simples para determinar a que IP conectar.
Comment: É uma boa solução, porém para este projeto não é viável o uso de um servidor central. Eu fiz o que essa [resposta](http://stackoverflow.com/a/3345981) sugeriu. Funciona, mas não consigo conectar a uma porta específica.
Comment: Esse exemplo só mostra como testar a capacidade de alcançar o host. A resposta do JLuann tem um exemplo de socket em uma porta específica.
Answer: Consegui resolver meu problema fazendo algumas edições num exemplo que usei como base.
Código:
public void checkHosts(String subnet) throws IOException {
    for (int i = 1; i < 255; i++) {
        String host = subnet + "." + i;

        SocketAddress sockaddr = new InetSocketAddress(host, 3128);
        Socket socket = new Socket();
        boolean connected = false;

        try {
            socket.connect(sockaddr, timeout);
            connected = true;
        } catch (SocketTimeoutException ex) {
            System.out.println(host + " isn't reachable");
        } catch (ConnectException ex) {
            System.out.println(host + " is reachable, but hasn't server on port 3128");
        }

        if (connected) {
            System.out.println(host + " has a server on port 3128!!!");
        }

        socket.close();
    }
}

Answer: Você pode tentar listar o IP dos servidores nesse lobby. Para pegar o IP de um servidor você pode usar a seguinte função:
public String getIp() {

  InetAddress ip;

  try {

    ip = InetAddress.getLocalHost();

    return ip.getHostAddress();

  } catch(UnknownHostException ex) {}

  return "IP não encontrado!";

}

Tente passar essa string do servidor para o lobby toda vez que um servidor novo for criado. E, quando for fechado, você tem que lembrar de tirar o IP do lobby também.
Espero ter ajudado!


React renderToString component unit testing

Question: Background
I am using React starter kit for my react application. Inside the server.js they are rendering component using renderToStaticMarkup and then passing it to Html component which include it using dangerouslySetInnerHTML as you can see here
I am trying to create a unit test for my AboutUs page. But because it was rendered as string inside the html component, the unit test does not work for it because it is unable to find this component
UNIT TEST
/*REACT*/
var React = require('react');
import ReactDOM from 'react-dom/server';
var TestUtils = require('react-addons-test-utils');

/*Components*/
var AboutUsPage = require('../../src/components/AboutUsPage');
var App = require('../../src/components/App');
var Html = require('../../src/components/Html');

/*UNIT TESTING*/
import sd from 'skin-deep';
var expect = require("chai").expect;

describe('AboutUsPage component', function(){
  let tree;
  let aboutElement;
  before('render and locate element', function() {
    const data = { title: '', description: '', css: '', body: '' };
    const css = [];
    const context = {
      onInsertCss: value => css.push(value),
      onSetTitle: value => data.title = value,
      onSetMeta: (key, value) => data[key] = value,
      onPageNotFound: () => statusCode = 404,
    };
    data.body = ReactDOM.renderToString(<App context={context}><AboutUsPage /></App>);
    data.css = css.join('');

    tree = sd.shallowRender();
    aboutElement = tree.dive(['App','AboutUsPage']); //could not find App or AboutUsPage components
  });

  it('it should have text hi"', function() {
    expect(tree.subTree('.htmlHead').text()).to.equal("hi"); //pass because it was in html component
  });
  it('it should have text hello"', function() {
    expect(aboutElement.subTree('.aboutHead').text()).to.equal("hello"); //fail because it was in aboutus component
  });
});

I am using mocha, chai & skin-deep for shallow rendering.
So how to write a unit test for the component which was rendered as string?
Answer: That is not a unit test. Consider what you are really trying to test. Is it a complete integration test of the server side rendering of AboutUsPage, or a AboutUsPage unit test?
If you only want to test AboutUsPage, then test that, and don't bring the rest of the components to the party. That is what a unit test is - testing individual units of code. So instead of
tree = sd.shallowRender();

just use
tree = sd.shallowRender(<AboutUsPage />);

and do your AboutUsPage related assertions on tree.
If however you want to test the whole chain, then there are several options. You already have the rendered markupstring in data.body, so you can always do some string operation and check that it contains what you're looking for. A better option might be to use a tool like jsdom that enables you to operate on the DOM in a Node environment, and use normal DOM selectors to run your assertions against.
If you really want to do your testing in a "real" environment, run your tests using PhantomJS, a headless browser that can be used with a whole bunch of test frameworks (http://phantomjs.org/headless-testing.html).


updating an object property with linq

Question: I have created an object and sadly for the life of me I couldn't figure out how to create a 3 property object with a hashed key (almost like a dictionary but instead of key and value, do key, value1 and value2)
As a work around I am using linq on a list of objects, which works fine but I want to know since linq is a querying language, can you update an object from it without creating a new object?
I want to essentially do this
    public void AddLineItemFulFilled(string itemID, int quantityOrdered, int quantityShipped)
 {
      if (!LineItems.Any(li => li.LineItemID.Equals(itemID)))
         LineItems.Add(new LineItemModel(lineItem, quantityOdered, quantityShipped));
      else
      {
          int matchingItem = 0;
          foreach(LineItemModel modUpdate in LineItems)
          {
              if(modUpdate.LineItemID.Equals(itemID) && matchingItem <= 1)
              {
                  modUpdate.QauntityShipped += quantityShipped;
                  matchingItem++;
              }
          }
      }
      else if(modUpdate.LineItemID.Equals(itemID))
         LineItems.RemoveAt(LineItems.InexOf(modUpdate));

 }

Will I get the same result with this?
 public void AddLineItemFulFilled(string itemID, int quantityOrdered, int quantityShipped)
            {
                if (!LineItems.Any(li => li.LineItemID.Equals(itemID)))
                    LineItems.Add(new LineItemModel(lineItem, quantityOdered, quantityShipped));
                else
                    LineItems.FirstOrDefault(li => li.LineItemID.Equals(itemID)).QauntityShipped += quantityShipped;
            }

Or will that make a second LineItemModel object with that ItemID?
(Alternatively is the hashed object I want to make easier than I realize? The object has 3 attributes, an ItemID string used as a de facto key, an int value of quantityShipped, essentially value1, and an int value of quantityOrdered, essentially value2)?
Comment: Are you wanting `quantityShipped` and `quantityOrdered` to participate in the uniqueness for the key, or do you want strictly `ItemID` to be the key?
Comment: just itemID, the quantityShipped is for a report later and the quantityOrdered is to compare with quantityShipped to only mark an item shipped if the item is fully shipped, so they don't need to be unique or part of any combined key, just tied to the item ID
Answer: Can you not do something as simple as this:
public class MyObject {
    public int ItemID { get; set;}
    public int QuantityShipped { get; set;}
    public int QuantityOrdered { get; set;}
}

public Dictionary<int, MyObject> myDictionary;
public string Foo(int itemId) {
    var value = myDictionary[itemId];
    return string.Format("Quantity ordered = {0}, quantity shipped = {1}", value.QuantityShipped, value.QuantityOrdered);
}

Comment: FYI, You can also use Dictionary> but it would be less readable
Comment: just basically have my entire object as the value of a dictionary with the key matching the itemID of my object? That ill probably work actually. I'm going to mark this resolved as that's a much simpler solution for me but I'll leave the question named as it is in case someone has a similar question about linq and someone can answer if the item is editied in teh original list or cloned in the second code snippet. Thank you!
Comment: There's no update on the QuantityShipped-property in this solution so probably I might have got the question wrong ...
Answer: First. There's a typo at Q(au)ntityShipped.
Second: The second approach is okay but try to avoid repeating the same lambdas because even if the syntax looks short, each one is (potentially) a loop through the whole list of objects.
I'd go for this:
public void AddLineItemFulFilled(string itemID, int quantityOrdered, int quantityShipped)
{
    var li = LineItems.FirstOrDefault(l => l.LineItemID.Equals(itemID));

    if (li == null)
      LineItems.Add(new LineItemModel(lineItem, quantityOdered, quantityShipped));
    else
        li.QuantityShipped += quantityShipped;
}

And no, FirstOrDefault wont return a second object or anything like that. If it finds the matching object you will get a pointer to that one. Changing properties on that given object will do exactly what you want.
Comment: wasnt that the solution for you?
Comment: yes bu Tim also gave me a solution with a different approach and I don't think it lets m mark both. It won't even let me upvote your answer yet

updating an object property with linq


Playing a fast but quiet Alberti bass

Question: My Alberti bass in the 3rd movement of the "Moonlight" sonata by Beethoven is way too loud, so that the melody in the right hand often vanishes. So I wonder how I can fix it. It should be played piano but also fast. If I use only forearm rotation, it is even getting louder. So I wonder if one has also to use more the fingers than the forearm. How should I practice to play fast but also piano?
I have the same problem with the triplets in the 1st movement of the "Tempest" sonata. I can play them either fast or quiet. But not both.
Answer: Some things can not be practised slowly, and this is one.
You can play this Alberti bass slow and soft several different ways, none of which would work to play it fast and soft. You have to start from some method that can play it fast. This is no different from an athlete learning how to do a high jump for example - you can't learn that by walking up to the take-off position and then trying to jump, you have to be running when you get there.
You are right to use forearm rotation, but too much energy is getting from your arm into the keys. Try playing this at full speed with forearm rotation, starting fff, and making a gradual diminuendo as far as you can go. Notice carefully what it feels like as you get softer. If you can feel you are making it softer by increasing the tension in your arm or hand, you are doing it wrong!
To get very soft, you need to combine the forearm rotation with "soft fingers" which absorb the energy of the rotation instead of transmitting it to the keys. Try the extreme of making the forearm rotation action, with your fingers making contact with the keys, but not pressing them enough to play the notes at all. Again, notice carefully what this feels like, and make sure you are doing in with your hand and arm relaxed.
You then need to stiffen your fingers just enough to make the notes sound, but not enough to play them loudly. Try doing the hand motion to play the complete Alberti bass (at full speed) but with only one of your fingers stiff enough to actually play the note. Do that for all the fingers individually, then put it all together.
When you first try this, the result will probably be uneven, with the notes sometimes sounding and sometimes not. But with practice, an even result will come.  And in reality, if this passage is played at up to tempo, softly, and with the sustain pedal, nobody will be able to hear a few silent notes anyway.
Comment: Thank you very much for the good detailed description. I thought so, that I probably hit a wall if I only practice slow.
Answer: If you can play it correctly but slowly, stick with slowly for now.  Ramp the speed up very gradually.  Success WILL come, I promise.   Check with your teacher that you're not doing anything silly.
Comment: Thank you for the comment. Should my fingers slightly lift (not too much of course) from the keys or should they stick on them like they were glued there? I am faster if they move a little bit above the keys.
Answer: From your description I would say that you are using too much weight from your arm and therefore hitting the keys too hard.
Try to ensure that your arms are in the correct position, elbows raised slightly, and control the weight that you are using to strike the keys.
And, as Laurence has already said, practise slowly and check with your teacher.
Good luck.
Comment: @Matriz The finger should lift away from the key slightly to ensure that the key returns to the correct position for the next strike.
Comment: @Matriz I lift them. The louder I want the sound, the higher I lift them, and the more I oscillate my arm from the elbow. I don't get more sound by pushing down harder on my arm so much. (Of course, different people have different ways of getting what they want. You have to find your own way.) What's most important is finding the most relaxed and most comfortable way to position your fingers for the next strike. And, as Jim says, while making sure that each key has a chance to return to its original position.
Comment: Thanks a lot for the comment. So is it ok, if my finger slightly lift (not too much of course) from the keys or should they stick on them like they were glued there?
Answer: Sounds familiar. I spent a year working up the Tempest for my senior recital in college many years ago, and I had a similar problem to overcome.
The reason that you can play fast or soft, but not both, is most likely the same as mine was: you're putting too much effort into getting all the notes in. Check and see how much effort you are putting into your arms to bear down on the keys while playing these. Play slowly and quietly, and speed up gradually. As you do, you should notice that the tension builds in your arms if you watch for it. If you are playing mostly with the fingers, you should be playing pretty quietly.
So, if you find that you are using a lot of arm exertion as you speed up, then you need to concentrate on get that out of there. Try to play the Alberti bass mostly with the fingers, and try to minimize the oscillation of the arms when playing the soft tremolos.
Answer: Children sometimes call the damper pedal the loud pedal.  So, for quiet, do the opposite.
Avoid that pedal, of course,
but also ensure that you're not holding any of those notes much longer than a sixteenth.  (Think staccato.)  Record a video of the dampers on the strings, and step through it a frame at a time, checking for more than one raised damper.

Playing a fast but quiet Alberti bass


How many two digit numbers are not a multiple of 10

Question: How many two digit numbers are not a multiple of 10.
9 *  9 = 81 correct?
Answer: Correct. More importantly, your apparent computation strategy
$$\left(\;\text{# of choices for 1st digit}\;\right)\cdot \left(\;\text{# of choices for 2nd digit}\;\right)$$
is correct.
A less-sophisticated check: There are $99$ integers from $1$ to $99$. (They count themselves!) Of these, nine are single-digits numbers, and nine are multiples of $10$. So $99-9-9 = 81$ numbers remain.
Answer: Yes, this is correct. The two digit numbers that are not a multiple of $10$ are the two digit numbers that do not contain a zero. Thus, there are $9\times9=81$ such numbers


Listar apenas uma imagem de um produto

Question: Estou fazendo um projeto, onde vai permitir que se cadastre mais de uma imagem por produto, isso vem me gerando uma certa dificuldade.
Queria que lista-se os produtos que possuem imagem e apenas uma imagem esse mesmo produto.
Obviamente talvez tenha forma mais fácil de fazer isso
Já tentei algumas formas que não vem dando o resultado correto que espero.
O que mais se aproxima do resultado final foi esse a baixo, porém duplica o produto que possuem mais de uma imagem
<code> SELECT DISTINCT *, (SELECT qc_imagens.img_nome  FROM qc_imagens
    JOIN qc_produtos on qc_produtos.pro_id = qc_imagens.img_pro_id
         WHERE qc_imagens.img_nome <> NULL AND qc_imagens.img_excluido = '0'
        order by qc_imagens.img_id DESC
         LIMIT 1) AS nome_img

         FROM qc_produtos p
 INNER JOIN qc_imagens img on img.img_pro_id = p.pro_id
 INNER JOIN qc_categorias c ON p.pro_categoria = c.cate_id
 WHERE pro_ativo = 1 AND img.img_excluido = '0'
</code>
Obrigado desde já
Answer: Tente agrupar pela coluna p.prod_id, por que ai isso força a pegar apenas a primeira linha, algo assim:
<code>SELECT  *
FROM qc_produtos p
 INNER JOIN imagens AS img ON p.pro_id = img.img_pro_id
 INNER JOIN qc_categorias c ON p.pro_categoria = c.cate_id
 WHERE pro_ativo = 1 AND img.img_excluido = '0'
 GROUP BY p.prod_id;
</code>
Comment: Não funcionou, eu não tenho o ER desse db, mas é bem isso mesmo

produtos  N --------------- 1 imagens

Um produto pode ter n imagens
Comment: Eu editei a resposta, mas se não der certo, tenta esse link tb: https://pt.stackoverflow.com/questions/96756/como-selecionar-apenas-1-registro-de-cada-id
Comment: Fala ai, até tinha conseguindo, porém sua forma bem mais enxuta, marquei como resolvido, brigado :) Tinha virado 2 subselect... uma gambs quase

Listar apenas uma imagem de um produto


Card$(\bigcup\limits_{n\in\omega} \aleph_2\times\dots\times\aleph_2)=\aleph_2$

Question: Why is the cardinality of $\bigcup\limits_{n\in\omega} \underbrace{\aleph_2\times\dots\times\aleph_2}_{n\text{ times}}$ equal to $\aleph_2$?
The cardinality of a set is the smallest ordinal number $\alpha$ such that there is a bijection $\alpha\xrightarrow[]{\text{bij}}\bigcup\limits_{n\in\omega} \underbrace{\aleph_2\times\dots\times\aleph_2}_{n\text{ times}}$
But I have no idea what $\aleph_2$ looks like
Answer: $\aleph_2$ is the smallest cardinal that is bigger than $\aleph_1$, which is the smallest cardinal bigger than $\aleph_0=\omega$. We cannot say much beyond that about $\aleph_2$, for example how it compares to the cardinality of $\Bbb R$.
However, if $\alpha$ is any infinite cardinal, then $\alpha\times \alpha\approx \alpha$ by essentially the same diagonal argument that shows $\Bbb N\times \Bbb N\approx \Bbb N$. By induction, $\alpha\times\ldots\times \alpha\approx \alpha$ and  even more so $\alpha\times \omega\approx \alpha$ and of course the union of $\omega$-many sets of cardinality $\alpha$ is also $\approx\alpha$.
Comment: Great. What do you mean "even more so"? since $\alpha$ is infinite don't we have $\alpha\ge\omega$? So that $\alpha\times\omega\approx\alpha$ was obvious once you wrote $\alpha\times\alpha\approx\alpha$?


dropping dataframe rows based on multiple conditions

Question: I am trying to drop some rows from a pandas DataFrame based on 4 conditions needing to be met in the same row.
So I tried the following command:
my_data.drop(my_data[(my_data.column1 is None) & (my_data.column2 is None) & (my_data.column3 is None) & (my_data.column4 is None)].index, inplace=True)

And it throws this error:
enter image description here
I've also tried:
my_data= my_data.loc[my_data[(my_data.column1 is None) & (my_data.column2 is None) & (my_data.column3 is None) & (my_data.column4 is None), :]

but without success
Can i get some help please :)
I'm working on python 3.5
Answer: Normally, a column is checked for nullness with the isnull method:
df.drop(df[df['column1'].isnull()
          & df['column2'].isnull()
          & df['column3'].isnull()
          & df['column4'].isnull()].index)

However, there are more compact and idiomatic ways for that:
df.dropna(subset=['column1', 'column2', 'column3', 'column4'], how='all')

A demo:
prng = np.random.RandomState(0)
df = pd.DataFrame(prng.randn(100, 6), columns=['column{}'.format(i) for i in range(1, 7)])

df.head()
Out:
    column1   column2   column3   column4   column5   column6
0  1.764052  0.400157  0.978738  2.240893  1.867558 -0.977278
1  0.950088 -0.151357 -0.103219  0.410599  0.144044  1.454274
2  0.761038  0.121675  0.443863  0.333674  1.494079 -0.205158
3  0.313068 -0.854096 -2.552990  0.653619  0.864436 -0.742165
4  2.269755 -1.454366  0.045759 -0.187184  1.532779  1.469359

df = df.mask(prng.binomial(1, 0.5, df.shape).astype('bool'), np.nan)

df.head()
Out:
    column1   column2   column3   column4   column5   column6
0       NaN  0.400157       NaN  2.240893       NaN       NaN
1  0.950088 -0.151357 -0.103219  0.410599  0.144044       NaN
2  0.761038  0.121675       NaN       NaN       NaN -0.205158
3       NaN       NaN -2.552990       NaN  0.864436       NaN
4  2.269755 -1.454366  0.045759 -0.187184       NaN       NaN

The following drops rows only if columns 1, 3, 5 and 6 are null:
df.dropna(subset=['column1', 'column3', 'column5', 'column6'], how='all').head()
Out:
    column1   column2   column3   column4   column5   column6
1  0.950088 -0.151357 -0.103219  0.410599  0.144044       NaN
2  0.761038  0.121675       NaN       NaN       NaN -0.205158
3       NaN       NaN -2.552990       NaN  0.864436       NaN
4  2.269755 -1.454366  0.045759 -0.187184       NaN       NaN
5  0.154947  0.378163 -0.887786 -1.980796 -0.347912       NaN

Comment: I was just about to add the second one :-)


LIMITAR A DOIS CARACTERES DE SAÍDA COM REGEX - POSTGRESQL

Question: Eu tenho a consulta abaixo que me retorna apenas os valores numéricos do meu campo de string, eu queria limitá-lo a dois caracteres de saída.
QUERY
SELECT NULLIF(regexp_replace(temperature, '\D','','g'), '')::numeric AS "Temperature"
from tbl_temperature_hosts
where temperature like '%Core 0%' limit 1

OUTPUT
6601205698

EXPECTED OUTCOME
66

Answer: Se entendi corretamente seu problema tente:
SELECT LEFT(NULLIF(REGEXP_REPLACE(temperature, '\D','','g'), ''), 2)::numeric AS "Temperature"
FROM tbl_temperature_hosts
WHERE temperature LIKE '%Core 0%' LIMIT 1

Comment: Perfeito, obrigado!


keystore was not valid(corona sdk)

Question: I builded a game in corona sdk and when I want to build my game to android
after it says:
D:\Corona SDK\Resources\debug.keystore was not valid

What can I do for this?
Answer: I have never used Corona SDK, however seems like you are using the wrong user/password for your debug.keystore file.
The default user/password for the debug.keystore is android/android, unless you have already changes those values.

keystore was not valid(corona sdk)