Transitive relation.

Question: I have read transitive relation, if $a\mathrel R b$ and $b\mathrel Rc$ then $a\mathrel Rc$.
But suppose we have a set of first cousins.
$$\mathrel R: \{(a,b),(a,c)\}$$
Where $a$, $b$ and $c$ are first cousins. Can anyone please help if the set $\mathrel R$ transitive?
Comment: With elements $a,b,c$ as described in the image above and the relation defined as one person is "related" to another iff they are first cousins, then your relation should have been $R=\{(a,b),(a,c)\color{red}{,(b,a),(c,a)}\}$ which is not a transitive relationship since for instance $(a,b)$ and $(b,a)$ are both pairs in the relation however $(a,a)$ is not a pair in the relation.  Similarly $(b,a)$ and $(a,c)$ are both pairs in the relation however $(b,c)$ is not.
Comment: Being first cousins is usually a symmetric relation as well. So if $(a, b)$ is there, then $(b, a)$ should too.
Comment: The relation you wrote, $R=\{(a,b),(a,c)\}$ is indeed a transitive relation.  This however has very little to do with an example of "*a set of first cousins.*"  The example of "*first cousins*" where two people are said to be "related" if they are first cousins will in general not be transitive so long as the number of people in the universal set being considered is large enough and you have at least some people who are cousins included since if $a$ is a first cousin of $b$ then you will also have $b$ is a first cousin of $a$ however $a$ is not said to be a first cousin of him/herself.
Comment: Now... if $a,b,c$ all happened to be first cousins of one another and your relation $R$ just happened to be defined on these three cousins but the pairs appearing in the relation have nothing to do with that... then all of this talk about cousins was completely meaningless and should never have been mentioned.
Comment: I have attached an image to clarify the relationship between a,b and c
Comment: Recall... although you might see transitivity often defined using particular letters for variables, those are merely placeholders.  Further, even though it is often written with three distinct letters, those three variables do *not* need to represent distinct elements, you could have had repeated values.  In words, a relation is transitive iff for every occurrence of one thing being related to another thing and that second thing being related to a third (*not necessarily different*) thing that you must also have the first thing being related to the third thing.
Comment: Thank you for your explanation. It helped me to clarify this.
Answer: Not transitive, b and c could be siblings.
Comment: Or not related at all, if $b$ has cousins on both their mother's and father's side.
Comment: @DreiCleaner, I have attached an image, so is this still not transitive?
Comment: Right, it is still not transitive. That image shows exactly what I said in my answer. $b$ and $c$ are not cousins because they are siblings.
Comment: If instead child $b$ was a child of daughter 1, then you would have $aRb$, $aRc$, and $bRc$ and it would be a transitive relation. Each pair would be first cousins.
Comment: Thanks for clarifying.
Answer: Well, the set is not transitive. Transitive means that $aRb\wedge bRc\Rightarrow aRc$.
The point is: If the premise is not satisfied, the whole assertion is true.

Transitive relation.


Why RecyclerView CustomAdaper Filter and onViewRecycled() both not working together in android?

Question: My Application need filter on customAdapter, so i implement Filter in CustomAdapter
In CustomAdapter i put Google Map. When Adapter is recycled google map pin and map view is changed for that solution i use onViewRecycled() method and in that i set Latitude and Longitude and set Marker on Google Map view.
But problem is that when i implement Filter logic then application is crash and give me ArrayIndexOutOfBound Exception that error point me in onViewRecycled() method.
Please Help me to solve this Problem.
My Adapter and Activity code is below:
PostListAdapter.java
public class PostListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable{

    Context mcontext;
    LayoutInflater inflater;

    View view;
    RecyclerViewHolder recyclerViewHolder;
    FragmentManager fm;
    MapView map;
    GPSTracker gps;
    private double latitude=0.0, longitude=0.0;
    LatLng latlongs;
    Geocoder geocoder;
    List<Address> addressList;
    GoogleMap thisMap;
    String mapTitle = null;
    String mapSnnipet = null;
    boolean isAgreePost;
    List<GetPostCallBack> getPostCallBackList;
    List<GetPostCallBack> getPostCallBackListFiltered=new ArrayList<>();
    Dialog dialog;
    String User_Id = "";
    double latitudeForMarker=0.0, longitudeForMarker=0.0;

    public PostListAdapter(Context mcontext, FragmentManager fm, List<GetPostCallBack> getPostCallBackList) {

        inflater = null;
        this.mcontext = mcontext;
        this.fm = fm;
        this.getPostCallBackList = getPostCallBackList;
        this.getPostCallBackListFiltered.addAll(getPostCallBackList);
        User_Id = Functions.getStringPref(mcontext, FindExperience.USER_ID);
        Log.d("TAG", "PostListAdapter: " + User_Id);
        inflater = (LayoutInflater) this.mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        gps = new GPSTracker(mcontext);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout_home, parent, false);
        recyclerViewHolder = new RecyclerViewHolder(view);
        return recyclerViewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

        recyclerViewHolder = (RecyclerViewHolder) holder;
        thisMap = recyclerViewHolder.gMap;

        if (!getPostCallBackList.get(position).getProfilePicture().equals("")) {
            Picasso.with(mcontext).load(getPostCallBackList.get(position).getProfilePicture()).placeholder(android.R.drawable.ic_menu_gallery).into(recyclerViewHolder.ivPostUserImg);
        }
        recyclerViewHolder.tvPostUserName.setText(getPostCallBackList.get(position).getFullName());
        recyclerViewHolder.tvPostQuote.setText(getPostCallBackList.get(position).getUserNote());
        recyclerViewHolder.tvPostCreatedDate.setText(getPostCallBackList.get(position).getPostDate());
        recyclerViewHolder.tvPostTitle.setText(getPostCallBackList.get(position).getPostTitle());
        recyclerViewHolder.tvPostCategorySubCategory.setText(getPostCallBackList.get(position).getCatName() + "/" + getPostCallBackList.get(position).getSubCatName());
        recyclerViewHolder.tvPostContent.setText(getPostCallBackList.get(position).getPostContent());

        recyclerViewHolder.btnAgree.setText("AGREE (" + getPostCallBackList.get(position).getTotalLike() + ")");
        recyclerViewHolder.btnDisagree.setText("DISAGREE (" + getPostCallBackList.get(position).getTotalDislike() + ")");
        final Activity activity = (Activity) mcontext;
        recyclerViewHolder.ReadMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent(mcontext, PostDetailsActivity.class);
                i.putExtra("Details", getPostCallBackList.get(position));
                activity.startActivity(i);
                activity.overridePendingTransition(R.anim.left_in, R.anim.left_out);
            }
        });
        recyclerViewHolder.btnAgree.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Intent i = new Intent(mcontext, AgreeListActivity.class);
                activity.startActivity(i);
                activity.overridePendingTransition(R.anim.left_in, R.anim.left_out);
                return true;
            }
        });
        recyclerViewHolder.btnAgree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                apiCallForUserAgreeDisAgree(getPostCallBackList.get(position).getPostId(), User_Id, "1");
            }
        });
        recyclerViewHolder.btnDisagree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                apiCallForUserAgreeDisAgree(getPostCallBackList.get(position).getPostId(), User_Id, "0");
            }
        });
        recyclerViewHolder.btnDisagree.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Intent i = new Intent(mcontext, DisAgreeListActivity.class);
                activity.startActivity(i);
                activity.overridePendingTransition(R.anim.left_in, R.anim.left_out);
                return true;
            }
        });
        recyclerViewHolder.btnComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(mcontext, CommentListActivity.class);
                activity.startActivity(i);
                activity.overridePendingTransition(R.anim.left_in, R.anim.left_out);

            }
        });
    }

    //Recycling GoogleMap for list item
    @Override
    public void onViewRecycled(RecyclerView.ViewHolder holder) {
        // Cleanup MapView here?
        if (recyclerViewHolder.gMap != null) {
            int position = recyclerViewHolder.getPosition();
            recyclerViewHolder.gMap.clear();
            recyclerViewHolder.gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            latitude=0.0;
            longitude=0.0;
            if (!(getPostCallBackList.get(position).getLangitude().equals("") && getPostCallBackList.get(position).getLongitude().equals(""))) {
                latitude = Double.parseDouble(getPostCallBackListFiltered.get(position).getLangitude());
                longitude = Double.parseDouble(getPostCallBackListFiltered.get(position).getLongitude());
                Log.d("TAG", "onBindViewHolder: recycled : " + latitude + " " + longitude);
                latlongs = new LatLng(latitude, longitude);
                // For zooming automatically to the location of the marker
//                CameraPosition cameraPosition = new CameraPosition.Builder().target(latlongs).zoom(14).build();
                geocoder = new Geocoder(mcontext, Locale.getDefault());
                try {
                    addressList = geocoder.getFromLocation(latitude, longitude, 1);
                    if (addressList != null && addressList.size() > 0) {
                        Address address = addressList.get(0);
                        StringBuilder sb = new StringBuilder();
                        StringBuilder sb1 = new StringBuilder();
                        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                            sb1.append(address.getAddressLine(i)).append("\n");
                            mapSnnipet = sb1.toString();
                        }
                        sb.append(address.getLocality());
                        mapTitle = sb.toString();
                    }
                    Log.d("TAG", "onMapReady: " + addressList.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                MarkerOptions a = new MarkerOptions().position(latlongs).title(mapTitle).snippet(mapSnnipet).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));

                recyclerViewHolder.gMap.addMarker(a);
                recyclerViewHolder.gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlongs, 18.0f));

            }
        }
    }

    public void apiCallForUserAgreeDisAgree(String post_id, String user_id, String status) {
        if (NetworkUtils.getConnectivityStatus(mcontext) != 0) {
            Log.d("TAG", "apiCallForAddPost: User_id : " + user_id);
            Log.d("TAG", "apiCallForAddPost: Post id : " + post_id);
            Log.d("TAG", "apiCallForAddPost: status : " + status);

            API api = App.retrofit.create(API.class);
            final Call<UserAgreeCallBack> userAgreeCallBackCall = api.isAgree(post_id, user_id, status);

            userAgreeCallBackCall.enqueue(new Callback<UserAgreeCallBack>() {
                @Override
                public void onResponse(Call<UserAgreeCallBack> call, Response<UserAgreeCallBack> response) {

                    if (response.code() == 200) {
                        if (response.body().getStatus().equalsIgnoreCase("success")) {
                            if (NetworkUtils.getConnectivityStatus(mcontext) != 0) {
                                dialog = ProgressDialog.show(mcontext, "", "Please Wait.....");
                                dialog.show();
                                API api = App.retrofit.create(API.class);
                                final Call<List<GetPostCallBack>> getPostCallBackCall = api.getAllPost();

                                getPostCallBackCall.enqueue(new Callback<List<GetPostCallBack>>() {
                                    @Override
                                    public void onResponse(Call<List<GetPostCallBack>> call, Response<List<GetPostCallBack>> response) {
                                        if (dialog != null && dialog.isShowing()) {
                                            dialog.dismiss();
                                        }
                                        if (response.code() == 200) {
                                            updateEmployeeListItems(response.body());
                                        }
                                    }

                                    @Override
                                    public void onFailure(Call<List<GetPostCallBack>> call, Throwable t) {
                                        if (dialog.isShowing() && dialog != null) {
                                            dialog.dismiss();
                                        }
                                        Toast.makeText(mcontext, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                                        Log.d("TAG", "onFailure: " + t.getLocalizedMessage());
                                    }
                                });

                            } else {
                                Toast.makeText(mcontext, "Please check your internet connection", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }

                @Override
                public void onFailure(Call<UserAgreeCallBack> call, Throwable t) {
                    Toast.makeText(mcontext, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                    Log.d("TAG", "onFailure: " + t.getLocalizedMessage());
                }
            });

        } else {
            Toast.makeText(mcontext, "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    public void updateEmployeeListItems(List<GetPostCallBack> employees) {
        final GetPostCallBack diffCallback = new GetPostCallBack(this.getPostCallBackList, employees);
        final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);
        this.getPostCallBackList.clear();
        this.getPostCallBackList.addAll(employees);
        diffResult.dispatchUpdatesTo(this);
    }

    @Override
    public int getItemCount() {
        return getPostCallBackList == null ? 0 : getPostCallBackList.size();
    }

    private Filter fRecords;
    @Override
    public Filter getFilter() {
        if(fRecords == null) {
            fRecords=new RecordFilter();
        }
        return fRecords;
    }

    class RecyclerViewHolder extends RecyclerView.ViewHolder implements OnMapReadyCallback {

        GoogleMap gMap;
        MapView map;

        @BindView(R.id.tvReadMore)
        TextView ReadMore;

        @BindView(R.id.btnAgree)
        Button btnAgree;

        @BindView(R.id.btnDisagree)
        Button btnDisagree;

        @BindView(R.id.btnComment)
        Button btnComment;

        @BindView(R.id.ivPostUserImg)
        CircularImageView ivPostUserImg;

        @BindView(R.id.tvPostUserName)
        TextView tvPostUserName;

        @BindView(R.id.tvPostQuote)
        TextView tvPostQuote;

        @BindView(R.id.tvPostCreatedDate)
        TextView tvPostCreatedDate;

        @BindView(R.id.tvPostTitle)
        TextView tvPostTitle;

        @BindView(R.id.tvPostCategorySubCategory)
        TextView tvPostCategorySubCategory;

        @BindView(R.id.tvPostContent)
        TextView tvPostContent;

        public RecyclerViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            map = (MapView) view.findViewById(R.id.mapAdapter);
            if (map != null) {
                map.onCreate(null);
                map.onResume();
                map.getMapAsync(this);
            }
        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
            MapsInitializer.initialize(getApplicationContext());
            gMap = googleMap;
            final int position = getPosition();
            if (gps.canGetLocation()) {
                latitude=0.0;
                longitude=0.0;
                if (!(getPostCallBackList.get(position).getLangitude().equals("") && getPostCallBackList.get(position).getLongitude().equals(""))) {
                    latitude = Double.parseDouble(getPostCallBackList.get(position).getLangitude());
                    longitude = Double.parseDouble(getPostCallBackList.get(position).getLongitude());
                    Log.d("TAG", "onBindViewHolder: " + latitude + " " + longitude);

                    latlongs = new LatLng(latitude, longitude);
                    // For zooming automatically to the location of the marker
//                CameraPosition cameraPosition = new CameraPosition.Builder().target(latlongs).zoom(14).build();
                    geocoder = new Geocoder(mcontext, Locale.getDefault());
                    try {
                        addressList = geocoder.getFromLocation(latitude, longitude, 1);
                        if (addressList != null && addressList.size() > 0) {
                            Address address = addressList.get(0);
                            StringBuilder sb = new StringBuilder();
                            StringBuilder sb1 = new StringBuilder();
                            for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                                sb1.append(address.getAddressLine(i)).append("\n");
                                mapSnnipet = sb1.toString();
                            }
                            sb.append(address.getLocality());
                            mapTitle = sb.toString();
                        }
                        Log.d("TAG", "onMapReady: " + addressList.toString());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    MarkerOptions a = new MarkerOptions().position(latlongs).title(mapTitle).snippet(mapSnnipet).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
                    if (gMap != null) {
                        gMap.addMarker(a);
                        gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlongs, 18.0f));
                        gMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                            @Override
                            public boolean onMarkerClick(Marker marker) {
                                if (marker != null){
                                    latitudeForMarker = Double.parseDouble(getPostCallBackList.get(position).getLangitude());
                                    longitudeForMarker = Double.parseDouble(getPostCallBackList.get(position).getLongitude());
                                    Log.d("TAG", "onMarkerClick: on viewcreated : http://maps.google.com/maps?daddr="+latitudeForMarker+","+longitudeForMarker);
//                                Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
//                                        Uri.parse("google.navigation:q="+mapSnnipet));

                                    Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                                            Uri.parse("http://maps.google.com/maps?daddr="+latitudeForMarker+","+longitudeForMarker));
                                    mcontext.startActivity(intent);
                                    return true;
                                }
                                return false;
                            }
                        });
                    }
                }
            }
        }
    }
    //filter class
    private class RecordFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            FilterResults results = new FilterResults();

            //Implement filter logic
            // if edittext is null return the actual list
            if (constraint == null || constraint.length() == 0) {
                //No need for filter
//                getPostCallBackList.clear();
//                getPostCallBackList.addAll(getPostCallBackListFiltered);
                results.values = getPostCallBackListFiltered;
                results.count = getPostCallBackListFiltered.size();

            } else {
                //Need Filter
                // it matches the text  entered in the edittext and set the data in adapter list
                ArrayList<GetPostCallBack> fRecords = new ArrayList<>();

                for (GetPostCallBack s : getPostCallBackListFiltered) {
                    if (s.getFullName().toLowerCase().contains(constraint.toString().toLowerCase().trim())) {
                        fRecords.add(s);
                    }
                }
                results.values = fRecords;
                results.count = fRecords.size();
            }
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint,FilterResults results) {

            //it set the data from filter to adapter list and refresh the recyclerview adapter
            getPostCallBackList = (ArrayList<GetPostCallBack>) results.values;
            notifyDataSetChanged();
        }
    }
}

HomeActivity.java
public class HomeActivity extends FooterController implements FragmentManager.OnBackStackChangedListener {

    @BindView(R.id.recyclerHome)
    RecyclerView recyclerHome;

    @BindView(R.id.fab)
    Button fab;

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.actvLocationFilter)
    AutoCompleteTextView actvLocationFilter;

    public static ImageView ivSearch;

    @BindView(R.id.etSearch)
    EditText etSearch;

    public static TextView tvTitle;

    public static TextView tvBack;

    @BindView(R.id.tvPost)
    TextView tvPost;

    //@BindView(R.id.ivDrawer)
    public static ImageView ivDrawer;

    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;

    @BindView(R.id.navList)
    ListView mDrawerList;

    private ArrayAdapter<String> drawerAdapter;
    LinearLayoutManager linearLayoutManager;
    PostListAdapter adapter;
    private boolean isLoading = false;
    private boolean isLastPage = false;
    Dialog dialog;
    API api;
    FragmentManager fm;
    GPSTracker gps;
    Boolean buttonStateOpen=false;
    public static int tabPosisiton=0;
    FindExperienceDatabase db;
    List<GetPostCallBack> getPostList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        setBottomBar(R.id.bottomBar,false);
        bindWidgets();
        setCustomActionBar();
        addDrawerItems();
        openDrawer();

        fm = getSupportFragmentManager();
        Functions.checkNetworkConnection(HomeActivity.this);
        apiCallForGetPost();
        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                fm = getSupportFragmentManager();
//                fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                switch (position){
                    case 0:

                        fm.beginTransaction().replace(R.id.container, new ProfileFragment()).addToBackStack(null).commit();
                        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                        break;

                    case 1:
                        fm.beginTransaction().replace(R.id.container, new SettingFragment()).addToBackStack(null).commit();
                        break;

                    default:
                        break;
                }
                drawer.closeDrawer(Gravity.RIGHT);
            }
        });

    public void apiCallForGetPost(){
        getPostList = new ArrayList<>();
        if (NetworkUtils.getConnectivityStatus(HomeActivity.this)!=0) {
            dialog = ProgressDialog.show(this, "", "Please Wait.....");
            dialog.show();
            API api = App.retrofit.create(API.class);
            final Call<List<GetPostCallBack>> getPostCallBackCall = api.getAllPost();

            getPostCallBackCall.enqueue(new Callback<List<GetPostCallBack>>() {
                @Override
                public void onResponse(Call<List<GetPostCallBack>> call, Response<List<GetPostCallBack>> response) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    if (response.code()==200){
                        getPostList = response.body();
                        setRecyclerViewAdapter(getPostList);
                    }
                }

                @Override
                public void onFailure(Call<List<GetPostCallBack>> call, Throwable t) {
                    if (dialog.isShowing() && dialog != null) {
                        dialog.dismiss();
                    }
                    Toast.makeText(HomeActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                    Log.d("TAG", "onFailure: " + t.getLocalizedMessage());
                }
            });

        } else {
            Toast.makeText(HomeActivity.this, "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    @OnClick(R.id.iv_search)
    public void search(){
        if (etSearch.getVisibility()==View.GONE) {
            etSearch.setVisibility(View.VISIBLE);
            etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_DONE) {
                        etSearch.clearFocus();
                        InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        in.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
                        etSearch.setVisibility(View.GONE);
                        return true;
                    }

                    return false;
                }
            });

            etSearch.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    adapter.getFilter().filter(s.toString()); // Perform Filter on Adapter
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        }
        else if (etSearch.getVisibility()==View.VISIBLE){
            InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            in.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
            etSearch.setVisibility(View.GONE);
        }
    }

    public void setRecyclerViewAdapter(List<GetPostCallBack> getPostList){
        adapter = new PostListAdapter(HomeActivity.this,fm,getPostList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerHome.setLayoutManager(mLayoutManager);
        recyclerHome.smoothScrollToPosition(0);
        recyclerHome.setAdapter(adapter);
    }
    public void openDrawer(){
        getSupportFragmentManager().addOnBackStackChangedListener(this);
        ivDrawer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawer.openDrawer(Gravity.RIGHT);
                buttonStateOpen=true;
            }
        });
    }
    private void addDrawerItems() {
        String[] osArray = { "Profile", "Settings" };
        drawerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
        mDrawerList.setAdapter(drawerAdapter);
    }

    @Override
    public void onBackStackChanged() {
        shouldDisplayHomeUp();
        Log.d("TAG", "onBackStackChanged: ");
    }
    public void shouldDisplayHomeUp(){
        //Enable Up button only  if there are entries in the back stack
        Log.d("TAG", "shouldDisplayHomeUp: "+getSupportFragmentManager().getBackStackEntryCount());
        boolean canback = getSupportFragmentManager().getBackStackEntryCount() > 0;
        getSupportActionBar().setDisplayHomeAsUpEnabled(canback);
    }
}

Comment: change `extends RecyclerView.Adapter` -> `extends RecyclerView.Adapter`
Comment: see https://gist.github.com/pskink/cd3bbdd742b5b1905a790c76831b5d85 use it as a base class instead of `RecyclerView.Adapter`
Comment: `onViewRecycled` passes `RecyclerView.ViewHolder` but you are using some `recyclerViewHolder`, i dont get it, why?
Comment: onBindViewHolder() i cast `RecyclerView.ViewHolder` into `RecyclerViewHolder`

Like this `recyclerViewHolder = (RecyclerViewHolder) holder;`
Comment: my question is why you dont use the `ViewHolder` passed  by `onViewRecycled` method? `public void onViewRecycled(RecyclerView.ViewHolder holder) {`
Comment: gMap is not found using `holder` @pskink
Comment: yeah..!! Thanks @pskink
Your solution is work like charm..
Comment: sure, good to hear it
Comment: But i phase new problem, when i scroll recyclerview and then i write in searchbox then app will crash.Why? @pskink
Comment: most likely due to `NullPointerException`, that's why
Comment: It gives me `ArrayIndexOutOfBoundException` @pskink
Comment: ok so i was wrong, ArrayIndexOutOfBoundException is the reason, why dont you use some generic `Filterable` adapter instead?
Comment: What you mean..i didn't get you..plz explain in detailed @pskink
Comment: `public class PostListAdapterNew extends MatchableRVArrayAdapter` i create new adapter like this. Is it right? @pskink
Comment: yes, exactly and for filtering override `matches` method
Comment: In matches() what i have to do? i mean write Filter logic or else? @pskink
Comment: just return true or false depending if your item matches given constraint or not (for convenience lowerCaseConstraint is also passed)
Comment: need to override getFilter() method and RecordFilter Class? @pskink
Comment: no, just override `matches`, thats all
Comment: and of course two abstract methods: `onCreateHolder` and `onBindHolder`, so all you need in your adapter is 3 methods + some constructor
Comment: what is write in `onCreateHolder`  method?
Comment: return your new holder here
Comment: like this? `recyclerViewHolder = new RecyclerViewHolder(view);
        return recyclerViewHolder;`
Comment: like `return new RecyclerViewHolder(view); `
Comment: adapter can't bind. I don't know why, it give me error like `java.lang.NullPointerException at com.example.find.findexperience.adapters.PostListAdapterNew$RecyclerViewHolder.` @pskink
Comment: your `RecyclerViewHolder` constructor crashes
Comment: i write 3 parameter in constructor like this
`public PostListAdapterNew(Context context, int resource, List objects) {
        super(context, resource, objects);
        this.mcontext = context;
        this.getPostCallBackList = objects;
        this.resource = resource;
        this.getPostCallBackListFiltered.addAll(getPostCallBackList);
        User_Id = Functions.getStringPref(mcontext, FindExperience.USER_ID);
        Log.d("TAG", "PostListAdapter: " + User_Id);
        gps = new GPSTracker(mcontext);
    }` @pskink
Comment: what `getPostCallBackListFiltered`? what do you need it for? why  this.mcontext ? why this.resource ? why this.getPostCallBackList? you dont need it at all, just call `super` constructor
Comment: onViewRecycled() method require? @pskink
Comment: if you need custom `onViewRecycled`, then yes, override it
Comment: and required to ovveride getItemCount() method? @pskink
Comment: no, no other methods / fields needed, no getPostCallBackListFiltered, no getPostCallBackList, no mcontext, no resource
Comment: getting constructor error like this `java.lang.NullPointerException
                                                                                at com.example.find.findexperience.adapters.PostListAdapterNew$RecyclerViewHolder.`
Comment: so debug your `RecyclerViewHolder` constructor, whats the problem in calling your debugger? do you know how to setup breakpoints and run the debug session on your android studio?
Comment: you have error in **RecyclerViewHolder**
Comment: ok i got it recyclerview is loaded successfully..but previously is reload recyclerView using **DiffUtil**, now how can i reload or refresh RecyclerView Data? @pskink
Comment: see what additional methods `MatchableRVArrayAdapter` provides
Comment: i try with `setNotifyOnChange(true);` but it not working @pskink
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/147674/discussion-between-user5908465-and-pskink).
Answer: Use the ViewHolder "holder", which is passed on to your Override function
public void onViewRecycled(RecyclerView.ViewHolder holder)

It will work as intended.
Comment: Your mean to say is i use `(holder.gMap != null)` instead of `(recyclerViewHolder.gMap != null)` , i try but **gMap** is not found using `holder`


saving player name & score to text file and delete the lowest score

Question: I want to add a save function to my game, where the program saving the score and the player name to the outer source like text file.
I already have the text file like this, and it already contain some dummy data :
AOLAS, 3500
SITI, 3600
JAMILAH, 2200
SURATNA, 3400
TATANG, 2000

what I want to do is, the program to save the player name & score to the text file. but before write the new data, it check the text file, line-per-line to get the line of data which has the lowest score on it and delete it. and after that the new data will be saved to the text file.
I tried to something like this :
   public void saveHighScores()
   {
        string line;
        StreamWriter sw = new StreamWriter("highscore.txt");
        while ((line = sw.WriteLine()) != null)
        {
            string[] parts = line.Split(',');
            hiScoreName = parts[0].Trim();
            QuizScreen.score = Int32.Parse(parts[1].Trim());
        }

        sw.Close();
   }

actually I just reversed my read high score data function from before, because I think it'll work like that. but it doesn't.
it get the error:

cannot implicitly convert type 'void' to 'string'" in the WriteLine().

...and I still can't figured the logic(and it's code) how to check the lowest score, delete it, and then save the new data...
Comment: That code won't compile (I reformatted post so as to be more obvious)
Answer: I think I see what you are doing, you're trying to write a file the same way you would read it, is this what you need?
public void saveHighScores(string hiScoreName, int score)
{
    string line;
    StreamWriter sw = new StreamWriter("highscore.txt");
    line = hiScoreName + ", " + score.ToString();
    sw.WriteLine(line);

    sw.Close();
}

You can also use arrays or lists if you need to record multiple high scores
Edit:
I think you need to understand the logic behind writing and reading from a file.
When you read a file, this line:
while((line = sr.ReadLine()) != null) {

checks whether the next line is null, or that we've reached the end of the file.
When you write to a file, you can skip this part, as, most often, you don't want to stop when you reach the end of a file. ALso, sw.WriteLine() writes to the file but doesn't return a value, which is causing your error.
in my code above, the lines:
line = hiScoreName + ", " + score.ToString();
sw.WriteLine(line);

mean this:
line = hiScoreName followed by a comma followed by the score = "name, score"
write that line to the file


Correct approach to comparing sub-group means across multiple treatment conditions

Question: Let's say I have an experiment where I randomly pair people up with either a male or a female player, and they play a game together.  I then measure some dependent variable -- call it outcome . From the perspective of participants, there are four possible subgroups -- Male-Male (MM), Male-Female (MF), Female-Male (FM), and Female-Female (FF).  I have created a group variable that is simply a factor variable representing each of those levels.
In my current set-up, if I want to compare differences in means between these groups, I can do something straight-forward like:
felm(outcome ~ group | team_id | 0 | 0)

Where I cluster the standard errors at the team level.  However, now I have two control conditions where I pair people up in the same way (into the four sub-groupings), but have them do different activity.  I want to demonstrate that, for the same sub-group, the treatment condition has a greater mean than any of the control conditions.
In other words, I want to compare MM in the treatment group to MM in either of the two controls, and confirm that the DV of MM in the outcome group is larger than both of the control conditions.
What is the right way to do this?
My current approach is to create a condition variable that is equal to three levels, e.g. ("Main Treatment", "Control 1", "Control 2").  So treatment is a factor with four levels ("MM", "FM", "MF", and "FF"):
lm(outcome ~ treatment*condition)

But I'm not sure this is actually capturing what I intend for it to capture

Edits:

With any of the above approaches, how can I continue to do the relevant comparisons while clustering standard errors at the team level (e.g. via felm from lfe library or lm_robust from estimatr library?)
With the ANOVA approach described in the answer, the resulting output will look something like this:

Response: outgroup_feelings_diff
                     Df Sum Sq Mean Sq F value   Pr(>F)
treatment             3   1276  425.23  3.8863 0.009073 **
condition             2    331  165.67  1.5141 0.220867
treatment:condition   6   1132  188.62  1.7238 0.113025
Residuals           592  64777  109.42

However, this doesn't tell me if a specific combination of the treatment and condition is better than some other combination -- it is presumably averaging across all combinations.  Is there a way, in the ANOVA framework to ask some specific question like whether MF in the "Main Treatment" is greater than MF in "Control 1" and "Control 2." (Should I just stick with the Tukey approach if I want to do this?)

What is the substantive difference between the interaction approach described in #2 and creating an entirely new variable that explicitly interacts treatment and condition.  For example:

treatment_condition <- paste0(treatment, condition)
lm(outcome ~ treatment_condition)

And then cycling through the relevant reference groups until I get the comparison I want.
Answer: Two-way anova interpretation
For the experiment you describe, you need a two-way anova (two-way since you have two factors in your experiment). The lm function (lm(outcome ~ treatment*condition)) that you describe fits this model, but there are different ways to get the results. The presentation of the results can be quite different, even though the underlying models is the same.
First way: using anova()
my_lm = lm(outcome ~ treatment*condition, data)
anova(my_lm)

The anova table will give you an estimate for each of your factors and the interaction. So this will tell you wether (1) the treatment has a significant effect on the outcome and (2) whether the condition has a significant effect on the outcome and (3) whether the treatment effect is different for certain conditions (this is the interaction effect).
Second way: using summary()
my_lm = lm(outcome ~ treatment*condition, data)
summary(my_lm)

To interpret this, we could look firstly at overall quality of the model (F-statistic and p-value, R squared and adjusted R squared. And secondly the coefficients table contains all estimated effects from the linear model. Those estimates are in the form of contrasts, meaning that there is not one estimate per 'variable', but that there is one estimate for each group (one less than number of categories, since the first category is taken as control group). On way to change the control group is using relevel().
With the same summary result, to find the estimated outcome for MM doing activity 2, you would need to sum the intercept + the estimate for MM + the estimate for activity 2.
Using this table, the estimate and the p-value for MM will tell you whether the outome of MM is on average significantly higher than the control group.
Pairwise comparisons and adding self-specified contrasts:
You want not only to compare MM to the automatically selected control group but also to other effects. One way is to get pairwise comparisons, or post hoc tests, where you compare each treatment category to each other(pairwise meaning test every possible combination for significance).
To do this easily you can use the Tukey post hoc tests in TukeyHSD(). Unfortunately, they do not work with an lm object, so you need to re-fit the exact same model but with the functiom aov.
my_lm = aov(outcome ~ treatment*condition, data)
TukeyHSD(my_lm)

This will give you pairwise comparisons for each of your treatments, so basically the same as the summary output but then repeated for each group as a reference group. Also the significance values are adjusted for the fact that you do many repeated tests.
If you want to compare even more, you can take a look into contrasts. They will allow you to compare two groups of treatment categories that you specify yourself. For example you could specify a contrast for MM and FF on one side vs MF and FM on the other side.
To do this, you should look into custom contrasts. A very good explanation an be found in the answer of this question: How to set custom contrasts with lmer in R
Some other reference material on contrasts here: https://rcompanion.org/rcompanion/h_01.html
And here a general reference on multi-factor anova: https://onlinecourses.science.psu.edu/stat502/node/152/
Edit:
1 - All the comparisons that I mention (even pairwise) can be specified using contrasts. I've taken a look at the felm documentation and there's also a constrast parameter that you can specify. I give you the following link that is very complete on setting up contrasts : https://rstudio-pubs-static.s3.amazonaws.com/65059_586f394d8eb84f84b1baaf56ffb6b47f.html
Basically for comparing a category A vs B and C you specify A as -1, B as 0.5 and C as 0.5 (or inverse negative / positive) as long as the sum is 0. Then it will compare the negative groups against the positive ones.
2 + 3 - For finding out whether a certain treatments works better for certain conditions, you should look at the interaction effect and see whether it is significant. Then the pairwise comparisons or specify particular constrasts for the interaction effect will detail this for particular groups.
It can become complicated here to specify those contrasts. To make it happen you could do what you propose in point 3, that is combine everything into one factor. The overall result should be the same (the F value of the omnibus test). Of course you're not going to have the split in treatment and condition and interaction effect.
Here a link that confirms this : Can you convert three-way ANOVA to one-way ANOVA?
Comment: I've updated my answer to include the additional questions.
Comment: Thank you so much for the thorough and comprehensive reply.  I have several quick follow-up questions that I don't fully understand how to implement - please see edits for details!
Comment: Thanks so much! Extremely thorough and informative


Is the maximum scalability of an Azure Function capped at 10?

Question: We're trying to test scalability of Azure functions (it's a bear). We came across this https://azure.microsoft.com/en-in/documentation/articles/functions-reference/#parallel-execution

If a function app is using the Dynamic Service Plan, the function app
  could scale out automatically up to 10 concurrent instances. Each
  instance of the function app, whether the app runs on the Dynamic
  Service Plan or a regular App Service Plan

Does this mean that the maximum scalability of a single function is just 10? we've never been able to get over 10 units running... (previous question on the algorithm to determine adding another consumption unit, this to determine the upper end of scalability).
Thanks
Comment: Possible duplicate of [What is the scaling algorithm for Azure Functions (never been able to get over 7 parallel instances running)](http://stackoverflow.com/questions/37709255/what-is-the-scaling-algorithm-for-azure-functions-never-been-able-to-get-over-7)
Answer: UPDATE: There is no official maximum number of instances. We see customers who are able to scale out to hundreds. The number you achieve depends mostly on your workload, but partly on the region you're running in (some regions have more capacity than others). The 10 instance limit mentioned in previous versions of the docs has been removed.
You can find more information about our consumption plan and scaling here: https://learn.microsoft.com/en-us/azure/azure-functions/functions-scale#how-the-consumption-plan-works
Also note that each instance in Azure Functions can run multiple function executions in parallel. For example, if you have a function app which has a single function that runs quickly, you could expect to see dozens or even hundreds of concurrent executions on a single instance. This is unlike other services such as AWS Lambda which only execute a single function at a time per instance. New instances are added only when the system decides that the current number of instances is insufficient to handle the current load (more details on that in my answer to your other question).
Comment: Thanks Chris, I understand this is a work in progress and appreciate your quick responses. To give your team some insight into what we are trying to do. We currently run 250 T2 instance on Ec2 to handle this problem. We can't run lambda (although we do for other operations) as this has some .net code necessary. The 'magic' behind the scenes for scaling is very frustrating as there is no way to deterministically ensure the user experience. The process is big on memory and takes a couple of minutes to run, which looks like it limits us to a best case scenario of 10 parallel executions.
Comment: Thanks for the information. That's definitely useful for us and we'll take that into consideration. One thing I forgot to mention in my original answer is that the 10 instance limit will go away by the time we hit GA. We definitely want to support cases where workloads require potentially hundreds of instances (it's just an internal config knob for us right now).
Comment: I've updated my answer since we are now GA and no longer have a limit to the number of instances we support.


Saving and Restoring caret position for contentEditable div

Question: I have a contentEditable div, the innerHTML of which can be updated through AJAX while editing. The problem is that when you change the contents of the div it moves the cursor to the end of the div (or loses focus depending on the browser). What is a good cross-browser solution to store caret position before changing innerHTML and then to restore it?
Answer: back to 2016 :)
After I came across solutions here and they did not suit me, because my DOM was replaced completely after each typing. I've done more research and come with a simple solution that saves the cursor by character's position that works perfect for me.
The idea is very simple.

find the length of characters before caret and save it.
change the DOM.
using TreeWalker to walk just on text nodes of context node and counting characters  until we got the right text node and the position inside it

Two edge case:

content removed completely so there is no text node:
so: move the cursor to the start of the context node

there is less content than the index pointed on :
so: move the cursor to the end of the last node

function saveCaretPosition(context){
    var selection = window.getSelection();
    var range = selection.getRangeAt(0);
    range.setStart(  context, 0 );
    var len = range.toString().length;

    return function restore(){
        var pos = getTextNodeAtPosition(context, len);
        selection.removeAllRanges();
        var range = new Range();
        range.setStart(pos.node ,pos.position);
        selection.addRange(range);

    }
}

function getTextNodeAtPosition(root, index){
    const NODE_TYPE = NodeFilter.SHOW_TEXT;
    var treeWalker = document.createTreeWalker(root, NODE_TYPE, function next(elem) {
        if(index > elem.textContent.length){
            index -= elem.textContent.length;
            return NodeFilter.FILTER_REJECT
        }
        return NodeFilter.FILTER_ACCEPT;
    });
    var c = treeWalker.nextNode();
    return {
        node: c? c: root,
        position: index
    };
}

<link href="https://rawgit.com/PrismJS/prism/gh-pages/themes/prism.css" rel="stylesheet"/>

Edit the CSS Snippet

    p { color: red }

Comment: I actually have the same question as @pelican_george - your approach works very well, but it does not work with line breaks. As soon as your insert a line break, the cursor stays on the first line (even thou the new line has been created).

Have a look at the jsfiddle with your example:
https://jsfiddle.net/80ovoxr9

I couldn't the line breaks to work unfortunately :(
Comment: What if you have line breaks and other formatting elements within the content editable element?
Comment: I have a content editable with breaks and such and it works. If you use it for an undo function, store the last keypress in a onKeyDown handler and use `range.setStart(pos.node ,pos.position-(lastKeypress == 13 ? 0:1));` to prevent the cursor going on a walk :-)
Comment: Seem like changing  to display inline-block help a bit with line-break.
Comment: you mean like  of ? it  still should work . that code build for richtext editor that change elements around the cursor when user writing
Comment: Thanks for the fiddle. I check it and find a little bug in the loop. but there another bug into `Prism`.  I fixed the loop bug (https://jsfiddle.net/80ovoxr9/10/]. ( Shift  + Enter help you get down a line)
Comment: What about restoring a selection, not only a caret position?
Comment: user selecting some text and then continue to write stuff, and he expect the selecting area remains ? anyway I guess you can create two range object one for the start position and one for the end position and use them to restore the selection range
Comment: @perymimon That saved my day. Thank you.
Comment: I get a bug with this script that causes the cursor to jump to the beginning when I put it at the end and enter a character. The solution is as simple as changing to `index > elem.textContent.length` and `position: index`, but I can't edit the answer because the queue is full.
Comment: 'lastNode' is assigned a value but never used
Comment: @Motla Thanks :), it clean it up a bit, probably stay there from a previous version
Comment: This answer is so close to perfect, but in still has some enter key/line break issues. Shift + enter doesn't work on firefox. Also adding line breaks to the end of the string  doesn't work in firefox. Also, in Chrome, is it possible to make "enter" work in the same way as "shift + enter"?
Comment: thanks. can you know how the reason for this and how to solve it? I will update my The reason
Comment: If anyone interested anymore, I have an approach that will work for line breaks and formatting element.
Comment: Anyone using this in react/nextjs? this works for me, but have a side effect..

its selecting/highlighting all the text before the caret.. its weird because in the snippet above it doesnt show
Answer: I know this is an ancient thread but I thought I would provide an alternative non-library solution
http://jsfiddle.net/6jbwet9q/9/
Tested in chrome, FF, and IE10+  Allows you to change, delete and restore html while retaining caret position/selection.
HTML

JS
function saveRangePosition()
  {
  var range=window.getSelection().getRangeAt(0);
  var sC=range.startContainer,eC=range.endContainer;

  A=[];while(sC!==bE){A.push(getNodeIndex(sC));sC=sC.parentNode}
  B=[];while(eC!==bE){B.push(getNodeIndex(eC));eC=eC.parentNode}

  return {"sC":A,"sO":range.startOffset,"eC":B,"eO":range.endOffset};
  }

function restoreRangePosition(rp)
  {
  bE.focus();
  var sel=window.getSelection(),range=sel.getRangeAt(0);
  var x,C,sC=bE,eC=bE;

  C=rp.sC;x=C.length;while(x--)sC=sC.childNodes[C[x]];
  C=rp.eC;x=C.length;while(x--)eC=eC.childNodes[C[x]];

  range.setStart(sC,rp.sO);
  range.setEnd(eC,rp.eO);
  sel.removeAllRanges();
  sel.addRange(range)
  }

function getNodeIndex(n){var i=0;while(n=n.previousSibling)i++;return i}

Comment: Uncaught ReferenceError: bE is not defined
Comment: This looks as though it's converting each selection range boundary to a path and back again. This is a great approach so long as the structure of the DOM is the same before and after the `innerHTML` changes, which isn't guaranteed to be true.
Comment: Is it possible to fix this code for multiple contenteditable divs? So that I can select, lets say, 1 of 3 div contenteditable, and then retrive the position of where I want to insert.
Answer: Update: I've ported Rangy's code to a standalone Gist:
https://gist.github.com/timdown/244ae2ea7302e26ba932a43cb0ca3908
Original answer
You could use Rangy, my cross-browser range and selection library. It has a selection save and restore module that seems well-suited to your needs.
The approach is not complicated: it inserts marker elements at the beginning and end of each selected range and uses those marker elements to restore the range boundaries again later, which could be implemented without Rangy in not much code (and you could even adapt Rangy's own code). The main advantage of Rangy is support for IE <= 8.
Comment: @thedayturns: That's the correct attitude to have, so I don't blame you :) I'm glad it helped.
Comment: @Norman: I ported Rangy's code to a standalone Gist: https://gist.github.com/timdown/244ae2ea7302e26ba932a43cb0ca3908. Obviously you can cut the selection stuff out if you like, but I left it in in case it was useful to anyone else.
Comment: Fantastic. I had some trepidation about using a random library from some guy on SO, but it did what I wanted in 2 lines of code. Thanks!
Comment: @TimDown Does Rangy support multiple contenteditable divs? Like, saving position of caret over three different divs. Reason being, I want to use 1 editor for 3 different fields.
Comment: I not sure how that approach can work if i replace completely the whole div's content
Comment: @perymimon: No, it wouldn't. I'd use a character offset-based approach instead in that case.
Comment: Hey Tim, sorry for asking here, but is there a standalone version of the save / restore module that will not require the Rangy core ?
Comment: I'm essentially looking for two functions: "save_range": to insert invisible span elements at current selection start and end (or one at caret). and "restore_range": that will change the spans back into a selection. nothing much more than that.


Como retornar apenas os resultados que tenham apenas a determinada condição

Question:  select
CODIGO_GRUPO
,CODIGO_COTA
,NUMERO_ASSEMBLEIA

from COBRANCAS c

where 2=2
and CODIGO_MOVIMENTO = 270

and NUMERO_ASSEMBLEIA = 1
and VERSAO = 0
and CODIGO_GRUPO >= 440

esse select retonar
codigo grupo  | codigo cota | numero assembleia

   440              01             01

   440              02             01

   440              03             01

porem na minha tabela eu sei que tenho estes mesmos grupos e cotas com o numero de assembleia nº 2 e eu gostaria de retornar apenas os que estivessem o numero de assembleia  1
Answer: Experimente acrescentar a condição abaixo no Where para verificar se existe outra linha para o grupo / cota:
and not exists
    (select 1 from COBRANCAS s
     where
         s.CODIGO_GRUPO = c.CODIGO_GRUPO and
         s.CODIGO_COTA = c.CODIGO_COTA and
         s.NUMERO_ASSEMBLEIA <> c.NUMERO_ASSEMBLEIA)


Do I have to be REALLY LOUD to get a full mixed/belted voice?

Question: I'm trying to teach myself how to sing for 2 months now or something. I've looked on the internet to gather as much information as I could to make my journey as safe as possible but nobody mentions this in a at least "descriptive" way.
I can go as low as a C2 ... but that's a useless note, not strong enough and as high as E4/F4. I think F4 is my where my break is. Anyway, I know how to do the transition smoothly from chest to head without hearing the break but my problem is that when I sing rock/metal where I have to put more pressure I am VERY loud. I think I do have somewhat proper chord closure and what I'm really asking here is... Do I have to be THAT loud? Is that the right way?
I mean someone walked in the room last time I tried doing what I describe above and he glares at me...  I'm like "I know" and he said "No.... you really Don't! Last time you try to sing that song."
I bet I'm labeled as the crazy person in my neighborhood by now. So what gives? Any input would be welcomed.
Comment: In my experience, singing as quietly as possible helps my voice sound as good as possible and last as long as possible. You should find a teacher, even if for only a couple lessons. I'm pretty sure that singing really loud is not good for your voice.
Answer: I think what you need are vocal exercises to train that bridge between your head voice and your chest voice. No worries, all singers are stuck with this problem - even experienced ones! Try the exercises in this video, they should help!

and also more on singing right here: http://superiorsingingsuccess.weebly.com/home/how-to-sing-better-for-guys
hope this helps man!
Comment: First of all thanks for the answer.
I have to say that since I'm self taught I'm abusing vids like the above. I've watched them "all."

I managed to fix my problem. The issue was a lowered soft palate. I thought I was rising it up enough but it could and did go MUCH further in which like a switch made me a better singer. It's weird how these things work. In just a moment of trying things out. The way I sing changed completely. It's not just the noise that it almost disappeared... I also can sing much more relaxed now, the tension goes to keeping the palate up and at The vocal chords.


Android SQLite connection management

Question: I'm working with SQLite in my android project. There is a feature that is clear to me -- if there are multiple threads working with DB then they should use only ONE instance of DBHelper and SQLite guarantee a safe access (even if it is concurrent) to the DB.
But I still have one thing needed to be clarified. How should I manage with DB connection (SQLiteDatabase object)? How often should I call geWritableDatabase() and close()? Is it ok if I call these methods once? Or it's better to obtain SQLDatabase object and close one every time I perform read/write operation on DB?
Answer: It is handled by default... I mean if a writtable database open, whenever you try to access read-only database it closes writtable one and create new read-only database instance. As far as i know :)
Comment: Yes. it is better to invoke getWritableDatabase() and getReadableDatabase() methods every time just to be sure which one you are about to use... Also if there is a multi-threading you have to manage some kind of synchronization there, where no developer wants his/her database closed while fetching data from database
Comment: Also take a look javadoc description...Create and/or open a database. This will be the same object returned by getWritableDatabase() unless some problem, such as a full disk, requires the database to be opened read-only. In that case, a read-only database object will be returned. If the problem is fixed, a future call to getWritableDatabase() may succeed, in which case the read-only database object will be closed and the read/write object will be returned in the future.
Comment: As a matter of fact, `getReadableDatabase` returns write-able connection in most cases. You only get read-only connection if device is running out of memory.
Comment: And if I want to write into DB from multiple threads than should getWritableDatabase() and close() be invoked in each of them?

Android SQLite connection management


Jquery POST to refresh a div

Question: I want to use $.post function of jquery to do a div refresh, only if the content returned in the json data from the php script is modified. I know that ajax calls with $.post are never cached. Please help me with $.post, or $.ajax if it is not possible with $.postor any other method with which this is possible.
Thanks
Answer: Why don't you cache the response of the call?
var cacheData;
$.post({.....
         success: function(data){
                  if (data !== cacheData){
                     //data has changed (or it's the first call), save new cache data and update div
                   cacheData = data;
                   $('#yourdiv').html(data);
                   }else{
                   //do nothing, data hasan't changed

This is just an example, you should adapt it to suit your needs (and the structure of data returned)
Answer: var result;
$.post({
    url: 'post.php'
    data: {new:'data'}
    success: function(r){
       if (result && result != r){
        //changed
       }

       result = r;
    }
});

Answer: Your question isn't exactly clear, but how about something like this...

  <input id="refresh" type="submit" value="Refresh" />

I think you should use .getJSON() like I used it there, it's compact, and offers all the functionality you need.
Answer: var div = $('my_div_selector');
function refreshDiv(data){
    // refresh the div and populate it with some data passed as arg
    div.data('content',data);
    // do whatever you want here
}
function shouldRefreshDiv(callback){
    // determines if the data from the php script is modified
    // and executes a callback function if it is changed
    $.post('my_php_script',function(data){
        if(data != div.data('content'))
            callback(data);
    });
}

then you can call shouldRefreshDiv(refreshDiv) on an interval or you can attach it to an event-handler

Jquery POST to refresh a div


Why different results to two different ways of writing query

Question: I am trying to understand why the following two SQL statements give different results.  The first works as expected, the second produces no records.
 Select * from Jet.LayoutListItemEntity_Default itemDefault
 Join  Jet.LayoutListEntity  b
 on itemDefault.UiKey = b.UiKey
 Left join (Select * from Jet.LayoutListItemEntity where DomainId =2) item
 on itemDefault.BindingPath = item.BindingPath
 where item.DomainId is null
 and b.DomainId = 2

 Select * from Jet.LayoutListItemEntity_Default itemDefault
 Join  Jet.LayoutListEntity  b
 on itemDefault.UiKey = b.UiKey
 Left join Jet.LayoutListItemEntity  item
 on itemDefault.BindingPath = item.BindingPath
 where item.DomainId is null
 and item.DomainId = 2
 and b.DomainId = 2

The primary difference is that one puts the item.DomainId = 2 at the end, instead of in it's own select. It seems to me they would produce the same results.
Greg
Comment: Any reason as to the downvotes?
Answer: These conditions are mutually exclusive:
where item.DomainId is null
 and item.DomainId = 2

item.DomainID can't simultaneously be NULL and 2
You can move the errant where criteria to the JOIN criteria:
Select * from Jet.LayoutListItemEntity_Default itemDefault
 Join  Jet.LayoutListEntity  b
 on itemDefault.UiKey = b.UiKey
 Left join Jet.LayoutListItemEntity  item
 on itemDefault.BindingPath = item.BindingPath
    and item.DomainId = 2
 where item.DomainId is null
 and b.DomainId = 2

Comment: Thank you.  I didn't realize you could put criteria like that in a join.
Answer: Your WHERE criteria is messed up in the 2nd query -- to make those statements the same, move the and item_DomainId = 2 to the JOIN.
 Select * from Jet.LayoutListItemEntity_Default itemDefault
     Join  Jet.LayoutListEntity  b
         on itemDefault.UiKey = b.UiKey
     Left join Jet.LayoutListItemEntity  item
         on itemDefault.BindingPath = item.BindingPath and item.DomainId = 2
 where item.DomainId is null
     and b.DomainId = 2


tableselect does not work for me somehow 1

Question: Array
(
    [table] => Array
        (
            [#type] => tableselect
            [#header] => Array
                (
                    [field_name] => FIELD NAME
                    [field_type] => FIELD TYPE
                    [no_of_values] => NO OF VALUES
                    [display_fields] => DISPLAY FIELDS
                    [field_label] => FIELD LABEL
                    [required] => Required
                    [product_type] => Product Type
                )

            [#options] => Array
                (

            [field_colour_pro] => Array
                        (
                            [field_name] => field_colour_pro
                            [field_type] =>
                            [no_of_values] =>
                            [display_fields] => 1
                            [field_label] => color
                            [required] => 0
                            [product_type] => shirt
                        )

                    [field_description] => Array
                        (
                            [field_name] => field_description
                            [field_type] =>
                            [no_of_values] =>
                            [display_fields] => 1
                            [field_label] => description
                            [required] => 0
                            [product_type] => test_pro_v
                        )

                )

            [#multiple] => 1
        )

$header = array(
    'field_name' => t('FIELD NAME'),
    'field_type' => t('FIELD TYPE'),
    'no_of_values' => t('NO OF VALUES'),
    'display_fields' => t('DISPLAY FIELDS'),
    'field_label' => t('FIELD LABEL'),
    'required' => t('Required'),
    'product_type' => t('Product Type'),
  );

  $rows = array();
  foreach(commerce_product_types() as $product_type => $product_type_array){
    $field_info = field_info_instances('commerce_product',$product_type);
    foreach($field_info as $machine_name =>$field_details){
      $rows[$machine_name] = array(
        'field_name' => $machine_name,
        'field_type' => $field_details['type'],
        'no_of_values' => $field_details['cardinality'],
        'display_fields'=>1,
        'field_label' => $field_details['label'],
        'required' => $field_details['required'],
        'product_type'=> $product_type,
      );

    }
  }

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#multiple' => TRUE,
  );

//  print_r($form);
  $form['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

return $form;

I tried to get the tableselect form #type into operation it does not work and gives empty row even when each row has values,I would like to help me find any silly mistake which I am making out here
Here is image of how the table select looks which is empty
Answer: I copied your code from and commented the variables and/or functions you're using since I don't know what they are for and just replaced a simple array to loop through.

/**
 * Implements hook_menu().
 */
function leomod_menu() {
  $items['leoo'] = array(
    'title' => 'asd',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('leomod_asd_form'),
    'access callback' => TRUE,
  );
  return $items;
}

/**
 * Form.
 */
function leomod_asd_form($form, &$form_state) {
  $header = array(
    'field_name' => t('FIELD NAME'),
    'field_type' => t('FIELD TYPE'),
    'no_of_values' => t('NO OF VALUES'),
    'display_fields' => t('DISPLAY FIELDS'),
    'field_label' => t('FIELD LABEL'),
    'required' => t('Required'),
    'product_type' => t('Product Type'),
  );

  $rows = array();
  $tests = array('1', '2', '3');
  //foreach(commerce_product_types() as $product_type => $product_type_array){
  foreach($tests as $test) {
    // $field_info = field_info_instances('commerce_product',$product_type);
    //foreach($field_info as $machine_name =>$field_details){
      $rows[$test] = array(
        'field_name' => $test,
        'field_type' => $test,
        'no_of_values' => $test,
        'display_fields'=> $test,
        'field_label' => $test,
        'required' => $test,
        'product_type'=> $test,
      );
    //}
  }

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#multiple' => TRUE,
  );

  //  print_r($form);
  $form['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

Since your table structure is working, I suspect there is something wrong with these lines:
foreach(commerce_product_types() as $product_type => $product_type_array) {

and
$field_info = field_info_instances('commerce_product',$product_type);
foreach($field_info as $machine_name =>$field_details) {

Also make sure you:

Flushed caches
Show all errors while developing since you're dealing with functions there that may return some errors that aren't displayed
Check the variables and functions if they return anything by using print_r() or Devel module's dsm().
Answer: Check that the function (presumably buildForm()) implements "FormStateInterface".  Drupal will render a table w/o children if not done from within such a function.  See: tableselect form doesn't work.


Need interdependent button CHANGE and select CLICK functionality by using jQuery. I need to combine them on document ready?

Question: The script is fine as far as the over all functionality is considered, but the only problem is the select option value disappeared (I believe #selectbox value is not properly selecting the value) when select from option or via button. Basically I need to equal .btn-itemlist and #selectbox value and move both of them simultaneously. Keeping in mind these values, are generated dynamically and total numbers of both values are same on load. I want both of them dependent on each other on document.ready and remain same by clicking and selecting.
$(document).ready(function() {
$('.btn-itemlist[value="0"]').click();

$(".btn-itemlist").click(function(e) {
   var _self = $(this),
   value = _self.val();
  $("#selectbox").val(value).trigger('change');
});

$('#selectbox').change(function(e) {
   var _self = $(this),
   value = _self.val();
    $('.btn-itemlist[value="'+ value+'"]').click();
});

});

Previously, I made the following script and this works fine only when one function is used either #selectbox or .btn-itemlist click(). Simply you can say either select become dependant on click or click over select but both of them are not interdependent. When I use both of them with document on.load only first parts executes (in this case .btn-itemlist) and jQuery starts throwing an error of:

" Uncaught RangeError: Maximum call stack size exceeded"

and this error further increases on every click or select of an option.
$(".btn-itemlist").click(function() {
  q = ($(this).attr('value')),
  $("#selectbox").val(q).trigger('change');
});

$('#selectbox').change(function()
{
val1 = $("#selectbox").val();
$('.btn-itemlist[value="'+ val1+'"]').click();
});

Here is the JSFiddle
JS Fiddle Demo
Comment: Please provide a [mre], including the HTML on which this code runs. Just enough to show us what you mean, and reproduces the problem. You can use [Stack Snippets](https://meta.stackoverflow.com/q/358992/215552) to produce something that runs here on Stack Overflow (the icon looks like `<>` in the editor toolbar).
Comment: Thanks for quick response. Here is the JS Fiddle
https://jsfiddle.net/hilalrehan/1knszvup/2/
Answer: just change
$(".btn-itemlist").click(function(e) {
   var _self = $(this),
   value = _self.val();
  $("#selectbox").val(value).trigger('change');
});

to
$(".btn-itemlist").click(function() {
  q = $(this).attr('value');
  $("#selectbox").prop('selectedIndex', q);


What thread calls the delegate when using iPhone CoreLocation framework?

Question: If I create CLLocationManager, assign it's delegate, and finally tell it to start updating, exactly which thread is calling the delegate? Some system thread?
Answer: Since the documentation doesn't say anything, you can safely assume that the delegate will be called from the run loop (main thread or UI thread, depending on which term you prefer).
Comment: well, that would explain the deadlock I experienced then!


How to practice sevenths?

Question: I'm trying to figure out a good way to add sevenths to my practice. One thing I did with triads is I'd take a scale, and then starting from each note in the scale play the arpeggio for the corresponding diatonic triad chord (I, ii, iii, etc).
I'd like to get better at sevenths though. Should I just add a sevenths to my arpeggio practice. For example in major, instead of diatonic triads play diatonic sevenths like I7, ii7, iii7, IV7, V7, vi7, viiø7.
Is this a good way to practice sevenths or maybe there's something better? My goal is to develop more harmonic ideas for improvisation/composition as well as being able to jam with others and have more "vocabulary" than just triads. I mainly play pop and some classical. Jazz isn't really my thing, but I like the "dreamy" sound of sevenths at times. If you saw my last question it was about the arpeggio section of Dance of the Sugar Plum Fairy and sevenths are used quite a lot in there. That type of sound is what I'm drawn to. I figure that after triads the most important chords to know are sevenths.
Comment: What specifically are you wanting to use sevenths for? Are you wanting to be able to arpeggiate them like you do the triads? Are you wanting to learn to use them in left hand accompaniment for jazz piano, for instance? Are you just wanting to be familiar with all the diatonic sevenths and how they're spelled, and what chord quality they are? This would help to know when giving you practice ideas.
Answer: I wouldn't even say you need to arpeggiate them. Just drill all your seventh chords in root position in every key (starting with diatonic sevenths, then experimenting with altered fifths, for instance).  But get to know them by heart. Know your dominant seventh, your supertonic minor seventh, etc. in every key by heart so you can reproduce them instantly on command.
Experiment with different inversions and voicings so you know them in and out.
A few tips:
1) As you go, just work on a few chords at a time. Don't try to tackle all the sevenths at once. Start with learning a couple (V7 and ii7 for instance) in every key, then when you've mastered those, add a couple more into the mix. Take your time to know them well.
2) The end goal should be to know the spelling (what notes are in them) of every chord in every key by heart, as well as to know how every kind of seventh chord (major, minor, major-minor, diminished, half-diminished, etc) sounds by ear. I realize this is a lofty goal, but will be very beneficial if you want full harmonic variety and freedom in improv.
3) As you learn them, begin substituting the sevenths in place of triads in your improv/jam sessions. You'll discover what inversions/voicings/progressions sound good by experience.
From there, you can move on to learning the beautiful family of  ninth and thirteenth chords, again starting simple before progressing to altered chords (raised/lowered fifths/ninths).
Happy practicing! Hope this helps!
Comment: @Tim I agree with your statement for the pop/classical music that OP is interested in. However it's worth mentioning that jazz/blues music uses almost exclusively sevenths, ninths, and thirteenths, and it's not unusual to play sevenths an entire song in a blues piece, for instance.
Comment: Warning. Do not try to use sevenths for every single chord, even if you could!!
Comment: The warning was for the OP, who patently has no interest in jazz. Well aware that extensions are de rigeur in jazz - use them all the time! Warning was for someone with a new toy...
Comment: @Tim I gotcha. And I didn't realize til after I answered they aren't interested in jazz...I think that was a later edit that I missed. But it's all good. Great input, thanks for adding that caveat. That's the great thing about this community -- when an answer needs clarifying, others can add their own bits and pieces!
Answer: A good way to learn anything musical is to, you know, play music. It helps if you like the music so it doesn't become a chore.
If you like the sounds of something, find a song that uses that, and learn to play that song.
In this case find a song that uses at least one 7th chord. Learn to play it. Once you have it down in one key, transpose it to another key.
So if you have a song that used C7 and G7 transpose it to up a step and play those new chords D7 and A7 in context. rinse and repeat.
If you find that you are struggling with one aspect of playing the part of the song that contains the 7th, try to come up with some exercises that will help.
For example (building off your example in the question), if you find they are arpeggiating and you are struggling with that, work on arpeggio exercises with 7ths.
Answer: First you need to establish what '7ths' there are.
Major, minor, dominant, diminished, half-diminished, minor/major.
All are made up only slightly differently, but they're not really interchangeable. Each works best in one place in the harmony.
So, use the diatonics first - I-maj7, ii-m7, iii - m7, IV - amaj7, V - dom 7, vi - m7, vii - dim7.
Learn the make-up (spelling) for each, and how each may or may not fit in particular keys.
Of course practise them in arpeggio form, also as block chords and inversions. Then experiment with known songs to find where they're most effective. An obvious, well used ploy is going from I to IV. A dominant using I as base will sound like it's inevitable that IV will follow!

How to practice sevenths?


Play a MIDI, except use a WAV on a single channel

Question: I used Cubase on the Atari ST in the 90s, and now a little bit of GarageBand on the Mac and Maschine/Kontakt, so I do have some understanding about computer DAWs and such but still I cannot find an easy way to do this.
For fun, I wanted to play a song (of which I have the MIDI) but, instead of playing the melody (on channel 4, just to be specific), I want to play a WAV file according to the notes on channel 4.
Suppose the WAV file contains just a "uh", I want to play that "uh" like if the standard WAV corresponds to the central C on the keyboard, and played accordingly depending on the note on channel 4, so that it can "sing".
Basically, instead of sending out a "note on" command on the MIDI port, I want to play my WAV "tuned" to the note on channel 4.
Hope it's clear :)
Thank you
Comment: You're looking for a *sampler*.
Comment: Kontakt ***is*** a sampler, but not the easiest to code yourself.
Answer: Actually, you still want to use MIDI notes, but you need to send or route them to a software sampler or a hardware MIDI expander (some plugins may even be found named software expanders).
You will first have to load your PCM file into your sampler or expander and configure it so that it sound as you wish.
You then can go further by adding more sounds to get a more interesting result:

one dedicated sound for every pitch
multiple sounds per pitch to address different velocities

On this French Wikipedia page, you can have a look at some hardware expanders: https://fr.wikipedia.org/wiki/Expandeur
(be carefull though, the term expander has multiple meanings in music and audio vocabulary)
In an Garage Band environment, you should try the instrument called AUSampler. Ableton Live provides Simpler and Sampler. There are also many free (Zampler RX, Serato Sample, Halion Sonic SE, ...) and non-free (Halion, Kontakt, ...) VSTs available on the internet.


How to minimize $f(x,y,z)$ on a closed subset of $\mathbb{R}^3$?

Question: Consider the minimization of $$f(x,y,z) = (x-\frac{y}{2})^2 + \frac{3}{4}(y-2)^2 +z^2 -3$$ on the set $$\{(x,y,z)\in\mathbb{R}^3|x^2+y^2\leq1\}$$
I'm trying to use the first and second order necessary conditions ($\nabla f \cdot v \geq 0$ and $v^T\nabla^2f v\geq 0$ for feasible $v$) to identify minimum points.
I think I've narrowed down the set of feasible $v$ to $v=\begin{bmatrix}u\\v\\w\end{bmatrix}$ such that $xu+yv <0$.
And I was able to show that $\nabla^2f(x,y,z)$ is positive definite (determinant of all leading minors are strictly positive).
However, I can't figure out how to generate a system of equations to actually identify any "critical" points.
Any suggestions would be appreciated. Thank you!
Comment: I would try at first without the condition $$x^2+y^2\le 1$$ to find a minimum. After this use the condition $$x^2+y^2=1$$
Comment: Splitting the cases this way was a huge help! Figured it out, thanks!
Answer: We need to look at first at the "interior points" s.t. $x^2+y^2<1$ by the condition $\nabla f=0$.
I've found no critical interior points.
Then we need to check the points $x^2+y^2=1$ using directly that condition.
That should lead to the minimization of $g(x,y)=xy+\frac32 y$ under the given condition.


List Drush specific add ons, plug ins, extensions, or modules to use drush dl in automated script

Question: I'm writing a really basic bash script and want use drush dl to download the Drush extras add on.
drush dl drush_extras
But I need to check whether drush extras is installed before I try to install it (and then use it) because it prompts the following text.

Install location C:\cygwin64\home\USER/.drush/drush_extras already exists. Do you want to overwrite it? (y/n):

How do I determine whether a drush add on/plug in/module (not sure what you call it) exists? So I handle that use case?
I'm trying to automate configuration, starting with assigning blocks to regions, and I have to make it work on Windows (first) and Linux. So I'm using Cygwin and Drush on Windows. There's probably different approaches, but this seems OK.
Comment: Welcome to Drupal Answers! So far, you stated facts, but it's not clear what you need to know, or (in other words) what you don't understand in achieving the described task.
Answer: I would personally lean towards simply installing with -y. Adding -y onto the command you've listed will return Y accepting the default on any prompt that comes up (like the one you mention).
drush dl drush_extras -y
If you still want to check if it's installed, you can check if the directory exists,
if [ -e $HOME/.drush/drush_extras ]; then
  # some logic here
fi

This won't help you if the directory is empty though.
Another option is checking the output of
drush someCommand -h

Where someCommand is a command provided by drush_extras. You can compare the output of a valid one to an invalid one. If they match, it's not installed.
Comment: @ja_him It's a drush built in feature. Try running `drush` or `drush -h`. I believe it comes up towards the beginning of the output. `--yes` is the expanded version of the command.
Comment: "Adding -y will return Y accepting the default on any prompt that comes up (like the one you mention)." I've looked [here](https://drushcommands.com/drush-7x/pm/pm-download/) but can't see the `-y` option, is this specific to `drush dl` or a general feature of shell commands?


how to get the user id logged in and register along with the post he's doing?

Question: I am developing a web application and am doing the relationship between tables. I want to do the following: The user will register a printer related to it, the program will get the data that he put in the form and save in the database along with his id to refer to in the other table when I call him.
I tried to do the following:
public function savePrinter(Request $request){
        $user = $request->user()->id;

        Printers::create($request->all(), $request->user()->id);

        return redirect()->back();
    }

Printers.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Printers extends Model
{
    protected $fillable = [
        'id',
        'name_printer',
        'link_printer',
        'printer_id'
    ];

    protected $table = 'printers';
}

I want the program to save in the printers table the id of the logged in user to do the reference
Obs

(the program is saving the correct printer name,I just can not save
  the logged user's id in printer_id)
Comment: In your printers table, do you have `user_id` column?
Answer: In  Users Model add this relationship
public function Printer() {
     return  $this->hasMany(Printers::class,'printer_id','id');
}

now in your controller add this line

 $user = $request->user()->Printer()->create($request->all());


Add custom value in session

Question: How can I add value in drupal session. I am adding value using $_SESSION = 'my value', but once trying to print $_SESSION variable it return blank.
Comment: It has to be an array. Collins' answer looks right.
Answer: Drupal bootstrap takes care of session_start for you, so you should be able to define sessions like...
<code>$_SESSION['my_data'] = 'my value';
</code>
You can also add the following in settings.php to determine the life span of the session
<code>ini_set('session.cache_expire',     200000);
</code>

Add custom value in session


Line integrals and parametrization

Question: I've just learned about line integrals, and I need some help understanding an example problem in my textbook.
The question is supposed to be really easy. Integrate $f(x,y,z)=x-3y+z$ over the line segment $C$ joining the origin to the point $(1,1,1)$.
I've been told to parametrize the line segment first, and this is the part I'm confused about. My knowledge on parametrizations is a bit wobbly....  From what I remember, I thought $ \bar{r}(t)$ would be $ \bar{r}(t)=<1,1,1> + t<1,1,1>= <1+t,1+t,1+t>=(1+t) \hat{i}+(1+t) \hat{j}+ (1+t) \hat{k}  $
but my textbook says $ \bar{r}(t)=t\hat{i}+t\hat{j}+t\hat{k}$, with $0 \leq t \leq 1$
Why is this? what does this mean? I would be grateful for a bit of help!
Comment: The line segment joins the origin to the point $(1,1,1)$, so the y-intercept is $(0,0,0)$ not $(1,1,1)$. Therefore, the position vector in your example should be $\bar{r}(t)=<0,0,0> + t<1,1,1> = t\hat{i} + t\hat{j} + t\hat{k}$
Comment: oh right!!!! gosh I am so stupid. of course it is!! thank you!! @Timmy
Answer: Basically, when you parametrize the line segment, the form of the vector is $$\vec{r}(t) = <x_0, y_0,z_0> + t<x_1, y_1,z_1>$$ Where $(x_0, y_0, z_0)$ is your initial point, and $(x_1, y_1, z_1)$ is your final point, and $t$ always have to be from $0\le t \le 1$ (do you see why?).
Think back to lines and how you parametrized them. This is no different, except there's a limit of $t$.
EDIT: The vector $<x_0, y_0,z_0>$ is the vector to your initial point, and the vector $<x_1, y_1,z_1>$ is the displacement vector between your two points, and the reason $t$ is bounded by $0\le t \le 1$ is because when $t = 0$, we get our initial point, and then when $t = 1$, we get our full length line segment, and all other values of $t$ are for all the other line segments that are pieces of the full length one.

Line integrals and parametrization


Pegar o id do array dentro da sessão

Question: Tenho a sessão $_SESSION['linha_pedagio'][] disposta assim:
Array
(
    [0] => Array
        (
            [0] => 2
            [1] => CGO - RJA (via Magé)
            [2] => 96.30
            [3] => 2
            [4] => 9681
        )

    [2] => Array
        (
            [0] => 4
            [1] => RJA - CPQ
            [2] => 224.70
            [3] => 2
            [4] => 493
        )

    [3] => Array
        (
            [0] => 9
            [1] => RJA - BMA
            [2] => 72.00
            [3] => 1
            [4] => 5270
        )

    [4] => Array
        (
            [0] =>
            [1] => BMA X B. PIRAI
            [2] => 20.00
            [3] => 1
            [4] => 5027
        )

    [5] => Array
        (
            [0] => 2
            [1] => CGO - RJA (via Magé)
            [2] => 96.30
            [3] => 2
            [4] => 4493
        )

)

Porém preciso excluir um dos arrays da $_SESSION, que sejam o 0, 2 ou 5.
Eu utilizei o unset($_SESSION['linha_pedagio'][$id]); mas coleto o valor errado para a variável $id,
Há uma forma de pegar esse id principal?
Valores: 0, 2, 3, 4 e 5.
Answer: Você pode "capturar" esse id da seguinte forma:
foreach($_SESSION['linha_pedagio'] as $id => $objeto){
    if($id == 0 || $id == 2 || $id == 5){
        unset($_SESSION['linha_pedagio'][$id]);
    }
}

Comment: Sim, correto @thiagofred
Comment: Obrigado Julyano... fazendo isso `$id => $objeto` ainda posso utilizar os outros dados do array né?
Ex: `$rota = $objeto[1]; $valor = $objeto[2];`

Pegar o id do array dentro da sessão


returning array results after in_array check?

Question: I am trying to read in a file that has HTML list items with ++++ as delimeters. Basically, I am trying to search through each item in the array for the text of "nmb" (which is stored in the class) and then display all of the items IN the array that have "nmb".  However, my current code does not work. It displays... NOTHING.  And gives no errors.  What am I missing here?
<?php
$term = "nmb";
$f_contents = file_get_contents("../includes/inc-condo-list.php"); //get the entire file
$array = explode("++++",$f_contents); //explode (create an array) seperated by new line elements
$datotal = count($array);  //gives me a TOTAL count.. maybe for later use

foreach ($array as $str ){    //go through each item in array
    if(!in_array($term, $array)) {
    echo $str;
    }
}

unset ($array);

?>

Here is an example of the list items being brought in from reading the file.
  ++++

     Some Link

        4 & 6 Bedrooms

    ++++

     Some Link

        4 & 6 Bedrooms

    ++++

Any help would be MORE than appreciated! Thank you.
Answer: in_array looks for an exact value match. Use something like this instead.
foreach ($array as $str ){    //go through each item in array
    if(strpos($str, $term) === false) { // if it's not present
        echo $str;
    }
}

Comment: And you're looking for it in the entire array, once for each element of said array.
Comment: Not quite sure I get what you mean, could you re-phrase that? :)
Comment: Of course - your exploded value would be an array with an element for every section between `++++`s. `in_array` looks for `$term` in every element in the given array (and so would look in every section). In essence, the answer to `!in_array($term, $array)` would be the same regardless of how many times through the loop you go. Did I make any sense then? (When I say you - I mean the OP).
Comment: Oh, gotcha - yes, I just corrected that because he was just checking the wrong thing. I wasn't the main problem, but it definitely wasn't helping :P
Comment: Thanks Joe! Smooth as silk. :) And thank you Adam as well for that clarification.


Neyman-Pearson lemma. Doubt on the text of the lemma

Question: In my book:
$\mathbf{X}=(X_1,\ldots,X_n)$
$f(\mathbf{x})$ is the joint density, where $f$ is either $f_0 \text{ or } f_1$.
Suppose we want to test $H_0: f=f_0$ or $H_1: f=f_1$. The test, whose test function is
$$\phi(\mathbf{X})=1\text{ if }\frac{f_1}{f_0}\geq k;$$
$$\phi(\mathbf{X})=0 \text{ otherwise,}$$
(for some $0<k<\infty$) is a most powerful test of $H_0$ versus $H_1$ at level $E_0(\phi(\mathbf{X}))$.
My question is how is $k$ defined? Can I interpret the lemma as if $\forall k \in (0,\infty)$ there will be a test function $\phi(\mathbf{X})$ such that it will determine the size for which the test with test function $\phi(\mathbf{X})$ is most powerful?
I'm just trying to understand which kind of relationship $k$ and the size of the test have between each other.
EDIT:
Here is a citation from the book I'm using: «the Neyman-Pearson lemma as stated here does not guarantee the existence of an MP $\alpha$ level test but merely states that the test that rejects $H_0$ for $T(X)\geq k$ will be an MP for some level $\alpha$» This makes me want to interpret as $\forall k \exists \alpha$. May I?
Comment: Please don't cross-post your questions here and on stats.stackexchange.
Answer: I don't think your interpretation is correct. What the lemma is saying is that if you use the likelihood ratio as your test function (or something that is equivalent to it), then it is the most powerful test of the null vs. alt. hypothesis for a particular type I error rate. In particular, it has the highest power of all tests that have a significance level of $E_0(\phi(\mathbf{X}))$
The value $k$ defines the "rejection region" of the likelihood ratio test, and it determines the expected value of $\phi(\mathbf{X}): \phi(\mathbf{X})=1\text{ if }\frac{f_1}{f_0}\geq k; \;\;0 \;\;\text{otherwise}$
This is spelled out by the expression $E_0(\phi(\mathbf{X}))$ in the text; which says that the expected value of the test function un*der the null distribution* (i.e., that's why the subscript is $0$) is the level of the test. We can make this clearer by re-writting this as $E_0(\phi(\mathbf{X})|k)$ to make it clear that it depends on $k$. Now, $E_0(\phi(\mathbf{X})|k)=\alpha=$Type I error rate (as per Michael Hardy) in typical "hypothesis test" terminology.
The larger you make $k$, the smaller you  make  $E_0(\phi(\mathbf{X})|k)$ and hence you reduce your chances of rejecting the null when it is in fact true.
Comment: @Anoldmaninthesea. Your latter formulation is correct. Each $k$ can be associated with a most powerful test of level $\alpha$ for some $\alpha$
Comment: Thanks for your answer. If the size isn't given, can I choose any $k \in (0,\infty)$?
Comment: @Anoldmaninthesea. For a given $f_0,f_1$, each value of $k$ determines a specific test "size" or type I error rate. if you don't care about the type I error rate, then why do any hypothesis test at all? Usually, you want to find $k:E_0(\phi(\mathbf{X})|k)\leq\alpha$ where $\alpha$ is your desired test size.
Comment: Here is a citation from the book «the Neyman-Pearson lemma as stated here does not guarantee the existence of an MP$\alpha$ level test but merely states that the test that rejects $H_0$ for $T(X)\geq k$ will be an MP for some level $\alpha$»
This makes me want to interpret as $\forall k \exists \alpha$. May I?
Answer: One chooses $k$ usually by deciding how much probability of Type I error one will tolerate (i.e. falsely rejecting $H_0$), balanced against the power of the test, which is the probability of rejecting $H_0$ when $H_0$ is false.  And that is a subjecctive economic decision.
Comment: ,I thank you for your answer.
Your answer seems to be from a more applied perspective. I was looking for an answer more based on the the text of the lemma itself. Could you help me in that way?


Propriedades do material design não aparecem em aparelho de API 19

Question: Eu adicionei a biblioteca de suporte para APIs abaixo da 21 e estou testando a propriedade elevation nos meus componentes.
Na visualização do layout, quando clico na aba de design, eu consigo ver a elevação mas quando executo para meu smartphone não muda nada, continua tudo sem elevação nenhuma.
Antes de adicionar o suporte eu não conseguia nem usar a propriedade, então não entendo como agora consigo usar e não funciona.
Adicionei as linhas em dependencies, no gradle:
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.android.support:design:22.2.1'

Answer: No que diz respeito ao "Material Design" nem tudo é suportado pela appcompat.
No caso da elevation, ela só é parcialmente implementada.
A appcompat permite a utilização da propriedade, mas ela não é renderizada em versões inferiores à API21.
O método setElevation(), da classe android.support.v4.view.ViewCompat, é implementado da seguinte forma(sem nada dentro):
@Override
public void setElevation(View view, float elevation) {

}

Assim, o código é compatível com as versões inferiores, mas o efeito da elevation só é visível em dispositivos Android com API21 ou superior.
O método é reescrito na implementação referente à API21 assim:
@Override
public void setElevation(View view, float elevation) {

    ViewCompatApi21.setElevation(view, elevation);

}

Comment: Então não existe uma maneira de eu ter esse efeito do elevation em APIs inferiores a 21? Porque eu consigo perceber a sombra em alguns aplicativos que tenho instalado no smartphone. Eles usaram algum outro recurso?
Comment: Sim, possivelmente recorrendo a *9-Patch drawables*, veja [isto](https://github.com/h6ah4i/android-materialshadowninepatch)
Comment: Muito obrigada! Só mais uma dúvida: usando esses efeitos eu não preciso do elevation do Material né?
Comment: Sim, segundo diz lá correm da API9 em diante