text:
Q: Android Studio: Issue with OnResume and SharedPreferences: Fatal Error at Runtime All,
Just want to be straight with everyone that I have no idea what I am doing lol. But I am having an issue implementing SharedPreferences onPause\onResume in this project, and I am wondering if someone can tell me where I am going wrong.
Error details:
`E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.androidlabs, PID: 2260
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.androidlabs/com.example.androidlabs.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:173)
        at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
        at android.content.Context.obtainStyledAttributes(Context.java:744)
        at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:848)
        at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:815)
        at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
        at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:259)
        at com.example.androidlabs.MainActivity.<init>(MainActivity.java:19)
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
        at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) `

Here is my main activity code. I can tell that the issue is coming from onResume (I think!) but no clue why!
`package com.example.androidlabs;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    //initializing variables
    Button next = (Button) findViewById(R.id.next);
    EditText name = (EditText) findViewById(R.id.name);       //initializing variables

    public static final String SHARED_PREF = "sharedprefs";
    public static final String TEXT = "text";
    private String text;

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

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences sh = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
                SharedPreferences.Editor editor = sh.edit();
                editor.putString("name", name.getText().toString());
                editor.apply();
                openNameActivity();
            }
        });

    }

        @Override
        protected void onResume() {
            super.onResume();
            SharedPreferences sh = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            String savedName = sh.getString("name",null);
            if (savedName != null){
                name.setText(savedName);
            }

        }

       @Override
        protected void onPause() {
            super.onPause();
           SharedPreferences sh = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            //save the users name in My Shared Pref
            SharedPreferences.Editor editor = sh.edit();
            editor.putString("name", name.getText().toString());
            editor.apply();

        }

    public void openNameActivity(){
        EditText name = (EditText) findViewById(R.id.name);
        String nameText = name.getText().toString();

        Intent intent = new Intent(MainActivity.this, NameActivity.class);
        intent.putExtra("name", nameText);
        startActivityForResult(intent, 1);
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if(resultCode == RESULT_OK){
                int result = data.getIntExtra("namePref", 0);
                if(result == 0){
                    Toast.makeText(MainActivity.this,"Choose a new name", Toast.LENGTH_LONG).show();
                }else{
                    finishAndRemoveTask();
                }
            }
            if(resultCode == RESULT_CANCELED){
                Toast.makeText(MainActivity.this,"Something went wrong", Toast.LENGTH_LONG).show();
            }

        }

    }
}`

A: Your app is crashing when you open your app?
It looks like you are doing initialisation of your button and editText at wrong place
can you move below mentioned code to onCreate method and place it below of setContentView method
next = (Button) findViewById(R.id.next);
name = (EditText) findViewById(R.id.name);

and also you will need to declare next and name both variable


text:
Q: What does >* do? I encounter this several times, but i don't now what >* exactly is? I think it overwrites something, but i'm not sure.
.GridWrapper>* {
font-size: 14px
}

@media screen and (min-width:601px) {
.GridWrapper>* {
    font-size: 17px
}
}

A: A > B selector will select an element B that is a direct child of an element A; similar to A B, where it can be any descendant. * is any element. Thus, .GridWrapper > * means "all direct children of elements classed GridWrapper".
More on MDN.

A: It simply means to select elements directly under the class GridWrapper to have a font-size of 14px.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can not delete item that is selected, only deletes the last item added I'm trying to delete the selected item in my RecyclerView, but when I click on my delete Button it just deletes the last item added. And after I delete the last item added I can not delete anymore. What am I missing?
MainActivity
public class MainWishActivity extends AppCompatActivity {

private NavigationView navigationView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private RecyclerView wishList;
private androidx.appcompat.widget.Toolbar mToolbar;

private ImageButton ibaddnewwishlist;

private CircleImageView NavProfileImage;
private TextView NavProfileFirstName, NavProfileLastName;

private FirebaseAuth mAuth;
private DatabaseReference UsersRef, WishListRef;

String currentUserID;

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

    mAuth = FirebaseAuth.getInstance();

    currentUserID = mAuth.getCurrentUser().getUid();

    UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
    WishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister").child(currentUserID);

    mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setTitle(" Dine Ønskelister");

    drawerLayout = (DrawerLayout)findViewById(R.id.drawable_layout);
    actionBarDrawerToggle = new ActionBarDrawerToggle(MainWishActivity.this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
    drawerLayout.addDrawerListener(actionBarDrawerToggle);
    actionBarDrawerToggle.syncState();
    ibaddnewwishlist = (ImageButton)findViewById(R.id.ib_addnewwishlist);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    navigationView = (NavigationView)findViewById(R.id.navigation_view);

    wishList = (RecyclerView)findViewById(R.id.rv_wishlist);
    wishList.setHasFixedSize(true);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setReverseLayout(true);
    linearLayoutManager.setStackFromEnd(true);
    wishList.setLayoutManager(linearLayoutManager);

    View navView = navigationView.inflateHeaderView(R.layout.navigation_header);

    NavProfileImage = (CircleImageView)navView.findViewById(R.id.civ_navprofilepicture);
    NavProfileFirstName = (TextView)navView.findViewById(R.id.tv_headerfirstname);
    NavProfileLastName = (TextView) navView.findViewById(R.id.tv_headerlastname);

    UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (dataSnapshot.exists()){

                if (dataSnapshot.hasChild("fornavn")){
                    String firstname = dataSnapshot.child("fornavn").getValue().toString();
                    NavProfileFirstName.setText(firstname);
                }

                if (dataSnapshot.hasChild("etternavn")) {
                    String lastname = dataSnapshot.child("etternavn").getValue().toString();
                    NavProfileLastName.setText(lastname);
                }

                if (dataSnapshot.hasChild("profilbilde")){
                    String image = dataSnapshot.child("profilbilde").getValue().toString();
                    Picasso.with(MainWishActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);

                }
                else{
                    Toast.makeText(MainWishActivity.this, "Profil navn finnes ikke...", Toast.LENGTH_SHORT).show();
                }

            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            UserMenuSelector(item);
            return false;
        }
    });

    ibaddnewwishlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            SendUserToWishListActivity();

        }
    });

    DisplayUsersWishLists();
}

private void DisplayUsersWishLists() {

    FirebaseRecyclerAdapter<WishListClass, WishListViewHolder > firebaseRecyclerAdapter =
            new FirebaseRecyclerAdapter<WishListClass, WishListViewHolder>
                    (
                            WishListClass.class,
                            R.layout.wish_list_single_layout,
                            WishListViewHolder.class,
                            WishListRef

                    ) {
                @Override
                protected void populateViewHolder(WishListViewHolder viewHolder, WishListClass model, final int position) {

                    final String Key = getRef(position).getKey();

                    viewHolder.setFornavn(model.getFornavn());
                    viewHolder.setDate(model.getDate());
                    viewHolder.setTitle(model.getTitle());
                    viewHolder.setProfilbilde(getApplicationContext(), model.getProfilbilde());

                    viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            Intent profileIntent = new Intent(MainWishActivity.this, UserWishItemActivity.class);
                            profileIntent.putExtra("Key", Key);
                            startActivity(profileIntent);
                        }
                    });
                }
            };

    wishList.setAdapter(firebaseRecyclerAdapter);

}

public static class WishListViewHolder extends RecyclerView.ViewHolder{

    View mView;

    public WishListViewHolder(@NonNull View itemView) {
        super(itemView);
        mView = itemView;

    }

    public void setFornavn (String fornavn){

        TextView wishlist_name = (TextView) mView.findViewById(R.id.tv_firstnamelist);
        wishlist_name.setText(fornavn);

    }

    public void setProfilbilde (Context ctx, String profilbilde){

        CircleImageView image = (CircleImageView) mView.findViewById(R.id.civ_profilepicturelist);
        Picasso.with(ctx).load(profilbilde).into(image);

    }

    public void setDate (String date){

        TextView wishlist_date = (TextView) mView.findViewById(R.id.tv_publisheddatelist);
        wishlist_date.setText("    " + date);
    }

    public void setTitle (String title){

        TextView wishlist_title = (TextView) mView.findViewById(R.id.tv_wishlisttitle);
        wishlist_title.setText(title);
    }

}
private void SendUserToWishListActivity(){

    Intent addNewPostIntent = new Intent(MainWishActivity.this, AddWishListActivity.class);
    startActivity(addNewPostIntent);

}

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

    FirebaseUser currentUser = mAuth.getCurrentUser();
    if (currentUser == null){
        SendUserToLoginActivity();

    }
    else
    {
        CheckUserExistence();
    }

}

private void CheckUserExistence(){

    final String current_user_id = mAuth.getCurrentUser().getUid();

    UsersRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (!dataSnapshot.hasChild(current_user_id)){

                SendUserToUserInfoAcitivity();
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}

private void SendUserToUserInfoAcitivity(){

    Intent setupIntent = new Intent(MainWishActivity.this, UserInfoActivity.class);
    setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(setupIntent);
    finish();
}

private void SendUserToLoginActivity() {
    Intent loginIntent = new Intent(MainWishActivity.this, LoginActivity.class);
    loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(loginIntent);
    finish();
}

private void SendUserToFindFriendsActivity(){

    Intent findfriendsIntent = new Intent(MainWishActivity.this, FindFriendsActivity.class);
    findfriendsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(findfriendsIntent);
    finish();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (actionBarDrawerToggle.onOptionsItemSelected(item))
    {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private void UserMenuSelector (MenuItem item){

    switch (item.getItemId()){

        case R.id.navbtn_addwishlist:
            SendUserToWishListActivity();
            break;

        case R.id.navbtn_profile:
            Toast.makeText(this, "Profil", Toast.LENGTH_SHORT).show();
            break;

        case R.id.navbtn_home:
            Toast.makeText(this, "Hjem", Toast.LENGTH_SHORT).show();
            break;

        case R.id.navbtn_friends:
            Toast.makeText(this, "Venner", Toast.LENGTH_SHORT).show();
            break;

        case R.id.navbtn_findfriends:
            SendUserToFindFriendsActivity();
            break;

        case R.id.navbtn_settings:
            Toast.makeText(this, "Instillinger", Toast.LENGTH_SHORT).show();
            break;

        case R.id.navbtn_logout:
            mAuth.signOut();
            SendUserToLoginActivity();
            break;

    }

}

SecondActivity
public class UserWishItemActivity extends AppCompatActivity {

private TextView tvwishlisttitle;
private EditText etwishitem;
private Button btnaddwishitem;
private RecyclerView wishListitems;

private String currentUserID, databaseUserID;
private String Key, postRandomName;
private DatabaseReference WishListUsersClickRef, UsersRef, WishItemsRef, wishListRef,WishItemsRef1;

private FirebaseAuth mAuth;

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

    Key = getIntent().getExtras().get("Key").toString();

    mAuth = FirebaseAuth.getInstance();

    currentUserID = mAuth.getCurrentUser().getUid();

    UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
    WishItemsRef = FirebaseDatabase.getInstance().getReference().child("Ønsker");
    wishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister").child(currentUserID).child(Key);

    tvwishlisttitle = (TextView)findViewById(R.id.tv_userwishlisttitle);
    etwishitem = (EditText)findViewById(R.id.et_wishitem);
    btnaddwishitem = (Button)findViewById(R.id.btn_addwishitem);

    btnaddwishitem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            CreateWishlist();

        }
    });

    wishListitems = (RecyclerView)findViewById(R.id.rv_wishlistitems);
    wishListitems.setHasFixedSize(true);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setReverseLayout(true);
    linearLayoutManager.setStackFromEnd(true);
    wishListitems.setLayoutManager(linearLayoutManager);

    WishListUsersClickRef = FirebaseDatabase.getInstance().getReference("Ønskelister").child(currentUserID).child(Key);

    WishListUsersClickRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            if (dataSnapshot.exists()){

            String title = dataSnapshot.child("title").getValue().toString();

            databaseUserID = dataSnapshot.child("uid").getValue().toString();

            tvwishlisttitle.setText(title);

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    DisplayWishListItems();

}

private void DisplayWishListItems() {

    FirebaseRecyclerAdapter<WishItemClass, WishListItemsViewHolder > firebaseRecyclerAdapter =
            new FirebaseRecyclerAdapter<WishItemClass, WishListItemsViewHolder>
                    (
                            WishItemClass.class,
                            R.layout.wish_list_item_layout,
                            WishListItemsViewHolder.class,
                            WishItemsRef.child(Key)

                    ) {
                @Override
                protected void populateViewHolder(final WishListItemsViewHolder viewHolder, final WishItemClass model, final int position) {

                    viewHolder.setWishitemname(model.getWishitemname());

                    viewHolder.m1View.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View view) {

                            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(UserWishItemActivity.this);
                            LayoutInflater inflater = getLayoutInflater();
                            final View dialogView = inflater.inflate(R.layout.endreslettjobb_dialog, null);

                            dialogBuilder.setView(dialogView);

                            dialogBuilder.setTitle(model.getWishitemname());

                            final AlertDialog alertDialog = dialogBuilder.create();
                            alertDialog.show();

                            final Button btndelete = (Button)dialogView.findViewById(R.id.btn_delete);

                            btndelete.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                    WishItemsRef.removeValue();

                                }
                            });

                            return false;

                        }
                    });

                }
            };

    wishListitems.setAdapter(firebaseRecyclerAdapter);

}

public static class WishListItemsViewHolder extends RecyclerView.ViewHolder{

    View m1View;

    public WishListItemsViewHolder(@NonNull View itemView) {
        super(itemView);
        m1View = itemView;

    }

    public void setWishitemname (String wishitemname){

        TextView wishitem_name = (TextView) m1View.findViewById(R.id.tv_wishitemname);
        wishitem_name.setText(wishitemname);

    }

    public void setUid (String uid){

    }

}

private void CreateWishlist() {

    postRandomName = String.valueOf(new Date().getTime());

    final String wishlist = etwishitem.getText().toString().trim();

    etwishitem.setText("");

    wishListRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (dataSnapshot.exists()) {

                HashMap postMap = new HashMap();
                postMap.put("uid", currentUserID);
                postMap.put("wishitemname", wishlist);
                WishItemsRef.child(Key).child(postRandomName).updateChildren(postMap)
                        .addOnCompleteListener(new OnCompleteListener() {
                            @Override
                            public void onComplete(@NonNull Task task) {

                                }

                        });

            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}

AddItemActivity
private Spinner spwishlisttitle;
private Button btnsavewishlist;

private DatabaseReference UsersRef, wishListRef;

private FirebaseAuth mAuth;

private String saveCurrentDate, currentUserID, postRandomName;

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

    UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
    wishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister");
    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();

    spwishlisttitle = (Spinner) findViewById(R.id.sp_wishlisttitle);
    btnsavewishlist = (Button) findViewById(R.id.btn_savewishlist);

    btnsavewishlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

           CreateWishlist();

        }
    });

}

private void CreateWishlist() {

    Calendar calFordDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(calFordDate.getTime());

    postRandomName = String.valueOf(new Date().getTime());

    final String wishlist = spwishlisttitle.getSelectedItem().toString().trim();

    UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (dataSnapshot.exists()) {

                String userFirstname = dataSnapshot.child("fornavn").getValue().toString();
                String userProfileImage = dataSnapshot.child("profilbilde").getValue().toString();

                HashMap postMap = new HashMap();
                postMap.put("uid", currentUserID);
                postMap.put("date", saveCurrentDate);
                postMap.put("title", wishlist);
                postMap.put("profilbilde", userProfileImage);
                postMap.put("fornavn", userFirstname);
                wishListRef.child(currentUserID).child(currentUserID + postRandomName).updateChildren(postMap)
                        .addOnCompleteListener(new OnCompleteListener() {
                            @Override
                            public void onComplete(@NonNull Task task) {

                                if (task.isSuccessful()) {

                                    SendUserToMainActivity();
                                    Toast.makeText(AddWishListActivity.this, "Ønskeliste opprettet", Toast.LENGTH_SHORT).show();

                                } else {

                                    Toast.makeText(AddWishListActivity.this, "Error ocurred", Toast.LENGTH_SHORT).show();

                                }

                            }
                        });

            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}

private void SendUserToMainActivity() {

    Intent mainIntent = new Intent(AddWishListActivity.this, MainWishActivity.class);
    startActivity(mainIntent);
}

}

I have edited my question with my code.
Hope this is helpful.


text:
Q: how to display a keyboard on the screen I have this,

       <textz id="1">1</textz>
       <textz id="2">2</textz>
       <textz id="3">3</textz>
       <textz id="4">4</textz>
       <textz id="5">5</textz>
       <textz id="6">6</textz>
       <textz id="7">7</textz>
       <textz id="8">8</textz>
       <textz id="Q">Q</textz>
      <textz id="e">E</textz>
      <textz id="x">X</textz>
      <textz id="r">R</textz>
      <textz id="c">C</textz>
      <textz id="entr" style="width:70px">Enter</textz>
      <textz id="esc" style="width:70px">ESC</textz>
      <textz style="background:transparent;"></textz>
      <textz style="background:transparent;"></textz>
      <textz style="background:transparent;"></textz>
      <textz style="background:transparent;"></textz>
      <textz style="background:transparent;"></textz>
      <textz id="w">W</textz>
      <textz style="background:transparent;"></textz>
      <textz style="background:transparent;"></textz>
      <textz style="background:transparent;"></textz>
      <textz style="background:transparent;"></textz>
      <textz style="background:transparent;"></textz>
      <textz style="background:transparent;"></textz>
      <textz style="background:transparent;"></textz>
      <textz id="a">A</textz><textz id="s">S</textz><textz id="d">D</textz>
      <textz id="space" style="width:97%;">Space</textz>

It works by itself but when I paste it in to moomoo.io (with Ctrl + Shift + I) it doesn't work any more, this is a simple "keyboard" that shows what keys I press to show the people on YouTube. I'm not hacking or cheating for example. I just want it to work on any website I add the code too, thanks. (press the snippet, and hit 1, 2, 3)

A: Not what you asked for, but I simplified your javascript code. I added all your key codes into an array, and then I simply do a look up.

If you want to inject this into Moo Moo:

*

*Open the developer tools (F12) while on moomoo.io.

*Copy the HTML code, including the style tag (second grey box below).

*In the Inspector tab: scroll to the bottom of the page:

*Firefox: Right click on
 and choose Paste / InnerHTML.

*Chrome: Right click on
 and choose Edit HTML. Paste the HTML code and click somewhere outside the HTML code.

*The keyboard should now pop up at the top left corner. Now it's time to bind some functionality to it.

*Click on the Console tab.

*Copy the javascript code (first box below). Paste it in the input, at the bottom of the page.

That would set you up with a working graphical representation of a keyboard.

var keys = [];
keys[13] = 'entr';
keys[27] = 'esc';
keys[32] = 'space';
keys[49] = 1;
keys[50] = 2;
keys[51] = 3;
keys[52] = 4;
keys[53] = 5;
keys[54] = 6;
keys[55] = 7;
keys[56] = 8;
keys[65] = 'a';
keys[67] = 'c';
keys[68] = 'd';
keys[69] = 'e';
keys[81] = 'Q';
keys[87] = 'w';
keys[83] = 's';
keys[88] = 'x';
keys[82] = 'r';

function checkKey(event, background) {
  let keyCode = event.keyCode;

  if (keys[keyCode]) {
    document.getElementById(keys[keyCode]).style.background = background;
  }
}

document.addEventListener('keydown', (event) => checkKey(event, 'white'));
document.addEventListener('keyup',   (event) => checkKey(event, 'rgb(0, 0, 0, .5)'));

  <textz id="1">1</textz>
  <textz id="2">2</textz>
  <textz id="3">3</textz>
  <textz id="4">4</textz>
  <textz id="5">5</textz>
  <textz id="6">6</textz>
  <textz id="7">7</textz>
  <textz id="8">8</textz>
  <textz id="Q">Q</textz>
  <textz id="e">E</textz>
  <textz id="x">X</textz>
  <textz id="r">R</textz>
  <textz id="c">C</textz>
  <textz id="entr" style="width:70px">Enter</textz>
  <textz id="esc" style="width:70px">ESC</textz>
  <textz style="background:transparent;"></textz>
  <textz style="background:transparent;"></textz>
  <textz style="background:transparent;"></textz>
  <textz style="background:transparent;"></textz>
  <textz style="background:transparent;"></textz>
  <textz id="w">W</textz>
  <textz style="background:transparent;"></textz>
  <textz style="background:transparent;"></textz>
  <textz style="background:transparent;"></textz>
  <textz style="background:transparent;"></textz>
  <textz style="background:transparent;"></textz>
  <textz style="background:transparent;"></textz>
  <textz style="background:transparent;"></textz>
  <textz id="a">A</textz>
  <textz id="s">S</textz>
  <textz id="d">D</textz>
  <textz id="space" style="width:97%;">Space</textz>


text:
Q: Css bounce animation not working, Why? I am creating scroll top icon just like demo: http://demo.themeum.com/html/eshopper/.
Here in demo scroll top icon is bouncing infinite. I want to create this one for my page also.
But i can't figure out why my effort not working? Fiddle
CSS:
a#scrollUp {
bottom: 0px;
right: 10px;
padding: 5px 10px;
background: #FE980F;
color: #FFF;
-webkit-animation: bounce 2s ease infinite;
animation: bounce 2s ease infinite;
}

A: you've missed out the declare keyframe animation in your css, update your css with the below
CSS
a#scrollUp {
    animation: 2s ease 0s normal none infinite bounce;
    background: none repeat scroll 0 0 #fe980f;
    bottom: 0;
    color: #fff;
    padding: 5px 10px;
    right: 10px;
}

@-webkit-keyframes bounce {
    0%, 20%, 50%, 80%, 100% {-webkit-transform: translateY(0);}
    40% {-webkit-transform: translateY(-30px);}
    60% {-webkit-transform: translateY(-15px);}
}

@-moz-keyframes bounce {
    0%, 20%, 50%, 80%, 100% {-moz-transform: translateY(0);}
    40% {-moz-transform: translateY(-30px);}
    60% {-moz-transform: translateY(-15px);}
}

@-o-keyframes bounce {
    0%, 20%, 50%, 80%, 100% {-o-transform: translateY(0);}
    40% {-o-transform: translateY(-30px);}
    60% {-o-transform: translateY(-15px);}
}
@keyframes bounce {
    0%, 20%, 50%, 80%, 100% {transform: translateY(0);}
    40% {transform: translateY(-30px);}
    60% {transform: translateY(-15px);}
}

.animated.bounce {
    -webkit-animation-name: bounce;
    -moz-animation-name: bounce;
    -o-animation-name: bounce;
    animation-name: bounce;
}

Fiddle Demo


text:
Q: Save captured image in specific folder on sd card I'm working with camera in android and I'm new to android camera. I've followed the tutorial from here
Whenever I'll add External storage permission in android manifest, camera saves it in default directory without asking me and I want to save it in my own folder created in sd card. I'd searched a lot but couldn't find any useful link. Please help, any help will be much appreciated. Thank you :)

A: You can add this code in  onActivityResult. This will store your image in a folder named "YourFolderName"
String extr = Environment.getExternalStorageDirectory().toString()
            + File.separator + "YourFolderName";
    File myPath = new File(extr, fileName);
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(myPath);
        bitMap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
        MediaStore.Images.Media.insertImage(context.getContentResolver(),
                bitMap, myPath.getPath(), fileName);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

also need to set permission on Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

A:
camera saves it in default directory without asking me and I want to save it in my own folder created in sd card

You can tell the camera where you would like the photo to be stored via EXTRA_OUTPUT, as is shown in the documentation's training module on ACTION_IMAGE_CAPTURE.
There is no requirement for all cameras to store images where you ask it to, though. If the file that you ask for does not exist after the image is taken, you will need to fall back to your existing application logic.

A: You can assign a path to write the image data to specific location like this:
String fileName = "/mnt/sdcard/foldername";
FileOutputStream  fos = new FileOutputStream(fileName);
fos.write(data);


text:
Q: JTree disable highlight effect on certain nodes I have a Jtree and I need to remove the highlight effect on certain node.
So, now I have this for alla nodes

and I would like have this on certain node:

How can I achieve this ?
Thanks

A: Could you not maybe use something like this ? Unsure of practicality and not tested it
tree.addMouseListener (new MouseAdapter (){

        public void mousePressed ( MouseEvent e ){

           // Check for right click
           if (SwingUtilities.isRightMouseButton(e)){

                  int selection[] = tree.getSelectionRows();

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

                     tree.removeSelectionInterval(selection[i], selection[i]);
                  }
           }
}

A: -First: you need to set an object (with your own property) to the node with the following method:
Group aGroup = new Group(); //Obviously use your correct constructor
DefaultMutableTreeNode node = new DefaultMutableTreeNode(yourObject);

Remember to implement toString method in Group class
-Second: Create a new class that extends DefaultTreeCellRenderer and override  getTreeCellRendererComponent like this:
public class MyRenderer extends DefaultTreeCellRenderer {

        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value,
            boolean sel, boolean exp, boolean leaf, int row, boolean hasFocus) {

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;

            if(node.getUserObject().getYourProperty()){
                 setTextNonSelectionColor(Color.BLACK);
                 setBackgroundSelectionColor(Color.BLUE);
                 setTextSelectionColor(Color.WHITE);
                 setBorderSelectionColor(Color.WHITE);
            }
           else{
                 setTextNonSelectionColor(Color.LIGHT_GRAY);
                 setBackgroundSelectionColor(Color.RED);
                 setTextSelectionColor(Color.WHITE);
                 setBorderSelectionColor(Color.WHITE);
           }

            super.getTreeCellRendererComponent(
                tree, value, sel, exp, leaf, row, hasFocus);
            return this;
        }
}

-Third: set your renderer to tree:
yourTree.setCellRenderer(new MyRenderer());


text:
Q: What type of web framework should be used to compare data between databases? I want to query 2 or more Databases every day at a certain time, compare the resulting data and show the inconsistencies in a web page.
Mainly the data will match through PKs and comparison made using some column values.
So I´m reading about web frameworks like Django, Node, Spring, Rails, etc and wondering if that's what I want. If a REST API is what suits this purpose or if it's something completely different.

A: I suggest you compare the data in the database layer and only return the comparison results, so you can show them with any framework.

A: First of all you'll need to focus in the databases that you're going to read, are they SQL/MongoDB/other?
Then think about the website that you're going to build, single page/multiple pages?


text:
Q: How to pass output directory folder in testng from command line TestNG command line argument :
-d  A directory
How do I use this option in eclipse ?
I tried passing it as VM arguments but I get error as unrecognized option

A: See TestNG - Eclipse > Preferences and Properties.
You can the TestNG workbench preferences, the project preferences, or a combination of both (so that you can have defaults and then override them in a project as needed):

9.1 - Workbench Preferences
TestNG workbench preferences:
The preferences here are shared among projects and launch configurations.

*

*Output directory: the path where to store the output including temp files, report files, etc. By default, the path is relative to each project except you check the option Absolute ouput path below.

...
9.2 - Project Properties
Project level properties:
Here are properties on each project level, it will override the same properties if defined in TestNG workbench preferences

*

*Output directory: for example, in the figure above, I prefer to put the output to maven 'target' directory rather than the default one under project root

...


text:
Q: Change function to use PDO This function is called stream and it is called via iOS app when the stream command is called. How can one change it to PDO?
function stream($IdPhoto=0) {

if ($IdPhoto==0) {

    $result = query("SELECT IdPhoto, device_token, /*title,*/ IdUser FROM photos /*p*/ ORDER BY IdPhoto DESC LIMIT 300 ");

} else {

    //do the same as above, but just for the photo with the given id
    $result = query("SELECT p.IdPhoto, p.device_token, /*title,*/ p.IdUser FROM photos p JOIN login l ON (l.IdUser = p.IdUser) WHERE p.IdPhoto='%d'", $IdPhoto) ;

}

if (!$result['error']) {
    // if no error occured, print out the JSON data of the
    // fetched photo data
    print json_encode($result);

} else {
    //there was an error, print out to the iPhone app
    errorJson('Photo stream is broken');
}
}

Update. This is a method someone suggested Change function to PDO
$conn = new PDO('mysql:host=localhost;dbname=dbname', 'root',    'password');
function stream($IdPhoto=0) {
global $conn;

if ($IdPhoto==0) {

// load the last 300 photos
$stmt = $conn->prepare("SELECT IdPhoto, device_token, IdUser FROM photos ORDER BY IdPhoto DESC LIMIT 300 ");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);

} else {

//This is the statement i need to call explicitly via PDO

//do the same as above, but just for the photo with the given id
$stmt = $conn->prepare("SELECT p.IdPhoto, p.device_token, p.IdUser FROM photos p JOIN login l ON (l.IdUser = p.IdUser) WHERE p.IdPhoto= :idphoto ");
$stmt->execute([':idphoto' => $IdPhoto]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);

}

if (!$stmt->errorInfo()[0]) {
// if no error occured, print out the JSON data of the
// fetched photo data
print json_encode($result);
} else {
//there was an error, print out to the iPhone app
errorJson('Photo stream is broken');
}
}

The thing is the stream only works with the first function. Can someone verify the syntax of the second PDO enabled function? Additional details: the iOS app calls the function using AFNetworking.


text:
Q: Kettle - Load Balancing Is there any way to handle load balancing in Pentaho ETL Servers? PDI should be able to handle switching of the servers once the memory increases more than the set target to a new server without having to fail or restart the job. A feature quite similar to Informatica powercenter.
I know we can cluster the data in PDI and also load balancing of server are usually done in the server side. Is it possible to do the same from a PDI point of view?
[Note: Apologies if you think this question is broad.]

A: I found a document in their enterprise edition support saying,

As of now dynamic load balancing and fail over features are not
  supported with PDI server.

But I think you can do jobs & transformation level clustering.
I found several URLs which might help you.
creating-clustered-transformations
partitioning-data-on-clustered-pentaho
clustering-in-kettle
How to build a simple PDI cluster
Create Carte Clusters
And also alternatively you can have dynamic load balancing and fail over feature on the database server side rather than on PDI server.


text:
Q: Mac DHCP Server I often have the need to connect to devices directly through the ethernet port on my MacBook.

*

*When I am connected to a wireless network, I can share my connection to ethernet. However, the second, I loose the wireless connection, I loose connectivity to the devices.

*I can set up a static IP on both the MacBook and the Device, but this is not very easy because I still have to make an initial connection to setup the static IP.
Is there any way to setup a DHCP server on the ethernet port that works even if I am not connected to a network?

A: Based on my answer here: Using Server 5.0.15 to share internet WITHOUT internet sharing I provide a possibility to share internet with PF and dnsmasq (i.e. without Apple's OS X Server):
To get NAT working without using Internet Sharing you have to use a pf rule and create a plist to enable forwarding and load the pf rule. Additionally you have to set up a DNS/DHCP server: dnsmasq.
Below I assume en0: the interface connected to the internet or a router and en1: the interface connected to the LAN. The router has the IP 192.168.0.1 and the netmask 255.255.255.0.
Use ifconfig to get the device names.
Prepare the Mac gateway:

*

*Set up the two interfaces en0 and en1 with fixed IPs and netmasks
Example:
en0: IP: 192.168.0.2 Netmask: 255.255.255.0 Gateway: 192.168.0.1 DNS: 8.8.8.8 and 127.0.0.1 Search Domains: home.org
en1: IP: 192.168.1.1 Netmask: 255.255.255.0

*Disable System Integrity Protection if El Capitan is installed

*Install Xcode Command Line tools/Xcode

*Install, set up and doctor brew

*Install dnsmasq:
brew install dnsmasq

*Set up and configure dnsmasq
cp /usr/local/opt/dnsmasq/dnsmasq.conf.example /usr/local/etc/dnsmasq.conf
sudo mkdir -p /usr/local/var/lib/misc
sudo touch /usr/local/var/lib/misc/dnsmasq.leases

open /usr/local/etc/dnsmasq.conf with an editor and modify at least the following lines:
~ line 144
# 3) Provides the domain part for "expand-hosts"
domain=home.org

~ line 163
# don't need to worry about this.
dhcp-range=192.168.1.50,192.168.1.100,255.255.255.0,12h

~ line 243
# Always give the host with Ethernet address 11:22:33:44:55:66
# the name fred and IP address 192.168.0.60 and lease time 45 minutes
dhcp-host=11:22:33:44:55:66,raspberry,192.168.1.70,12h
**use the proper MAC of your raspberry here**

~ line 536
# This defaults to a sane location, but if you want to change it, use
# the line below.
dhcp-leasefile=/usr/local/var/lib/misc/dnsmasq.leases

You may configure much more - just check the config file and its descriptions.
sudo brew services start dnsmasq
sudo chmod 644 /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist
sudo chown root:wheel /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist

*Create a file named nat-rules in /private/etc/ with the following content
nat on en0 from en1 to any -> (en0)

*Create a shell script named nat-pf.sh enabling forwarding and loading the pf rule. I saved it in /usr/local/bin:
#!/bin/sh

sysctl -w net.inet.ip.forwarding=1
sysctl -w net.inet.ip.fw.enable=1

#disables pfctl
pfctl -d

sleep 1

#flushes all pfctl rules
pfctl -F all

sleep 1

#starts pfctl and loads the rules from the nat-rules file
pfctl -f /private/etc/nat-rules -e

*Create a plist named org.user.natpf.plist with the following content and save it in /Library/LaunchDaemons/ to execute the above shell script at start-up:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Disabled</key>
    <false/>
    <key>KeepAlive</key>
    <dict>
        <key>SuccessfulExit</key>
        <false/>
    </dict>
    <key>Label</key>
    <string>org.user.natpf</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/nat-pf.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>StandardErrorPath</key>
    <string>/tmp/org.user.natpf.stderr</string>
    <key>StandardOutPath</key>
    <string>/tmp/org.user.natpf.stdout</string>
</dict>
</plist>

All three files need a trailing empty line so don't simply copy the above code/lines.

*Modify ownership and file modes:
sudo chown root:wheel /private/etc/nat-rules
sudo chown root:wheel /usr/local/bin/nat-pf.sh
sudo chmod 755 /usr/local/bin/nat-pf.sh
sudo chown root:wheel /Library/LaunchDaemons/org.user.natpf.plist

*Load the launch daemon:
sudo launchctl load /Library/LaunchDaemons/org.user.natpf.plist

*Reboot your gateway Mac. If everything works fine enable SIP again.
The file /tmp/org.user.natpf.stderr contains error messages. You may add a similar key to the file /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist to get potential error messages:
    ...
    <key>StandardErrorPath</key>
    <string>/tmp/homebrew.mxcl.dnsmasq</string>
    <key>StandardOutPath</key>
    <string>/tmp/homebrew.mxcl.dnsmasq</string>
    ...

Prepare your Internet Router (if you have one)

*

*Add a static route: Network: 192.168.1.0 Netmask: 255.255.255.0 Gateway: 192.168.0.2

Prepare your Raspberry

*

*You may have to reboot it.

After setting all things up successfully you should have a reliable LAN with NAT, DHCP and DNS. You may even enter ping raspberry with a proper result.
If you run into problems leave acomment.


text:
Q: Could not find media-1.0.0.jar (androidx.media:media:1.0.0) I wanna use react-native-video in my project, but when I start compiling, I get this error: "Could not find media-1.0.0.jar (androidx.media:media:1.0.0)". My build.gradle file:
buildscript {
    ext {
        buildToolsVersion = "30.0.1"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath('com.android.tools.build:gradle:3.6.2')
        classpath 'com.google.gms:google-services:4.2.0'
        classpath 'com.android.tools.build:gradle:3.4.1'
    }
}

allprojects {
    repositories {
        mavenLocal()
        maven {
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

How can I fix it? "implementation 'androidx.media:media:1.0.0'" doesn't help.

A: add implementation "androidx.media:media:1.2.1" into your app\build.gradle file in dependencies. Mine solved by that I hope it work out for you too.

A: Try to add the implementation "androidx.media:media:1.2.1" in dependencies of
node_modules\react-native-video\android\build.gradle
and:
node_modules\react-native-video\android-exoplayer\build.gradle
This worked for me with version 5.1.1 of this lib


text:
Q: margin not overlap when the outer explicit set height I wonder why the phenomenon will happen?
the inner div set margin-bottom 16px
As far as I know,the outer div contact with the inner div,no padding or border,if the outer div isn't set height css style,the under div will 16px away from the outer div, because the margin is overlap.However,if height css style is set on the outer div,the under div is close to the outer div.
so,can you explain how this phenomenon is caused?

.outer {
  background: yellow;
  height: 100px;
}

.inner {
  height: 100px;
  background: green;
  margin-bottom: 16px;
}

.under {
  background: red;
  height: 10px;
}

A: inner is nested inside outer, and under is directly underneath outer with no space or padding. So regardless of the margin given to inner, there'll be no space between outer and under.
You can do this by simply adding a margin-top to under.
.outer{
    background:yellow;
    height:100px;
}

.inner{
    height:100px;
    background:green;
}

.under{
  background:red;
  height:10px;
  margin-top:16px;
}

A: You cannot add a margin to child element to affect on a parent element. You may add margin-bottom:16px; to Outer class as below
.outer{
background:yellow;
height:100px;
margin-bottom:16px;
}

A: set .outer height:auto;

.outer{
  background:yellow;
  height:auto;
}
.inner{
  height:100px;
  background:green;
  margin-bottom:16px;
}
.under{
  background:red;
  height:10px;
}

A: So first things first, let's address this:

if you remove height css style on the outer div,you will find the under div is move down

This is due to Margin Collapsing:

If there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.
These rules apply even to margins that are zero, so the margin of a first/last child ends up outside its parent (according to the rules above) whether or not the parent's margin is zero.

Your child margin is collapsing with the parent margin, thus the 16px margin acts as part of the parent.

However by specifying a height, you negate margin collapsing.
From the W3 Box Model spec*:

Two margins are adjoining if and only if:

*

*Both belong to vertically-adjacent box edges, i.e. form one of the following pairs:

*

*The bottom margin of a last in-flow child and bottom margin of its parent if the parent has 'auto' computed height

Because the margins do not collapse, the child's margin will simply attempt to expand the height of the outer div (which won't be reflected, because the parent has a strictly set height of 100px).

But wait... what if we broke the collapse some other way? Would we see the height increase by 16px?

Two margins are adjoining if and only if:

*

*no line boxes, no clearance, no padding and no border separate them

Seems easy enough. Let's add a border to break this rule.

.outer {
  background: yellow;
  border-bottom: 1px solid black;
}

.inner {
  height: 100px;
  background: green;
  margin-bottom: 16px;
}

.under {
  background: red;
  height: 10px;
}

Voila! As expected, the margins do not collapse, therefore the child's margin attempts to expand the height of the parent. With no height property on the parent to counter this, the height of the parent grows to 116px.

* This is pointing at an older spec, however this behavior has not changed. In fact, some of the newer spec documents I've found reference/link to this one.


text:
Q: Intuitions behind python API design Usually while writing code, I tend to make mistakes with some function as those functions signatures dont follow my intuition. Or more appropriately my intuition do not follow the design thinking behind these functions. I always wondered if python APIs have some inconsistencies.
For example, in python, we have:
>>> ','.join(['1','2','3'])
'1,2,3'

>>> '1,2,3'.split(',')
['1', '2', '3']

Many times I find myself doing:
['1','2','3'].join(',')

and some times (/ very rarely):
','.split('1,2,3')

Similarly I find this somewhat frustrating:
>>> sorted([1,2,3])
[1, 2, 3]

>>> reversed([1,2,3])
<list_reverseiterator object at 0x000002008932A95

That is, one list function returns list, while other returns an iterator. To save me some time (usually in timed coding competition), I usually end up doing extra list():
>>> list(reversed([1,2,3]))
[3, 2, 1]

>>> list(sorted([1,2,3]))
[1, 2, 3]

I believe there must be some API design standards or technical considerations behind these and am unaware of them. Can someone please share their understanding regarding these, so that it will become part of my intuition and I will do less mistakes. Or is it just the coding practice that will help me make less mistakes? Also, these are just couple of the things that I can recall now, which I usually make mistakes at. Can you share similar API confusions and intuitions behind them that you face (if you face them at all)?

A: You need to understand the reasoning behind each one.

','.join(['1','2','3'])

Any iterable can be joined by a string. Not just lists. If you'd design it like [...].join(','), each possible iterable would need to implement its own join method. You'd need list.join, tuple.join, dict.join etc. Your own classes would all need to implement their own join method.
Thus is makes more sense for join to be a method of str which accepts any arbitrary iterable.

'1,2,3'.split(',')

Conversely, it only makes sense to split a string, so split is a method on str. You may be able to split other types as well, but how that works would differ per type, so it makes sense for each type to define its own split method as makes sense.

sorted([1,2,3])

You must treat the entire list as a whole in order to sort it, all the list contents get shuffled around inside it during the sort operation. So you get a list as return value, as the operation intrinsically produces one anyway.

reversed([1,2,3])

Conversely, you do not need to produce a complete reversed copy of the list in memory in order to reverse it; you can just go through it one item at a time. Often you want to iterate over a collection in the reverse order, not store a reversed collection. So to make it efficient and save memory, it returns an efficient iterator which allows you to do this, instead of forcing you to double your memory usage. If you need to store this as a reversed list, you can do it yourself with list(reversed(...)).


text:
Q: Allow creation of folder on apache2 in Ubuntu Server I'm creating a site which I'm going to host on an Ubuntu Server. I have a user registration form on my site, which creates a user and a folder for that user (if filled out correctly). The form in handled by PHP and I'm running Apache 2 on the server. When I run the code on my laptop the folder is created, but when I run the same code on the server the folder is not there. I guess that it has something to do with permisssion. How can I tell apache that the code should have write permission in a specific folder called "users" located in /var/www/mysite/public/users/ ???

A: Try using chmod command that provides folder permission. Something like
chmod 777 -R foldername

A: If security is not an issue I would suggest:
chmod 775 -R /var/www/
chown -R [your_user]:www-data /var/www/

So both apache2 (www-data) and you can edit folders and files inside /var/www (or /var/www/html if this is your folder).
Notice that this may have issues with git and other tools that capture folder permissions (eg with git you may commit files with 775).


text:
Q: Using --no-rdoc and --no-ri with bundler When using gem install gem_name I can pass --no-rdoc and --no-ri switches to skip generating RDoc/RI documentation for the gem on install.
Is there a similar way to do this with bundle install?

A: Bundler doesn't include rdoc and ri.  There is nothing you need to do.

A: See https://stackoverflow.com/a/7662245/109618 for a better ~/.gemrc:
install: --no-rdoc --no-ri
update:  --no-rdoc --no-ri

A: Make a file ~/.gemrc and put this in it:
gem: --no-rdoc --no-ri
That should make it apply whenever you run the gem command. (Even from bundle install)

A: The up-to-date setting for ~/.gemrc is
gem: --no-document

But as pointed out, this is already bundler's default.


text:
Q: How to fix Floating point exception: 8 in C code I'm trying to write a program that lists all prime numbers in a given parameter. My terminal won't output anything, even though I have a print function at the end of the program.
Could you also let me know if the x and g variables were necessary or could I have just stuck with i.
Here's my code:
#include <stdio.h>

#define MAX_SIZE 1000
int main(){

    int N , i, x, g, a[MAX_SIZE];

    scanf("%d", &N);

    a[0] = 2;

    for (i = 1; i < N - 2; i++)
    {
        a[i] = (a[i-1]) + 1;
    }

    for (x = 0; x < N - 2; x++){
        for (i = 1; i < N - 2; i++){
            if (a[i] % a[x] == 0) {
                for (g = i; g < N - 2; g++){
                    a[g] = a[g+1];
                }
            }
        }
    }

    for (i = 0; i < N - 2; i++){
        printf("%d \n", a[i]);
    }

   return 0;
}

A: You have off-by-one error here:
for (g = i; g < N - 2; g++){
  a[g] = a[g+1];

}

When g = N - 2 - 1, the value a[N - 2] is used, but the element is not initialized and the value is indeterminate.
You should check and fix your algorithm not to read uninitialized element.

Your code looks too complicated for me. Here is an example of my code to print all prime numbers that are N or less:
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int N;
    int* primes;
    int prime_count;
    int i, j;
    if (scanf("%d", &N) != 1) return 1;
    primes = malloc(sizeof(*primes) * N);
    if (primes == NULL) return 2;

    prime_count = 0;
    for (i = 2; i <= N; i++) {
        int is_prime = 1;
        for (j = 0; j < prime_count; j++) {
            if (i % primes[j] == 0) {
                is_prime = 0;
                break;
            }
        }
        if (is_prime) primes[prime_count++] = i;
    }

    for (i = 0; i < prime_count; i++) {
        printf("%d\n", primes[i]);
    }

    free(primes);
    return 0;
}


text:
Q: How to install 10.4 on a partition on a Macbook Pro that was been upgraded to 10.6.8 10.4 was the original OS.  I have software that wouldn't run on 10.6.8 which I didn't realize until after I'd upgraded to 10.6.8.  I made a partition but restart/"option" won't recognize it.  How can I run the software that requires 10.4?
When I try to reboot, it's as if I'd never made the partition, even though it's on the desktop as a second hard drive.

Why can't I access the partition as an option when I reboot?

A: You've made the partition, but it won't be bootable until you install OS X on it. Boot from the install media CD holding C on boot, choosing the new partition as the destination for the install. Once OS X is installed on the partition, it will appear alongside your existing install in Startup Manager when holding alt/option on boot.


text:
Q: Is there a faster way to compute $\left\lfloor{(k + 1)m \over n}\right\rfloor - \left\lfloor {km\over n}\right\rfloor$? I'm looking to compute the integer difference between the $k$th and $(k+1)$th multiples of a fraction, i.e.
$$\left\lfloor{(k + 1)m \over n}\right\rfloor - \left\lfloor {km\over n}\right\rfloor$$
where all variables are positive integers (and they're not predetermined constants).
I'm already speeding this up by doing $km + m$ instead of $(k + 1)m$ so that I can factor out $km$, but unfortunately, this computation requires two integer divisions, and integer division is quite slow.
Is there a faster way to compute the same exact value?
I feel like the simplicity of the problem might admit a simple solution, but for some reason I'm not seeing one.

A: Provided the $\bmod$ operation is faster on whatever platform you'll be running your algorithm (it usually is), then
$$\require{cancel}
\frac{(\cancel{km}+m)-((km+m)\bmod n)-\cancel{km}+(km\bmod n)}{n}
$$
matches your expression with just one integer division. In fact, the numerator must be a multiple of $n$. This is just an application of this formula
$$
\left\lfloor \frac{x}{y} \right\rfloor y = x - (x \bmod y)
$$
which is valid for positive $y$.

A: My method has the following set up:

*

*Calculate $a=m\ mod\ n$

*Check the sign of  $\left(a(k+1) \ mod\ n -a\right)$

*If its $\geq 0$, then $\frac{m-a}{n}$ is the answer

*Otherwise, (if $<0$) its $\frac{m-a}{n}+1$
I hope it suits your needs.

A: Most processors have a command to compute div and mod at the same time (2 for the price of 1).  Check your manual.  For example: https://en.cppreference.com/w/cpp/numeric/math/div
So you can do
(a, b) = div_mod(k*m, n)
b += m
while b >= n {
    b -= n
    a += 1
}
return a

If you know the relation between m and n in advance, then you can do:
z = m/n*n
------------
(a, b) = div_mod(k*m, n)
b += (m - z)
a += (b >= n)
return a

But notice each line has a write-read dependency with the command before it.  So it might actually be faster to just computer the result with 2 modulus since that can be done in parallel.  You just have to test it.
But the best thing would be to know what you are actually doing, for example if you are looping over k, then the div_mod can probably be skipped altogether.


text:
Q: React Native, there is no route defined for index undefined I want to create an Order Page with two tabs place order tab, my orders tab. So I have created one Order.js file and another OrderContent.js file.
Order.js
/* @flow */
import React from 'react'

import {
  View,
  StatusBar,
} from 'react-native'

import SplashScreen from 'react-native-splash-screen'

import HomeHeader from '../Components/HomeHeader'
import OrderContent from './OrderContent'

export default class OrdersScreen extends React.Component {
  static navigationOptions = {
    drawer: () => ({
      label: 'Orders',
    }),
  }
  static propTypes = {
    navigation: React.PropTypes.object.isRequired,
  }

  componentDidMount() {
    SplashScreen.hide()
  }
  render() {
    return (
      <View style={{flex: 1, backgroundColor: '#fff'}}>
        <StatusBar
          barStyle="light-content"
          backgroundColor={'#202930'} />
        <HomeHeader
          title="Order Page"
          navigation={this.props.navigation} />
        <OrderContent navigation={this.props.navigation}
           />
      </View>
    )
  }
}

Ordercontent.js
const CustomTabView = ({router, navigation}) => {
  const { routes, index } = navigation.state
  const ActiveScreen = router.getComponentForState(navigation.state)

  return (
    <View style={styles.container}>
      <CustomTabBar navigation={navigation} />
      <ActiveScreen
        navigation={addNavigationHelpers({
          ...navigation,
          state: routes[index],
        })}/>
    </View>
  )
}
CustomTabView.propTypes = {
  router: React.PropTypes.object.isRequired,
  navigation: React.PropTypes.object.isRequired,
  // team: React.PropTypes.func.isRequired,
}

const CustomTabRouter = TabRouter({
    PlaceOrder: {
      screen: PlaceOrderScreen,
      path: '/place-order',
    },
    MyOrders: {
      screen: MyOrderScreen,
      path: '/my-orders',
    },
  },
  {
    // Change this to start on a different tab
    initialRouteName: 'PlaceOrder',
  }
)

const OrderContent = createNavigationContainer(createNavigator(CustomTabRouter)(CustomTabView))

export default OrderContent

When I tried to run the app, it shows like

there is no route defined for the index undefined. Check that you passed in a navigation state with a valid tab index.

I know that the problem exists in <OrderContent navigation={this.props.navigation} /> part itself but don't know how to overcome.

A: react native by default goes to a page called index.js
Have you created a file in this name ?
it should contain something like this
<code>

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);
</code>

Instead of App you can place Order or OrderContent instead .
Basically you choose your " landing tab " this way .


text:
Q: Find a function from graph I have a greater "trouble". I wanna learn more about "graphs". On this webpage I found some nice graphs in heart shape. And they where written as functions. Another graph I found was "the batman (equation) graph".
I would really like to know how to create some functions on my own. Is their any manual? I think it is important - in physics and chemistry we have to look close at graphs and figure out which function we can fit them to. Often we can find some evidence in text - but once we got a random plot in physics, where the instructor just told us which function we should fit it to.
I would like to know such an important thing on my own. Could you maybe write a little - so I can understand how to make my "own" functions by looking at a graph?
Kind regards!

A: All graphs may not be represented by functions but every function has a graph.
You can look into the book Calculus by Finney.


text:
Q: Nav showing up in second line I'm trying to build a responsive nav tabs using bootstrap and jquery, however my tab seems to keep breaking in second line.
I want to nicely use full width, and squeeze tabs if there are many.

    {% block tab_buttons %}
    {% endblock %}

Hosts

  {% for tab in event.benchmarks.all %}

{{ tab.name }}

  {% endfor %}

I want to use the full screen width to use all the space, instead of forming tabs in new line.
It looks like this as of now

A: I would use flexbox here:

 #event-detail-nav {
  display: flex;
  text-overflow: ellipsis;
  list-style-type: none;
}
#event-detail-nav>li {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

Test1

Test2

Test3


text:
Q: Composite Predicate of function pointers in C I am attempting to build a composite predicate using function pointers.
I dont know if this is possible.
My predicates are of the form: int (*predicate)(int)
Those work fine.
I want to make a function that takes 2 params of type int (*predicate)(int) and returns a function of type  int (*predicate)(int), such that the new function returns the value of a(x) && b(x).
I want to make something that works like this:
int ( *composite(int (*a)(int), int (*b)(int)) )(int x) {
    return a(x) && b(x);
}

or:
int ( *negate(int (*a)(int)) )(int x) {
    return !a(x);
}

I understand that my attempts are returning a value, not a function, but if I try to make another function for them to return, I end up with the exact same problem.
If I do:
int composed(int (*a)(int), int (*b)(int), int x ) {
    return a(x) && b(x);
}

It compiles, but then it is no longer of type int (*predicate)(int) so I cannot use it the way that I want to.
How should I go about doing this?
Complete sample code attached for reference:
#include <stdio.h>

unsigned int count(const int* xs, unsigned int len, int (*predicate)(int)) {
  int c = 0;
  for(int i = 0; i < len; i++) {
    if(predicate(xs[i])) c++;
  }
  return c;
}

int isEven(int x) { return x % 2 == 0; }
int isOdd(int x) { return !isEven(x); }
int isPos(int x) { return x > 0; }
int isNeg(int x) { return x < 0; }

// int composed(int (*a)(int), int (*b)(int), int x ) {
//     return a(x) && b(x);
// }
//
// int ( *composite(int (*a)(int), int (*b)(int)) )(int x) {
//     return &composed(a,b)(x)
// }

int main() {
  int xs[] = {-5,-4,-3,-2,-1,0,1,2,3,4,5};
  const int len = 11;

  printf("Even: %d\n", count(xs, len, &isEven));
  printf(" Odd: %d\n", count(xs, len, &isOdd));
  printf(" Pos: %d\n", count(xs, len, &isPos));
  printf(" Neg: %d\n", count(xs, len, &isNeg));

  // int (*compositePtr)(int) = composite(&isNeg, &isOdd);
  // printf("Odd & Neg: %d", count(xs, len, compositePtr));

}

A: I once wrote the following code for demonstration purposes:
#include <stdio.h>

/* one int for the implicit parameter n,
 * one int as return type,
 * one int as parameter.
 */
typedef struct int_int_int_closure {
    int (*call)(const struct int_int_int_closure *, int);
    int n;
} int_int_int_closure;

static int
adderfn(const int_int_int_closure *cl, int n) {
    return cl->n + n;
}

int
main(void)
{
    int_int_int_closure a3;

    a3.call = adderfn;
    a3.n = 3;

    printf("%d\n", a3.call(&a3, 2));
    return 0;
}

You could generalize this code so that the closure consists of a function pointer, a pointer to its data and the size of the data.

A: You can't dynamically create closures or functions in C, so you need to do something else.  The easiest is to use an extra level of indirection.  If you change your predicates to
int (**predicate)(void *, int)

which you call as (**predicate)(predicate, x), then you can create new dynamic predicates quite easily:
typedef int (*predicate_t)(void *, int);

struct compose_fn_data {
    predicate_t  fn, *a, *b;
};

int and_fn(void *data_, int x) {
    struct compose_fn_data *data = data_;
    return (**data->a)(data->a, x) && (**data->b)(data->b, x);
}

int or_fn(void *data_, int x) {
    struct compose_fn_data *data = data_;
    return (**data->a)(data->a, x) || (**data->b)(data->b, x);
}

predicate_t *compose(predicate_t fn, predicate_t *a, predicate_t *b) {
    struct compose_fn_data *rv = malloc(sizeof *rv);
    rv->fn = fn;
    rv->a = a;
    rv->b = b;
    return &rv->fn;
}

predicate_t *and(predicate_t *a, predicate_t *b) { return compose(and_fn, a, b); }
predicate_t *or(predicate_t *a, predicate_t *b) { return compose(or_fn, a, b); }

On minor annoyance with this is that for simple functions, you need to define an additional one-word data structure to hold the function pointer, just to indirect through it.  You usually do this with a global next to the function definition:
int isEven_fn(void *data, int x) { (void)data; return x % 2 == 0; }
predicate_t isEven = isEven_fn;
int isOdd_fn(void *data, int x) { return !isEven_fn(data, x); }
predicate_t isOdd = isOdd_fn;
int isPos_fn(void *data, int x) { (void)data; return x > 0; }
predicate_t isPos = isPos_fn;
int isNeg_fn(void *data, int x) { (void)data; return x < 0; }
predicate_t isNeg = isNeg_fn;

Now you can do things like:
printf("Even: %d\n", count(xs, len, &isEven));
printf("Odd & Neg: %d", count(xs, len, and(&isNeg, &isOdd)));
printf("%d", count(xs, len, or(and(&isNeg, &isOdd), &isEven)));

though the latter do leak memory.

A: When the syntax for passing function pointers to/from functions was invented, I suspect that lots of unmentionable substances were smoked.
Given a function pointer int (*)(int), a function returning such a function pointer is declared as:
int (*func(void))(int);
1          2     3

Where 1 = return type of the function pointer, 2 is the parameter list of the function and 3 = the parameter list of the function pointer.
Now if you want to make a function returning one such pointer, and take two such pointers as parameters, it is trivial:
int (*func(int(*a)(int), int(*b)(int)))(int)

No, it isn't trivial... this is madness! If you can actually write and understand code like this, then it means you have simply worked far too much with C for your own good.
What you absolutely should do instead, is to use a typedef.
typedef int (predicate_t)(int);
...

predicate_t* func (predicate_t* a, predicate_t* b);

However, I suspect that you actually just need a function which returns an integer and not a function pointer.

A: Here's a block-based implementation of your effort to create compositions of predicate functions:
//
//  ViewController.m
//  PredicateFunctionsExercise
//
//  Created by James Alan Bush on 3/12/22.
//

#import "ViewController.h"
@import simd;

typedef int (^boolean_expression)(void);
typedef int (^guarded_boolean_expression)(void);
typedef int (^ const (*guarded_boolean_expression_t))(void);
typedef int (^(^conditional_boolean_expression)(guarded_boolean_expression_t))(void);
typedef int (^ const (^ const (*conditional_boolean_expression_t))(guarded_boolean_expression_t))(void);
typedef int (^predicate)(void);
typedef int (^ const (*predicate_t))(void);

static int c = 0;
static int flag = (1 << 0);
guarded_boolean_expression flag_conditional = ^ int { return flag; };

conditional_boolean_expression isEven = ^ (guarded_boolean_expression_t _Nullable x) { return ^ int { int result = (*x)() % 2 == 0; printf("%d %s (%d)\t", flag, (result) ? "is even"     : "is not even",     result); return result; }; };
conditional_boolean_expression isOdd  = ^ (guarded_boolean_expression_t _Nullable x) { return ^ int { int result = (*x)() % 2 == 1; printf("%d %s (%d)\t", flag, (result) ? "is odd"      : "is not odd",      result); return result; }; };
conditional_boolean_expression isPos  = ^ (guarded_boolean_expression_t _Nullable x) { return ^ int { int result = (*x)() > 0;      printf("%d %s (%d)\t", flag, (result) ? "is positive" : "is not positive", result); return result; }; };
conditional_boolean_expression isNeg  = ^ (guarded_boolean_expression_t _Nullable x) { return ^ int { int result = (*x)() < 0;      printf("%d %s (%d)\t", flag, (result) ? "is negative" : "is not negative", result); return result; }; };

static void (^evaluate_predicate)(predicate_t) = ^ (predicate_t p) {
    printf("\nresult = %d (%d invocations)\n", (*p)(), c);
};

static int (^(^(^g)(__strong conditional_boolean_expression, __strong conditional_boolean_expression, guarded_boolean_expression_t))(int (^__strong)(conditional_boolean_expression_t, conditional_boolean_expression_t, guarded_boolean_expression_t)))(void) =
^ (conditional_boolean_expression boolean_conditional_a, conditional_boolean_expression boolean_conditional_b, guarded_boolean_expression_t guarded_conditional) {
    return ^ (int (^bitwise_operation)(conditional_boolean_expression_t, conditional_boolean_expression_t, guarded_boolean_expression_t)) {
        return ^ (int boolean_expression) {
            return ^ int {
                ++c;
                return boolean_expression;
            };
        }(bitwise_operation((conditional_boolean_expression_t)&boolean_conditional_a, (conditional_boolean_expression_t)&boolean_conditional_b, guarded_conditional));
    };
};

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // gbe_a is set to a precalculated and stored result
    // Invoking gbe_a() merely returns the results without recalculating it -- perfect for use inside the domain of discourse
    guarded_boolean_expression gbe_a = g(isEven, isOdd, &flag_conditional)(^ int (conditional_boolean_expression_t boolean_conditional_a, conditional_boolean_expression_t boolean_conditional_b, guarded_boolean_expression_t guarded_conditional) {
        return ((*boolean_conditional_a)(guarded_conditional)() & (*guarded_conditional)()) && (*boolean_conditional_b)(guarded_conditional);
    });

    guarded_boolean_expression gbe_b = g(isPos, isNeg, &flag_conditional)(^ int (conditional_boolean_expression_t boolean_conditional_a, conditional_boolean_expression_t boolean_conditional_b, guarded_boolean_expression_t guarded_conditional) {
        return ((*boolean_conditional_a)(guarded_conditional)() & (*guarded_conditional)()) && (*boolean_conditional_b)(guarded_conditional);
    });

    // Returning a variety of bitwise operations with randomly chosen operands and operators
    // to demonstrate that simd vectors can be used combining multiple bitwise operations into a single operation
    simd_uint2 bit_vector = simd_make_uint2((gbe_a() << 0), (gbe_b() << 0));
    simd_uint2 bit_mask   = simd_make_uint2(flag, flag);
    simd_uint2 results    = simd_make_uint2(bit_vector & bit_mask);
    printf("\n%d & %d == %d\t\t\t", bit_vector[0], bit_mask[0], results[0]);
    printf("%d & %d == %d\n", bit_vector[1], bit_mask[1], results[1]);
    results    = simd_make_uint2(bit_vector | bit_mask);
    printf("%d | %d == %d\t\t\t", bit_vector[0], bit_mask[0], results[0]);
    printf("%d | %d == %d\n", bit_vector[1], bit_mask[1], results[1]);
    results    = simd_make_uint2(bit_vector ^ bit_mask);
    printf("%d ^ %d == %d\t\t\t", bit_vector[0], bit_mask[0], results[0]);
    printf("%d ^ %d == %d\n", bit_vector[1], bit_mask[1], results[1]);
}

@end

The console output:


text:
Q: are arrays faster than arraylist? My intuition says arrays are faster than arraylist because arraylists are implemented using arrays that resize as it fills up/loses elements.
I just wanted to confirm if this is true or not, implying there's never a reason to use an arraylist if you know the number of elements you want to hold.

A: ArrayList gives you many features a raw array does not have. If you know the number of elements you can create an ArrayList of that size.
new ArrayList<String>(100);

If you are worrying about the difference in speed between an ArrayList and an array, you are worrying about the wrong thing. It is highly unlikely to be the bottleneck in your code. If it is, there is almost certainly a better answer than changing to an array.
Don't succumb to premature optimization. It'll wreak havoc on your code. Most things don't matter, only a few things do. You can only find those few things by profiling your code. Trying to make every part fast is a very ineffective way of making the whole fast. Keeping a clean, simple design is much more effective. That will give you the necessary seams for introducing optimizations in the one or two places they're actually needed.

A: As other people have said already, use ArrayList unless performance benchmarks say it is a bottle beck.
Yes there is a performance difference due to accessor overhead, which will not be significant in general.  An exception to that general rule is if you are storing primitive types inside your ArrayList.  That will encore a significant performance hit as it converts the objects to/from Object and primitive types.
// easier to work with but slow
ArrayList<Double> slowList;

// faster primitive data array
double[] fasterList;

A: Any performance difference will be negligible, especially if you initialize your arraylist with an initialCapacity. Write your code in whatever way makes it the most readable and maintainable, and try not to optimize stuff like this unless you've determined through testing that you are getting a significant performance hit from it.
Potential reasons to use ArrayList:

*

*useful methods (contains, etc.)

*implements Iterable, Collection, and List, and can therefore be used in a lot of API calls that are interface-based.

*even though you currently "know" that your collection's size can never change, life throws unexpected requirements at us. Why lock yourself into a pattern when there's no discernible advantage to be gained?

A: ArrayList can't be faster at simple get/set, but the difference would be very small and likely not worth worrying about in almost any realistic scenario.
The List API has some methods you may need, even in the case you already know the size will be fixed. Think contains() for example. You'd also have to use ArrayList in a case where you wanted an Iterator or an API needed a List -- again even if you know the list is of fixed size.

A: Yes, arrays are much faster. You can see a noticeable speed-up if you running numerical algorithms.
However for normal application purposes, you don't have to worry about it. This is because most of the runtime is spent doing other things anyways.

A: You shouldn't optimize your code too early, instead use the data structure which fits in your code best.
as you said a rule of thumb could be:

*

*i don't know the number of elements or it is changing a lot => List (don't fixate on implementations)

*the number of elements is fixed an known beforehand => array

A: if you know the size of the array, ensuring that it wont expand or shrink. than use arrays. if you dont know, array list are preferable and stable. for performance, is this your only concern left ? move along..

A: Arrays much faster than array list. The difference can be hundreds of percents and  probably come from the JVM optimization.  If you declare your array variables as volatile than you will get similar performance.


text:
Q: SSAS Cube showing irrelevant ID I write a calculation MDX formula to show ID and the sum of any one ID. But its showing Sum of one ID and showing like bellow. Where I should show only 1   10.
After sum in the DB there are:
1  10,
2  30,
3  29,
4  97

I should show only 1  10
But its showing:
1  10,
2  10,
3  10,
4  10

I mean how many ID I have, its showing all of them. The ID is in Dimension.
anyone please help?

A: You writed calculation MDX formula with set of Dimension ID where this ID is equal 10. So MDX always show same value if yours "filtered" Dimension is inserted. If you try to insert Dimension which is not in mdx formula (must be connected to measure group) you will see what mdx calculation value is divided.


text:
Q: How to extract non grouped column data? I have a table A with following data:
A:
colA colB
 a     x
 b     x
 c     y
 d     y
 e     z
 f     z

I want the output as:
colA colA_1
 a     b
 c     d
 e     f

I.e. I want to group the data based on colB and fetch the values from colA. I know that the same value will appear exactly twice in colB.
What I am trying to do is:
SELECT a1.colA, a2.colA
FROM A a1
JOIN A a2
ON a1.colA != a2.colA and a1.colB=a2.colB;

But this gives the output as:
colA colA_1
 a     b
 b     a
 c     d
 d     c
 e     f
 f     e

How can I fix this to get the desired output?

A: No need to join, simply do a GROUP BY:
SELECT min(colA), max(colA)
FROM A
group by colB


text:
Q: How to set HTML Audio or Video Thumbnail and Title on chrome media control menu and in windows media control dialog How to make thumbnail and title of audio or video in html visible in chrome media control menu and in windows media control menu (dialog appears on volume up or down key pressed)
Chrome Menu

Windows Media control Menu

Possible Thoughts:-

*

*may be some meta attribute to acheive this?

*or playing with https://schema.org/MusicRecording?

A: After digging some time, found a solution in developers.google.com web updates.
Result:-

To Acheive this:-
Refer:- Media Session


text:
Q: Wild Cards File Rename Script I am trying to write a script which renames files based on a file extension.
The script should prompt the user for their desired file extension. Following that it should ask the user what prefix to prepend the file name(s). The default prefix should be today's date in the format of YYYY-DD-MM.
So if the user presses enter it should just use today's date as default. Otherwise it will use whatever the user has input for the prefix. After that I want it to display the original file name and the new name of the file on the same line, then finally the file should be renamed:
This is how i'd like the output to appear
Example output 1:
Please enter a file extension: gif
Please enter a file prefix: (Press ENTER for 20180219). helpme
Renaming goose.gif to helpmegoose.gif.

Example output 2:
Please enter a file extension: gif
Please enter a file prefix: (Press ENTER for 20180219).
Renaming goose.gif to 20180219goose.gif.

This is the code I have thus far:
#!/bin/bash

cd /c/Users/johndoe/unix
curr=$(date +"%Y-%m-%d")

echo -n "Please enter file extension: " ; read extension
echo -n "Please enter a file prefix(Press ENTER for ${curr}) " ; read prefix

if [ -e $extension ]
then

for FILES in /c/Users/johndoe/unix/*.$extension
do
    echo -n "Renaming ${FILES} to " ; mv ${FILES} $prefix${FILES};
done
else
    echo -n "Renaming ${FILES} to " ; mv ${FILES} $curr${FILES};
fi

A: #!/usr/bin/env bash

cd /c/Users/johndoe/unix || exit 1
curr=$(date +"%Y-%m-%d")

IFS= read -rp "Enter file extension: " ext
IFS= read -rp "Enter prefix (ENTER for $curr): " prefix

shopt -s nullglob

for file in *".$ext"; do
    printf 'Renaming %s to %s.\n' "$file" "${prefix:-$curr}$file"
    mv -- "$file" "${prefix:-$curr}$file"
done


text:
Q: How can I determine what fonts are used by an mxd? A client has sent me an mxd and a file gdb.
When I look at the symbols, they don't look good.  I think they need to send me some fonts.  Is there some way I can use arcmap to determine the name of the font file I need so that I can request it from them?

A: A quick look at a few ArcGIS 10 mxds suggests that grepping
[A-Za-z0-9 ]+ÿÿ×â

will turn up (loads of) font names.  I used Windows Grep for this test.  I can't guarantee it will turn up all the font names, but the approach looks promising.
Here's a screen shot of the output.  Note how two font names were picked up ("Batang" at the end of line 81), not just the default "Arial" that litters the file.


text:
Q: Catch KeyError in Python If I run the code:
connection = manager.connect("I2Cx")

The program crashes and reports a KeyError because I2Cx doesn't exist (it should be I2C).
But if I do:
try:
    connection = manager.connect("I2Cx")
except Exception, e:
    print e

It doesn't print anything for e. I would like to be able to print the exception that was thrown. If I try the same thing with a divide by zero operation it is caught and reported properly in both cases. What am I missing here?

A: If it's raising a KeyError with no message, then it won't print anything. If you do...
try:
    connection = manager.connect("I2Cx")
except Exception as e:
    print repr(e)

...you'll at least get the exception class name.
A better alternative is to use multiple except blocks, and only 'catch' the exceptions you intend to handle...
try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print 'I got a KeyError - reason "%s"' % str(e)
except IndexError as e:
    print 'I got an IndexError - reason "%s"' % str(e)

There are valid reasons to catch all exceptions, but you should almost always re-raise them if you do...
try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print 'I got a KeyError - reason "%s"' % str(e)
except:
    print 'I got another exception, but I should re-raise'
    raise

...because you probably don't want to handle KeyboardInterrupt if the user presses CTRL-C, nor SystemExit if the try-block calls sys.exit().

A: You should consult the documentation of whatever library is throwing the exception, to see how to get an error message out of its exceptions.
Alternatively, a good way to debug this kind of thing is to say:
except Exception, e:
    print dir(e)

to see what properties e has - you'll probably find it has a message property or similar.

A: I am using Python 3.6 and using a comma between Exception and e does not work. I need to use the following syntax (just for anyone wondering)
try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print(e.message)

A: You can also try to use get(), for example:
connection = manager.connect.get("I2Cx")

which won't raise a KeyError in case the key doesn't exist.
You may also use second argument to specify the default value, if the key is not present.

A: If you don't want to handle error just NoneType and use get()
e.g.:
manager.connect.get("")

A: I dont think python has a catch :)
try:
    connection = manager.connect("I2Cx")
except Exception, e:
    print e

A: Try print(e.message) this should be able to print your exception.
try:
    connection = manager.connect("I2Cx")
except Exception, e:
    print(e.message)


text:
Q: Webpack throws error with Emscripten: Can't resolve 'fs' I'm encountering errors in importing a javascript file into a vue.js component:
This is the content of /components sub-folder:
/startingV/src/components$ ls -lah
total 132K
drwxr-xr-x 2 marco marco 4,0K dic 26 11:22 .
drwxr-xr-x 5 marco marco 4,0K dic 26 09:32 ..
-rw-r--r-- 1 marco marco  441 nov  2  2016 Counter.vue
-rw-r--r-- 1 marco marco  441 dic 21 15:13 FormValidation.vue
-rw-r--r-- 1 marco marco 100K dic 26 10:38 js_plumbing.js
-rw-r--r-- 1 marco marco 9,3K dic 26 10:38 js_plumbing.wasm
-rw-r--r-- 1 marco marco  473 dic 26 11:14 Result.vue

When compiling:
Failed to compile.

./src/components/js_plumbing.js
Module not found: Error: Can't resolve 'fs' in '/home/marco/cpp/WebAssemblyinAction
/Appendix_B/B.1_ccall/startingV/src/components'

this is the Result.vue file:
template>
    <p button @click="callAdd">Add!</p>
</template>

<script>
    import * as js_plumbing from './js_plumbing'
    export default {
      data () {
        return {
          result: null
        }
      },
      methods: {
        callAdd() {
          const result = Module.ccall('js_plumbing.Add',
              'number',
              ['number', 'number'],
              [1, 2]);
          console.log('Result: ${result}');
        }
      }
    }
</script>

The js_plumbing.js and the js_plumbing.wasm files have been generated through this command :
emcc add.c -o js_plumbing.js -s EXTRA_EXPORTED_RUNTIME_METHODS=['ccall','cwrap']

where add.c is:
#include <stdlib.h>
#include <emscripten.h>

// If this is an Emscripten (WebAssembly) build then...
#ifdef __EMSCRIPTEN__
  #include <emscripten.h>
#endif

#ifdef __cplusplus
extern "C" { // So that the C++ compiler does not rename our function names
#endif

EMSCRIPTEN_KEEPALIVE
int Add(int value1, int value2)
{
  return (value1 + value2);
}

#ifdef __cplusplus
}
#endif

This is the link I took some info about how to generate the .js and .wasm files:
https://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html#interacting-with-code-ccall-cwrap
Complete error message in the command line when doing npn run dev :
(base) marco@marco-U36SG:~/cpp/WebAssemblyinAction/Appendix_B
/B.1_ccall/startingV$ npm run dev

> myproject@1.0.0 dev /home/marco/cpp/WebAssemblyinAction/Appendix_B
/B.1_ccall/startingV
> cross-env NODE_ENV=development webpack-dev-server --open --hot

✖ 「wdm」: Hash: 12bee4de7abfde1cbc5d
Version: webpack 4.41.3
Time: 6707ms
Built at: 12/26/2019 12:37:07 PM
   Asset      Size  Chunks                    Chunk Names
build.js  2.18 MiB    main  [emitted]  [big]  main
Entrypoint main [big] = build.js
[0] multi (webpack)-dev-server/client?http://localhost:8080
(webpack)/hot/dev-server.js ./src/main.js 52 bytes {main} [built]
[./node_modules/strip-ansi/index.js] 161 bytes {main} [built]
[./node_modules/vue/dist/vue.esm.js] 319 KiB {main} [built]
[./node_modules/webpack-dev-server/client/index.js?http:
//localhost:8080] (webpack)-dev-server/client?http://localhost:8080
4.29 KiB {main} [built]
[./node_modules/webpack-dev-server/client/overlay.js] (webpack)-dev-
server/client/overlay.js 3.51 KiB {main} [built]
[./node_modules/webpack-dev-server/client/socket.js] (webpack)-dev-
server/client/socket.js 1.53 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/createSocketUrl.js]
(webpack)-dev-server/client/utils/createSocketUrl.js 2.89 KiB {main}
[built]
[./node_modules/webpack-dev-server/client/utils/log.js] (webpack)-dev-
server/client/utils/log.js 964 bytes {main} [built]
[./node_modules/webpack-dev-server/client/utils/reloadApp.js]
(webpack)-dev-server/client/utils/reloadApp.js 1.59 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/sendMessage.js]
(webpack)-dev-server/client/utils/sendMessage.js 402 bytes {main}
[built]
[./node_modules/webpack/hot sync ^\.\/log$] (webpack)/hot sync
nonrecursive ^\.\/log$ 170 bytes {main} [built]
[./node_modules/webpack/hot/dev-server.js] (webpack)/hot/dev-server.js
 1.59 KiB {main} [built]
[./node_modules/webpack/hot/emitter.js] (webpack)/hot/emitter.js 75
bytes {main} [built]
[./node_modules/webpack/hot/log-apply-result.js] (webpack)/hot/log-
apply-result.js 1.27 KiB {main} [built]
[./src/main.js] 134 bytes {main} [built]
    + 34 hidden modules

ERROR in ./src/components/js_plumbing.js
Module not found: Error: Can't resolve 'fs' in '/home/marco
/cpp/WebAssemblyinAction/Appendix_B/B.1_ccall/startingV
/src/components'
 @ ./src/components/js_plumbing.js 88:26-39
 @ ./node_modules/babel-loader/lib!./node_modules/vue-loader
/lib/selector.js?type=script&index=0!./src/components/Result.vue
 @ ./src/components/Result.vue
 @ ./node_modules/babel-loader/lib!./node_modules/vue-loader
/lib/selector.js?type=script&index=0!./src/App.vue
 @ ./src/App.vue
 @ ./src/main.js

How to solve it?
Marco

A: TLDR;
There are two solutions:

*

*Add -s ENVIRONMENT='web' in your emcc command, so try emcc add.c -o js_plumbing.js -s EXTRA_EXPORTED_RUNTIME_METHODS=['ccall','cwrap'] -s ENVIRONMENT='web'
or

*Add "node": { "fs": "empty" } field in your webpack.config.js. I don't know how to do it in zero-config way though.

Why
Emscripten's emcc command produces both .js and .wasm files. The .js file is not only a wrapper of the .wasm but also provides a C/C++ runtime for the web, and more importantly in the question, a generic loader for the .wasm file.
The .js file's loader is very comprehensive that covers node, web, web worker, and D8 JS shell by default. This often make problems with bundlers such as Webpack because the bundlers try to resolve all modules in the source code, including require('fs') which is used for loading .wasm file in the nodejs environment, and the bundler produces error if any module is not available for the web environment.
One way to avoid the problem is that to use ENVIRONMENT flag in emcc command. This will remove some problematic codes such as require('fs').
Another way is to let Webpack ignore fs module by adding "node": { "fs": "empty" } in the webpack configuration.


text:
Q: Error when populating FutureBuilder with data from sqflite I have an SQLite database with movies. I'm following this example.
I want to show all the movies in a ListView.
I try to populate the ListView using a FutureBuilder like in the example, but where I assign the future of the FutureBuilder, it throws the following exception:
type 'Future<dynamic>' is not a subtype of type 'Future<List<Movie>>'

I find this strange as my function that I use in the FutureBuilder returns a List<Movie> and not dynamic.
What could be causing this error?
Database:
class MovieDatabase {
  MovieDatabase._();
  static final MovieDatabase db = MovieDatabase._();
  static Database _database;

  Future<Database> get database async {
    if (_database != null) return _database;
    _database = await initDB();
    return _database;
  }

  initDB() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "MovieDB.db");
    return await openDatabase(path, version: 1, onOpen: (db) {},
        onCreate: (Database db, int version) async {
      await db.execute("CREATE TABLE Movie ("
          ...
          ")");
    });
  }

  getAllMovies() async {
    final db = await database;
    var res = await db.query("Movie");
    List<Movie> list =
        res.isNotEmpty ? res.map((m) => Movie.fromSqLite(m)).toList() : [];
    return list;
  }
  ...
}

Widget:
@override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: <Widget>[
          FutureBuilder<List<Movie>>(
            future: MovieDatabase.db.getAllMovies(), // This line causes the error
            initialData: List(),
            builder:
                (BuildContext context, AsyncSnapshot<List<Movie>> snapshot) {
              return snapshot.hasData
                  ? ListView.builder(
                      itemCount: snapshot.data.length,
                      itemBuilder: (BuildContext context, int position) {
                        Movie movie = snapshot.data[position];
                        return Card(
                          child: ListTile(
                            title: Text(movie.title),
                          ),
                        );
                      },
                    )
                  : Center(
                      child: CircularProgressIndicator(),
                    );
            },
          ),
        ],
      ),
    );
  }

A: The method getAllMovies() has no specific return type, so, by default, it will return:

*

*void: if there is no return statement.

*dynamic: if there is a return statement. Int if it returns int, String if it returns String...

In your case it is returning a list but dart does not know that until the method is called. The widget FutureBuilder requires a function that needs to explicitly return a List of Movies, not a dynamic.
Just add a List of Movies as a return type to getAllMovies() method and you should be good to go:
 List<Movies> getAllMovies() async {
    final db = await database;
    var res = await db.query("Movie");
    List<Movie> list =
        res.isNotEmpty ? res.map((m) => Movie.fromSqLite(m)).toList() : [];
    return list;
  }


text:
Q: How to rewrite this limit? This is probably an easy Analysis exercise:
Let $A \subset \mathbb{R}^d$ be a bounded domain with smooth boundary (like a sphere) and $f:A \rightarrow \mathbb{R}$.
Assume now that for all $x_0 \in \partial A$ we have $$\lim_{A \ni x \rightarrow x_0} f(x) =0.$$ That means, $f$ is continuous on the boundary of $A$ and constant $0$.
Let $x_r \in A$ be arbitrary with $dist(x_r, \partial A)<r$, that means the (euclidean) distance between $x_r$ and the boundary of $A$ is less than $r$.
How can I now conclude formally correct that
$$\lim_{r \rightarrow 0} f(x_r) =0.$$
It would be trivial if $x_r$ converged to a point but this is not true in general. So I don't have a point $x_0 \in \partial A$ which I can use to exploit the continuity at $x_0$.
What can I do else?


text: Q: rating star images are not deleted in Wordpress rating widget plugin Am using rating widget plugin for star ratings of my posts in WordPress,When i delete the post from WP-admin,the title of the post got deleted but still the star ratings showing,what i have to do to delete the ratings star images?