Search functionality in fragment with recycler view

Question: Below is my code
package com.mypoolin.hybrid_upi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.builder.Builders;
import com.mypoolin.hybrid_upi.objects.Banks;
import com.mypoolin.mypoolinsupportlibrary.util.Log;

import java.util.ArrayList;

//import com.bumptech.glide.Glide;

public class ListFragment extends Fragment {
    private static final String TAG = "BankListFragment";
    public static boolean networkFailure = false;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    // ArrayList<HashMap<String, String>> bankData = new ArrayList<>();
    ArrayList<Banks> bankData = new ArrayList<>();
    ArrayList<Banks> bankDataOriginl = new ArrayList<>();
    RecyclerView recyclerViewBankList;
    EditText searchText;
    ImageButton imageButtonClearSearch;
    SwipeRefreshLayout swipeRefreshLayoutBank;
    String transactionType = "T";
    // TODO: Rename and change types of parameters
    int confirmed = 0;
    int upi = 0;
    int forWalletRedeem = 0;
    private OnFragmentInteractionListener mListener;
    private RecyclerView.Adapter mAdapter;

    public ListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @return A new instance of fragment BankListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BankListFragment newInstance(ArrayList<Banks> param1, String transactionType) {
        BankListFragment fragment = new BankListFragment();
        Bundle args = new Bundle();
        args.putSerializable("bankList", param1);
        args.putString("transactionType", transactionType);
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            if (getArguments().containsKey("bankList")) {
                bankDataOriginl = (ArrayList<Banks>) getArguments().getSerializable("bankList");
                bankData = (ArrayList<Banks>) getArguments().getSerializable("bankList");
            }
            if (getArguments().containsKey("transactionType")) {
                transactionType = getArguments().getString("transactionType");
            }
        }
        //  MyPoolinUtil.hideSoftInput(getActivity());

    }

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

    }

    private void loadView(View view, ArrayList<Banks>list) {
        Log.d(TAG,"test list:"+list);
        searchText = (EditText) view.findViewById(R.id.searchEditText);
        imageButtonClearSearch = (ImageButton) view.findViewById(R.id.imageButtonClearSearch);
        imageButtonClearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchText.setText("");
            }
        });

        swipeRefreshLayoutBank = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout_bank_list);
        recyclerViewBankList = (RecyclerView) view.findViewById(R.id.bankListRecyclerView);
        //recyclerViewBankList.addItemDecoration(new DividerItemDecoration(getActivity().getApplicationContext(), DividerItemDecoration.VERTICAL_LIST));
        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        recyclerViewBankList.setHasFixedSize(true);
        // use a linear layout manager
        recyclerViewBankList.setLayoutManager(new LinearLayoutManager(getActivity()));
        // create an Object for Adapter
        mAdapter = new BankDataAdapter(getActivity().getApplicationContext(), bankData);
        // set the adapter object to the Recyclerview
        recyclerViewBankList.setAdapter(mAdapter);
        //recyclerViewBankList.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        try {
            searchText.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) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.toString().isEmpty()) {
                        imageButtonClearSearch.setVisibility(View.GONE);
                    } else {
                        imageButtonClearSearch.setVisibility(View.VISIBLE);
                    }
                    String name = s.toString();
                    Log.e(this.getClass().getName(), name);
                    swapList(name);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void swapList(String name) {
        ArrayList<Banks> newList = new ArrayList<Banks>();
        if (name.trim().isEmpty()) {
            //this.contactList=contactListoriginal;
            mAdapter = new BankDataAdapter(getActivity().getApplicationContext(), bankDataOriginl);
            // set the adapter object to the Recyclerview
            recyclerViewBankList.setAdapter(mAdapter);
        } else {
            mAdapter = new BankDataAdapter(getActivity().getApplicationContext(), bankData);
            for (Banks c : bankData) {
                if (containsName(name, c.getBankName())) {
                    newList.add(c);
                }
            }
            mAdapter = new BankDataAdapter(getActivity().getApplicationContext(), newList);
            recyclerViewBankList.setAdapter(mAdapter);
            mAdapter.notifyDataSetChanged();
        }
    }

    public boolean containsName(String s, String name) {
        if (s != null && name != null) {
            int l = s.length();
            if (name.length() >= l && name.substring(0, l).equalsIgnoreCase(s)) {
                return true;
            }
            else {
                String[] names = name.split("[\\s]+");
                for (String n : names) {
                    if (n.length() >= l && n.substring(0, l).equalsIgnoreCase(s))
                        return true;
                }
            }
        }
        return false;
    }

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

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

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

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private class BankDataAdapter extends RecyclerView.Adapter<BankDataAdapter.ViewHolder> {
        Context context;

        private ArrayList<Banks> bankList;

        public BankDataAdapter(Context context, ArrayList<Banks> contactList) {
            this.bankList = contactList;
            this.context = context;
            //ImageLoader imageLoader = ImageLoader.getInstance();

        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_row_bank_list, null);

            // create ViewHolder

            ViewHolder viewHolder = new ViewHolder(itemLayoutView);

            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            final int pos = position;
            viewHolder.textViewBankName.setText(bankList.get(pos).getBankName());
            //  viewHolder.imageViewBankLogo.setImageURI(Uri.parse("http://hybridsdk.mypoolin.com/get_bank_image/" + bankList.get(pos).getBankCode()));
            /*Glide.with(context)
                    .load("http://hybridsdk.mypoolin.com/get_bank_image/"+bankList.get(pos).getBankCode())
                    .asBitmap()
                    //.error(MyPoolinUtil.getDrawableFromText(position, bankList.get(position).getBankName(), context))
                    .into(viewHolder.imageViewBankLogo);*/

            Ion.with(viewHolder.imageViewBankLogo)
                    //.error(MyPoolinUtil.getDrawableFromText(position, bankList.get(position).getBankName(), context))
                    .load("http://mypoolin.com/hybrid_upi/get_bank_image/" + bankList.get(pos).getBankCode());
        }

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

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

            public TextView textViewBankName;
            public ImageView imageViewBankLogo;

            public ViewHolder(View itemLayoutView) {
                super(itemLayoutView);
                imageViewBankLogo = (ImageView) itemLayoutView.findViewById(R.id.imageViewBankLogo);
                textViewBankName = (TextView) itemLayoutView.findViewById(R.id.textViewBankName);
                itemLayoutView.setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
                int position = getAdapterPosition(); // gets item position
                if (position != RecyclerView.NO_POSITION) { // Check if an item was deleted, but the user clicked it before the UI removed it
                    Banks user = bankList.get(position);
                    // We can access the data within the views
                    //  Toast.makeText(context, bankList.get(position).getBankName() + s, Toast.LENGTH_SHORT).show();
                    Intent returnIntent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putString("bankName", bankList.get(position).getBankName());
                    bundle.putString("bankCode", bankList.get(position).getBankCode());
                    bundle.putString("transactionType", transactionType);

                    returnIntent.putExtras(bundle);
                    getActivity().setResult(Activity.RESULT_OK, returnIntent);
                    getActivity().finish();

                }
            }
        }
    }

}

I get banklist data from getExtra in onCreate method of fragment and I am saving banklist data to Arraylist as bankdata and bankoriginaldata and my problem is that I am not able to get banklist data inside swaplist method and the search functionality is not working. In swap list method before foreach loop bank data is getting null but I have bank data in load view method but not in swap list. Can any one tell what is happening?
How to fix the above issue? And I would like to know why the bank data is getting null inside swap method and how to access it.
Will the search functionality in my case work as expected?
Comment: Please, edit your code.
Comment: not clear on editing?
Comment: There are non code text on the top of your code.
Comment: Removed non code text
Answer:   private void swapList(String name) {
        bankData.clear();
        if (name.trim().isEmpty()) {
            bankData.addAll(bankDataOriginl);
        } else {
            for (Banks c : bankDataOriginl) {
                if (containsName(name, c.getBankName())) {
                    bankData.add(c);
                }
            }
        }
        mAdapter.notifyDataSetChanged();
    }

change your swapList method.
change 1 more thing, in your oncreate method
if (getArguments() != null) {
            if (getArguments().containsKey("bankList")) {
                bankDataOriginl = (ArrayList<Banks>) getArguments().getSerializable("bankList");
            }
            if (getArguments().containsKey("transactionType")) {
                transactionType = getArguments().getString("transactionType");
            }
        }

And call swapList("") from loadView.
Comment: Dont no for some reason i dont get bankData and bankDataOriginl vales inside swapList method.foreach loop will  be empty.
Comment: containsName method is not getting called


Why is this OpenGL-es texture bound to hills in cocos2d 2.0 torn?

Question: This question is related to Repeating OpenGL-es texture bound to hills in cocos2d 2.0
After reading the answers posted in the above post, I've used the following code for computing the vertices and texture coordinates:
    CGPoint pt0,pt1;

    float ymid = (p0.y + p1.y) / 2;
    float ampl = (p0.y - p1.y) / 2;
    pt0 = p0;
    float U_Off = floor(pt0.x / 512);

    for (int j=1; j<_segments+1; j++)
    {
        pt1.x = p0.x + j*_dx;
        pt1.y = ymid + ampl * cosf(_da*j);
        float xTex0 = pt0.x/512 - U_Off;

        _vertices[vertices++]=CGPointMake(pt0.x, 0);
        _vertices[vertices++]=CGPointMake(pt0.x, pt0.y);

        _texCoords[texCoords++]=CGPointMake(xTex0, 1.0f);
        _texCoords[texCoords++]=CGPointMake(xTex0, 0);

        pt0 = pt1;
    }
    p0 = p1;

But unfortunately, I still get a tear / misalignment in my texture (circled in yellow):

I've attached dumps of the arrays of vertices and texcoords
I'm new to OpenGl, and can't figure out where the miscalculation is. How do I prevent the line (circled in yellow in image) from appearing ?
EDIT: My texture is either 1024x512 or 512x512 depending on the device. I use the following texture parameters:
ccTexParams tp2 = {GL_LINEAR, GL_LINEAR, GL_REPEAT, GL_CLAMP_TO_EDGE};

Answer: Most likely the reason is in non-continuous texture coordinates.
In texcoords dump you have the following coordinates:
(CGPoint) 0x34b0b28 = (x=1.00390625, y=0)
(CGPoint) 0x34b0b30 = (x=0.005859375, y=1)

It means that between these two points texture is mapped from 1 to 0 (in reverse direction). You should continue texcoords after 1.00390625 => 1.005859375 => ... Also, your texture must have power-of-two size and must be set up with REPEAT mode.
If your texture is in atlas and you cannot set REPEAT mode, you may try to clamp texcoords to [0; 1] range and place two edge points with x=1 and x=0 in the same position.
And, at last, if your texture doesn't change in x-axis you may set x = 0.5 for all points.
Comment: Reto Koradi, there is support of NPOT textures only for `GL_CLAMP_TO_EDGE` wrapping mode (internally NPOT texture is filled into POT memory area, AFAIK).
Comment: ES 2.0 supports non-power of two textures as long as mipmapping is not enabled. Many implementations also have the necessary extension of full NPOT support.
Comment: Good point, I had forgotten about the limits on wrap modes for NPOT textures. I assume that most modern GPUs support NPOT textures natively. But the ES 2.0 specs were probably written to make life easier for ones that don't. ES 3.0 lifts these restrictions on NPOT textures.


How to compute a confusion matrix derived from multiple columns?

Question: I have got two DataFrames for which I would like to compute a confusion matrix.
The below is an example of how 'df_responses' is structured:
Question 1      |  Red  |  Blue  | Yellow | None of the Above |
Participant ID  |       |        |        |                   |
1               |   1   |    1   |    1   |       0           |
2               |   0   |    0   |    0   |       1           |
3               |   1   |    0   |    1   |       0           |

And, the below is an example of how 'df_actual' is structured:
Question 1      |  Red  |  Blue  | Yellow | None of the Above |
                |       |        |        |                   |
1               |   1   |    0   |    1   |       0           |
2               |   1   |    0   |    1   |       0           |
3               |   1   |    0   |    1   |       0           |

Ideally, I would also like to create a new DataFrame that contains the True Positive and False Negative score for each participant as follows:
Question 1      | True Positive | False Negative |
Participant ID  |               |                |
1               |     2         |       0        |
2               |     0         |       2        |
3               |     2         |       0        |

I have tried (@John Mommers):
for x in range(len(df_responses)):
    tn, fp, fn, tp = confusion_matrix(df_responses, df_actual).ravel()
    print (f'Nr:{i}  true neg:{tn}  false pos:{fp}   false neg:{fn}   true pos:{tp}')

However, I get a
ValueError: multilabel-indicator is not supported.

Is there perhaps another way I can compute TP and FN?

Addition (data as text):
df_responses

{'Red': {1: 1, 2: 0, 3: 1},
'Blue': {1: 1, 2: 0, 3: 0},
'Yellow': {1: 1, 2: 0, 3: 1},
'None of the above': {1: 0, 2: 1, 3: 0}}

df_actual

{'Red': {1: 1, 2: 1, 3: 1},
'Blue': {1: 0, 2: 0, 3: 0},
'Yellow': {1: 1, 2: 1, 3: 1},
'None of the above': {1: 0, 2: 0, 3: 0}}

Comment: Yes, I've added it!
Comment: can you repost your data as text with `df.to_dict()`?
Comment: what is the true positive of participant 2
Comment: True positive of participant 2 is zero
Answer: You can create the df you want by e.g.:
df = pd.DataFrame()
df["tp"] = np.sum((df_actual == 1) & (df_responses == 1), axis=1)
df["fp"] = np.sum((df_actual == 0) & (df_responses == 1), axis=1)

Note this is not really a confusion matrix - in that case your rows are predicted and columns label values (or vice versa), with values as counts.  This may not be well-defined for multi-value label/responses, that's why you're getting the error with sklearn.
Answer: You can't use sklearn function confusion_matrix in this way because it only supports one-dimensional labels, and in your case you have four labels. That's why you're getting the error multilabel-indicator is not supported.
So you have to pass each line of your data frame to this function.
for x in range(len(df_responses)):
   y_responses = df_responses.iloc[x].to_numpy()
   y_actual = df_actual.iloc[x].to_numpy()
   tn, fp, fn, tp = confusion_matrix(y_responses, y_actual).ravel()
   print (f'Nr:{i} true neg:{tn} false pos:{fp} false neg:{fn} true pos:{tp}')


Plotting negative values on a non symmetric log scale

Question: I have be trying to reproduce the graph shown here:  As you can see, the x-axis is a log scale that contains only negative values. I have looked online for some tips. Most of them dealt with the symlog function of matplotlib which I'd rather not use since the function I am trying to plot is only defined on ]-inf, 0[. So I am asking for another suggestion. Also, I would like the x-axis to only have the three ticks shown on the attachment (i.e., -10^0, -10^-2, -10^-4). Any tip is welcomed! Thank you!
The code for the function is:
x = np.linspace(-1, -0.0001, 10000)

a = 2*np.log((1+(1-16*20*x)**0.25)/2) +np.log((1+((1-16*20*x)**0.25)**2)/2) - 2*np.arctan((1-16*20*x)**0.25) + np.pi/2

b = 2*np.log((1+(1-16*10*x)**0.25)/2) +np.log((1+((1-16*10*x)**0.25)**2)/2) - 2*np.arctan((1-16*10*x)**0.25) + np.pi/2

c = 2*np.log((1+(1-16*5*x)**0.25)/2) +np.log((1+((1-16*5*x)**0.25)**2)/2) - 2*np.arctan((1-16*5*x)**0.25) + np.pi/2

y = (np.log(20/5) - a + b)/(np.log(10/5) - c + b)

Answer: You can plot y against -x in log scale and format the xticks accordingly:
from matplotlib.ticker import FuncFormatter
fig, ax = plt.subplots()
ax.plot(-x,y)
ax.set_xscale('log')
ax.invert_xaxis()
ax.set_xticks([1,1e-2,1e-4])
ax.xaxis.set_major_formatter(FuncFormatter(lambda x,pos: '$-\\mathdefault{10^{'+f'{int(np.log10(x))}'+'}}$'))

Output:
Comment: Hi! thank you so much for your reply! Could you please explain to me what the last line of code does?
Comment: @nalfahel basically the ticks are `1,1e-2,1e-4` and the last line of code labels the ticks with its negative values.


Is it possible to get report in sonarqube on how issues are handled?

Question: Is it possible to get report in sonarqube on how issues are handled? I.e. Comment, Assign, Confirm, Change Severity, Resolve, Won't Fix, and False Positive? We would like to get insight on how teams are using sonarqube.
Answer: To some degree this is immediately available in your issues page search facets. Go to the project and then to its issues page. Expand the Status and Resolution facets, which are collapsed by default, and you'll see issue counts of Fixed, False Positive, Won't Fix, and Confirmed issues. You can narrow the set and see sub-breakdowns by clicking on any facet value; the rest of the values will adjust accordingly.
What you won't see here are the number of issues with

comments
adjusted severities

In terms of issue assignment, you also won't get much help here because most issues are auto-assigned at creation, and the facets won't tell you how many have been re-assigned.


Casting objects

Question: In my code i have sth like:
class A
{
 enum eType
 {
  A=0,
  B,
  C
 };
 virtual eType ReturnType()
 {
  return A;
 }
};

class B : A
{
 eType ReturnType()
 {
  return B;
 }
}

class C : A
{
 eType ReturnType()
 {
  return C;
 }
}

and I have many objects B and C class on my MFC CList. How I can write method like this
auto GetObjectFromList
{
 return object;
}

which return appropriate object. I mean when on list will be object B class, this method should return object class B with methods from B class and when it will be object class C this method should return object class C with class C methods? I tried with auto from C++11 but I can't do it right.
Comment: Why isn't returning an (pointer to possibly) A sufficient?
Comment: can you give an example of how you would want to use this function?
Answer: I think you mean "class B : public A" right?
std::auto_ptr GetObjectFromList()
{
    return std::auto_ptr( new B ) ;  // you can new C if you want to return a C
}

Comment: Since OP seems to be using C++11, and `auto_ptr` is deprecated, maybe better to use `unique_ptr`.
Answer: First, you say that you have a collection of B and C. if you will not have an instance of A class, make it pure virtual by
virtual eType ReturnType() = 0;
Second, you need to make the inheritance by:
class A : public B
Then for the question, you will need to use dynamic_cast<> to see which instance is stored at the index you are looking for.

Casting objects


How should I troubleshoot and unclog an outdoor drain?

Question: Our back concrete patio directs water to a nearby outdoor drain.  The drain consists of what seems to be a 5 Inch green PVC pipe with a plastic grate cover that sticks out of the ground a few inches.
The drain pipe goes down into the ground 8 - 10 inches and then turns sharply so that the drain is parallel to the side of our house and going towards the front of the house (presumably exiting out towards the street). I'm not sure where the drain comes out (I've never seen this drain work and it's been clogged since we bought the house.
Since the drain doesn't work, water on the back patio has no where to go (fun fun fun).  I need help/advice on how to troubleshoot and correct this before rain season.
I was initially thinking using a hose or auger to see how far down the clog is. But if/when I do find the clog, I'm not sure how to fix it. Dig up the entire pipe?
I was also thinking of pouring water down the drain, trying to loosen it with the hose/auger, and checking the front of our house to see if I can find an exit point.
Any ideas, feedback, assistance would be greatly appreciated.
Comment: Have you tried snaking it out yet?
Answer: One frequent cause of backups is that a root from a tree or large bush has grown into the pipe. If that's happened to you, you'll need to dig up the clogged area to sever the root and then repair the pipe, or if it's a porous drain pipe, wrap it in a landscaping fabric.
As Tester says, use a snake to see what you can find. You can also measure the distance until the snake gets stuck to get an idea of where you need to dig. Pay attention to any bends you feel the snake making on the off chance it isn't a straight run to the front.
Once you have an idea from one side, I'd fill the drain up with water on a dry day and see if you can find the outlet. Then try snaking from that outlet as well since the clog may be a long one from sediment building up over time. Again, measure the distance, and now you'll have an overall area to check.
Answer: Just rent an auger and auger it out; simple to do.  Or hire an auger company to do it for you. And yes, the clog should definitely be flushed out of the pipe with water, while augering or after you/they think the clog is broken up.


Nginx 301 Redirect by variable

Question: I am setting up a 301 redirect server for the websites I host.  When I get a new customer, I don't want to go edit the domain list in the server block below.  Instead of a hard-coded domain in the nginx configuration, I want to redirect anydomain-here.com to 301 -> www.anydomain-here.com
All domains that are bare (ie domain.com) will be redirected to www.domain.com
server {
  server_name domain-requested.com;
  rewrite ^/(.*)$ http://www.domain-requested.com/$1 permanent;
}

In the example above, is it possible to change domain-requested to a variable?  This would allow the server to redirect any site that doesn't have a subdomain, such as www.
Answer: You could use a map to set a variable if a bare domain was used:
map $host $anydomain_here {
    # capture bare domain & store in variable $anydomain_here
    ~^(?<anydomain>[^\.]+)\.com$ $anydomain;
}

server {
    listen  80  default_server;
    server_name _;

    if ($anydomain_here) {
        # redirect if a bare domain was matched
        return 301 $scheme://www.$anydomain_here.com$uri;
    }
}

Comment: That works perfectly - I didn't even think of doing it that way!  Thanks for helping and giving me something to learn!
Comment: I'm glad you found it useful! Nginx is fun. There are so many different ways to do things.
Answer: You can get rid of at least one hardcoded domain name with Nginx 1.4.6:
 rewrite ^/(.*)$ http://www.$server_name/$1 permanent;

You could abstract that further by putting it an include file, which all server blocks include. You can't do better than that using Nginx alone, because rewrite is not allowed to be declared in the http context to apply to multiple server blocks.
Some other ideas to consider:

Use a templating system to manage your Nginx configs.
Many DNS provides provide HTTP redirection services, so their web servers would be the one receiving the request and receiving the redirects.

I have used both approaches above myself.  The downside to using an DNS providers for HTTP redirection is they don't handle incoming SSL requests, but that's only a downside if you were going to buy and install a second SSL cert just to handle HTTPS redirects on the second domain yourself.

Nginx 301 Redirect by variable


Accessibility focus goes in space in between the cells in a table view

Question: I am using a table view to show my data. There is no separator view in between the cells but when I switch on the voice over, the focus after on the cell, goes in the space between the two cells ans then on another swipe goes to the next cell.
I am not able to figure out what's going wrong.
The tableView is being imported from another framework, where it is working fine.
The separatorStyle for tableView is set to none.
Comment: Can you show your attempt please? what you want to achieve?
Answer: I just figured out the problem.
In the framework where tableView is populated, array.filter{ !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } was missing at one place where the tableView was passed with the array as data.
so, that focus was on cells with empty spaces as data.
Thank you


using std::move on unique_ptr on a type derived from templated base in C++1y

Question: I have problems when trying to use std::move semantics on templated types derived from another type. That is I get an error on the following example.
#include <memory>

template <typename T>
class A{
};

template <typename T>
class B:A<T>{
};

int main()
{
  std::unique_ptr<B<int> > bar(new  B<int>());
  std::unique_ptr<A<int> > foo (std::move(bar));
}

The error is on the line defining foo and it is:
In function 'int main()':
17:47: error: no matching function for call to 'std::unique_ptr<A<int> >::unique_ptr(std::remove_reference<std::unique_ptr<B<int> >&>::type)'

Obviously the non templated equivalent works fine.
Comment: [Cannot reproduce](https://ideone.com/yE7Hqc).
Comment: My bad, the real problem is that I am using private inheritance, I should have written class B: public A{};
Answer: B privately inherits from A, so there is no available conversion from B to A. Change to public inheritance and your code will compile.
template <typename T>
class B: public A<T>{};
//       ^^^^^^

In your example, A's destructor should be virtual, otherwise you'll have undefined behavior when foo goes out of scope because you'll be attempting to delete a B instance via an A *.
Answer: The problem is that I am using private inheritance.
When I change the definition of B to:
    class B: public
Things are working.
I am keeping this other solution just for the record:
For the lack of a better idea I am resorting to this:
std::unique_ptr<A<int> > foo ( (A<int> * ) new  B<int>());

Comment: Was this the answer, or did you mean to edit your question?
Comment: This does a reinterpret cast, which likely isn't what you want.


Image Rotation that works

Question: I'm not sure why this is so difficult under Ubuntu/Linux.  With Windows if I rotate an image in Windows Explorer or Window's image viewer, it retains that orientation everywhere in every application.  But with Ubuntu some applications rotate and save that rotation, but the rotation is ignored by other applications and visa versa.
My main problem is that I can't seem to get the orientation of my photos to be set correctly and the honored by all applications.  Apparently I hold my phone in different orientations when taking pictures and I'd like to fix them once and for all.  But there doesn't seem to be any simple tutorial on how to do this, just random posts about command line picture editing which doesn't work if I have to open the images up in a viewer, then close and run a command on them and open them up again to check...  This is madness.
The best I can find is cryptic discussions of Exif data, without any clear novice instruction.
Does someone have a simple tutorial on how to do this simply and permanently so that I can get my 1000's of pictures corrected once and for all?
Thank you
Comment: Do any of these suggestions work? https://help.ubuntu.com/community/Photos/RotatingPhotos
Comment: I haven't tried all of these, but the Image Viewer definitely does not work and Shotwell doesn't work either.  They just seem to rotate the Exif, but applications that don't honor Exif still display the picture in the wrong orientation.  I suspect Windows literally rotates the data so that it's always correct.

I will try some of these others though.  Thank you.
Answer: I ran into the same problem and scripted something:
It actually rotates all the data of image files in the current folder using imagemagick convert, and then resets the exif information using exiftool. You may need to add more cases, these here were sufficient for me.
#!/usr/bin/env bash

for filename in ./*; do
        rotation=$(exiftool -Orientation -n $filename)
        rotationnumber=${rotation: -1}

        if [ "$rotationnumber" == "1" ]; then
                echo "not rotated " $filename
        elif [ "$rotationnumber" == "6" ]; then
                echo "rotated 90 CW " $filename
                # rotate data
                convert $filename -rotate 90 $filename
                # set exif orientation to not rotated
                exiftool -Orientation=1 -n $filename
        else
                echo "unknown " $filename $(exiftool -Orientation $filename)
        fi
done
rm *_original

beware, it does delete the original data!

Image Rotation that works


Finding covariance matrix

Question: We have 2 dimensional normal distribution with PDF given by the formula:
$f(x,y)=\frac{1}{4\sqrt{5}\pi}\exp\left\{-\frac{1}{40}\left(9(x-1)^2+8(x-1)(y+1)+4(y+1)^2\right)\right\}$
Let $U_1=X-Y, \ U_2=X+Y+1, \ U_3=-X$.
Find the covariance matrix of vector $(U_1,U_2,U_3)$.
Firstly, let's rewrite this a bit:
$f(x,y)=\frac{1}{2\pi\sqrt{20}}\exp\left\{-\frac{1}{2\cdot20}\left(9(x-1)^2-2\cdot(-4)(x-1)(y+1)+4(y+1)^2\right)\right\}$
Hence
$\mathbf{C_X}=\begin{bmatrix} 4&-4\\-4&9\end{bmatrix}$
And now I have to find a transformation matrix (or however it's called).
$U_1=X-Y \\ U_2=X+Y+1 \\ U_3=-X$
I am not sure what should I do with this "$+1$".
$A_1=\begin{bmatrix} 1&-1&0\\-1&1&0\\ -1&0&0\end{bmatrix} \\ A_2=\begin{bmatrix} 1&-1&0\\-1&1&1\\ -1&0&0\end{bmatrix}$
And then do multiplication $\mathbf{C_{U_1,U_2,U_3}}=A\mathbf{C_X}A^T$
But which $A$ is the right one?
Edit: of course third raw of $\mathbf{C_X}$ is $(0,0,0)$, just like third column
Answer: I think you need to use the following fact (see wiki on affine transformations of multivariate normal): if $\mathbf{x}\sim\mathcal{N}(\mathbf{\mu},\mathbf{\Sigma})$ and $\mathbb{y}=\mathbf{c}+\mathbf{B}\mathbf{x}$, then $\mathbf{y}\sim\mathcal{N}(\mathbf{c}+\mathbf{B}\mathbf{\mu},\mathbf{B}\mathbf{\Sigma}\mathbf{B}')$. ($\mathbf{x}$, $\mathbf{\mu}$ are $n\times 1$, $\mathbf{\Sigma}$ is $n\times n$, $\mathbf{c},\mathbf{y}$ are $m\times 1$, $\mathbf{B}$ is $m\times n$.)
In your application, $\mathbf{\mu}'=\left[\begin{array}{cc}-1&1\end{array}\right]$ and $\mathbf{\Sigma}=\left[\begin{array}{cc}4&-4\\-4&9\end{array}\right]$. And you need $\mathbf{B}=\left[\begin{array}{cc}1&-1\\1&1\\-1&0\end{array}\right]$ and $\mathbf{c}=\left[\begin{array}{c}0\\1\\0\end{array}\right]$. The rest is algebra.
Comment: So in other words $A_1$ is the correct choice. Thank you.

Finding covariance matrix


Where's my room in Winterhold?

Question: Is it the one to right from main entrance to the apartments on the 1st floor? I've somehow missed the explanation where's exactly my room. That one at least doesn't say "Steal from" when I point to containers.
Answer: If you can't remember, your room is most easily detected by the bed.  All the other beds will say "Sleep (Owned)" - yours will not.
An important note - there will often be people hanging out in your room (Jzargo seems to frequent mine).
Comment: If you have a problem with people hanging out in your room, you should probably stop barging into theirs, putting buckets on their heads, and making off with all their valuables.
Answer: Your room in the college of Winterhold is the first room to the right when you enter the Hall of Attainment on the ground floor.
Answer: Yes it is.
If you want to be sure open the console(tilde key) click on wardrobe to select it and type            IsOwner you should see to who it belongs exactly.

Where's my room in Winterhold?


Remove Dash/Hyphen From Wordpress CustomPosttype Permalink

Question: I want to remove all hyphens/dashes from the custom post type permalink in Wordpress.
For example:
www.website.com/customposttype/post-name/
Becomes :
www.website.com/customposttype/postname/
I want automatic solution for future and old posts.
Any advice on how to do this with any functions.
Thanks
Comment: You want automatic solution for future and old posts? If it is just not many posts, you can easily manually edit the slugs, remove spaces so no dashes...
Comment: i want automatic solution for future and old posts
Answer: You need to use to hook into WordPress's sanitize title hook.
function no_dashes($title) {
    return str_replace('-', '', $title);
}
add_filter('sanitize_title', 'no_dashes' , 9999);

It will remove the dashes from the URL. However it will work only when you save a post. That is for new posts it will work just fine. But for existing posts, you have to go and edit/hit update/save to make it happen.
TODO: Also you need to have to check for Custom Post Type also, so it does not apply for all post types.
UPDATE: I thought adding post_type check would be easier hence I added above TODO, but you are right looks like we do not have any data related to that on the filter hook I used.
For that please use this code and see if it works:
function no_dashes( $slug, $post_ID, $post_status, $post_type ) {

    if( $post_type == "page" ) {
        $slug = str_replace( '-', '', $slug);
    }
    return $slug;
}
add_filter( "wp_unique_post_slug", "no_dashes", 10, 4 );

Comment: its working for all post,page and custom post type i want to remove dash from only in custom post type how to do that
Comment: @sarun Check updated code and see if it works for you.
Comment: @sarun Great! Happy coding!
Answer: Warning, dashes and hyphens must only be removed in utl path, not in domain.
That's why I would do something like this :
Something like this :
// This is our sample url, I just add a hyphen in domain name to ensure it won't be replaced
$url = "http://www.my-website.com/customposttype/post-name/foo_bar/";

// We use native php url parser to extract url path
$parsed_url = parse_url($url);
$url_path = $parsed_url["path"];

// Then, we replace dashes and hyphens in this path using a simple regular expression
$url_path = preg_replace('/(-|_)/', '', $url_path);

// Finally we rebuild a new url from the original one by replacing the path with the new one
$new_url = $parsed_url["scheme"].$parsed_url["host"].$url_path;

Demo
Comment: Removing just dashes on php level is going to break all WP links of those posts if it is not done on WP level ...


JSP compilation to string or in memory bytearray with Tomcat/Websphere

Question: I am doing conversion to image and PDF output.  I need an input HTML document that is generated by our application JSPs.  Essentially, I need to render the final output product of a JSP based application to a String or memory and then use that string for other processing.
What are some ways that I can just invoke the JSP renderer to get the final HTML content that is normally output to the user?
Ideally, I am looking for something that will work for multiple application servers like websphere.  But something that is Tomcat specific will also work.
There are a couple of other different approaches, but I think rendering the JSP (which may include sub JSPs) is the best approach.
Optional Paths that I would rather stay away from.

I could perform a network request to the page using the Socket APIs and then read the final output that is rendered from that particular page.  This is probably the next best option, but we work on multiple servers and JVMs, targeting the page I need would be complicated.
Use a filter to get that final page output.  This Ok but I have always had problems with filters and illegalstateexceptions.  It never seems to work 100% the way I need to.

It seems like this should be simple.  The JSP compiler is essentially just a library for parsing an input JSP document and subdocuments and then output some HTML content. I would like to invoke that process through Java code. On the server and possibly as a standalone console application.
Answer: This is a downright irritating problem, one I've had to handle a few times and one I've never found a satisfactory solution to.
The basic problem is that the servlet API is of no help here, so you have to trick it. My solution is to write a subclass of HttpServletResponseWrapper which override the getWriter() and getOutput() methods and captures the data into a buffer. You then forward() your request to the URI of the JSP you want to capture, substituting your wrapper response for the original response. You then extract the data from the buffer, manipulate it, and write the end result back to the original response.
Here's my code that does this:
public class CapturingResponseWrapper extends HttpServletResponseWrapper {

    private final OutputStream buffer;

    private PrintWriter writer;
    private ServletOutputStream outputStream;

    public CapturingResponseWrapper(HttpServletResponse response, OutputStream buffer) {
        super(response);
        this.buffer = buffer;
    }

    @Override
    public ServletOutputStream getOutputStream() {
        if (outputStream == null) {
            outputStream = new DelegatingServletOutputStream(buffer);
        }
        return outputStream;
    }

    @Override
    public PrintWriter getWriter() {
        if (writer == null) {
            writer = new PrintWriter(buffer);
        }
        return writer;
    }

    @Override
    public void flushBuffer() throws IOException {
        if (writer != null) {
            writer.flush();
        }
        if (outputStream != null) {
            outputStream.flush();
        }
    }

}

The code to use it can be something like this:
HttpServletRequest originalRequest = ...
HttpServletResponse originalResponse = ...

ByteArrayOutputStream bufferStream = new ByteArrayOutputStream();
CapturingResponseWrapper responseWrapper = new CapturingResponseWrapper(originalResponse, bufferStream);

originalRequest.getRequestDispatcher("/my.jsp").forward(originalRequest, responseWrapper);

responseWrapper.flushBuffer();
byte[] buffer = bufferStream.toByteArray();
// now use the data

It's very ugly, but it's the best solution I've found. In case you're wondering, the wrapper response has to contain the original response because the servlet spec says that you cannot substitute a completely different request or response object when you forward, you have to use the originals, or wrapped versions of them.
Comment: I get the feeling everyone has the same ghastly solution.
Comment: That is a good approach.  Kind of like the 'filter' oriented approach.

But the only problem with this, there are two problems.

1. You can't run this as a standalone system.  E.g. you can't do:
main() { compileJSP() }

2. If you use this within filter code, some applciation servers are nitpicking about the state of the requestwrapper and I tend to get illegalstateexceptions and can't ever get the JSP to render to a string (essentially when I do it this it is never straightforward).

But, yea that is a good solution.
Comment: to skaffman.

The network request approach isn't that bad either.

new Socket()/URL() {
http://localhost/myjsppage
...
read the output from the request
}

But that involves a network request and probably more code.


keep checkbox enabled using jquery or javascript

Question: I have a checkbox on my website which is currently enabled and it can be disabled by users. What I want to do is to keep it locked in that way so it cannot be disabled.
I think this can be achieved using jquery or javascript but I'm not quite sure how.
<input type="checkbox" value="check" id="moove_gdpr_strict_cookies">

And please note it's a wordpress website. So I can't edit HTML.
Comment: Just use this in document ready - `$('#moove_gdpr_strict_cookies').prop('disabled', true)`. It will disable the element.
Answer: you can simple prevent click.
$(document).ready(function() {
   $('#moove_gdpr_strict_cookies').click(function(e) {
      e.preventDefault();
   });
});

Answer: Simply you can return false onclick event
$('#moove_gdpr_strict_cookies').on('click',function(){
   return false;
});

Answer: Would suggest to do something like this:
  var form = document.getElementById('yourform');
  form.onSubmit = function () {
    var formElems = document.getElementsByTagName('INPUT');
    for (var i = 0; i , formElems.length; i++){
      if (formElems[i].type == 'checkbox'){
        formElems[i].disabled = true;
      }
    }
  }

Answer: I would not recommend doing this. As suggested by the id of checkbox this checkbox has to do with GDPR. A user on your sight MUST have the right to decline cookies for tracking purposes (which this seems to be). Please be careful, as fines can be very high.
Technically most answers seem viable.


Does same partition really never be consumed by more than one consumers on a single group at the same time

Question: Assume a topic has 2 partitions.
We have 2 consumers in a same group both consume from that topic: Consumer A consumes partition 0, Consumer B consumes partition 1.
Consumer A is the group leader of the consumer group.
At a moment, Consumer B got a batch of messages from the topic, for example message: X, Y. Right after that, Consumer B stopped.
After a while, Consumer A thinks that Consumer B is dead, and decides to rebalance and consume from partition 1. It gets messages: X, Y, Z (in order) and then writes to a database.
After that, Consumer B resumes the execution, had no idea that some time has passed, and continue to write message X, Y, overwriting the effect of Z.
And then Consumer B fails completely.
Is it possible? If yes, the simple way of consuming messages and upserting to a database might not be safe.
Comment: There's a very good explanation.. hope this will help
https://stackoverflow.com/a/51829144/7098046
Comment: Your description seems to be missing when/if the consumer committed any offsets. And if B dies, then the group rebalances, then A would read both partitions
Comment: It doesn't matter offset is commited or not by A here. Because B doesn't read anything from committed offsets topic when it writes to Database.
Comment: Kafka Consumers always query the offsets topic. You cannot disable that
Comment: Kafka Consumers as I remember only querying the committed offset topic at the start. You dont know about raft/paxos consensus or distributed locking, do you?
Comment: Kafka currently uses ZAB, so no
Comment: So you know how Zab work#??
Answer:
Consumer A thinks that Consumer B has dead, decide to rebalance and consume from partition 1. It got messages: X, Y, Z (in order) and then write to a database

Okay, let's say it commits offsets for each of those messages as well.
If B starts back up, it will start to read offsets after the most recent committed value, and not re-read data that it had tried to before unless the consumer was manually seeked to that position.
Comment: It's stopped right after receving messages, but before write to Database, so it didnt touch committed offsets topic to determine offsets is old version or not.
Comment: B doesnt fail, it's just paused, because of GC pause, VM pause or someone accidentally send stop signal to B.
Comment: Failure or pausing would still cause a rebalance and loss of processed record state
Comment: B can detect it has read old offsets but ONLY after B has already written to the database. Above problem still there
Comment: Pause of B can cause A to rebalance, but B didnt even know right away that itself has already left the group when it performing the write
Comment: I'm not sure I understand your problem. Ideally, you wouldn't write a database client in a consumer on your own, anyway, and would rather use Kafka Connect framework, which has fault tolerance controls


The selected option must shown after the function of onchange

Question: I have 2 dropdowns, just like the title.. The selected option must shown after the function of onchange meaning when it automatically refreshes the selected option must stay and show the selected options . The problem is when I select an option from the 2nd dropdown which has onchange function it refreshes and it gets back to the default option.
Here's the code

      BRANCHES

     Add Branch

       <form action="func_vbrs.php" method="POST" class="form-horizontal">
        <fieldset>

Branch

       <select name="bid" class='form-control'>
        <option value='' default style='color:gray;'>Branch</option>
         <?php
          include_once "config.php";

          $sql="select branchID, b, bl from branch where b!='HOK'";
          $stmt=$con->prepare($sql);
          $stmt->execute();
          $stmt->bind_result($bid, $b, $bl);
          $stmt->store_result();

          while($stmt->fetch()){
           echo '<option value="'.$bid.'">'.$b.'-'.$bl.'</option>';
          }
         ?>
       </select>

Category

        <select name="brcat" class="form-control"  onchange='this.form.submit()'>
         <option value="" default style="color:gray;">Category</option>
         <option value="Stock">Stock</option>
         <option value="Sales">Sales</option>
         <option value="Stock Transfer">Stock Transfer</option>
        </select>

    <input type="submit" value="Submit">
    </fieldset>
    </form>

As you can see the 2nd drop down is category, If a user already selects an option after the automatic refresh or onchange function, it gets back to default option.
Answer: You need to cross check against post on page load, and add a selected tag appropriately.  There are more elegant solutions with less bulky code if you use a loop to create your options, but that's another question.
<?PHP
    if (!empty($_POST['brcat'])){
        $selected_item = $_POST['brcat'];
    } else { $selected_item = Null; }

    function selcheck($item1, $item2){
        if ($item1 == $item2){
            $ret = " selected=\"selected\" ";
        } else {
            $ret = "";
        }
        return($ret);
    }

?>

<select name="brcat" class="form-control"  onchange='this.form.submit()'>
    <option value="" default style="color:gray;">Category</option>

<?PHP
$sel = selcheck("Stock",$selected_item);
?>
<option value="Stock"<?=$sel?>>Stock</option>

<?PHP
$sel = selcheck("Sales",$selected_item);
?>
<option value="Sales"<?=$sel?>>Sales</option>

<?PHP
$sel = selcheck("Stock Transfer",$selected_item);
?>
<option value="Stock Transfer"<?=$sel?>>Stock Transfer</option>


Solve equation $ 1+2^x=3^y$

Question: Find integers $x$ and $y$ such that$$ 1+2^x=3^y.$$
It is obvious that $x = y = 1$ and $x = 3, y = 2$ are solutions.
I think others are not.
How to show that?
Answer: Case 1: $y$ is odd.  Then $3^y \equiv 3 \mod 8$.  When is $2^x \equiv 2 \mod 8$?
Case 2: $y = 2 z$ is even.  Then $2^x = 3^{2z} - 1 = (3^z - 1)(3^z + 1)$, so
$3^z - 1$ and $3^z + 1$ are powers of $2$.  What powers of $2$ differ by $2$?
By the way, this proof of a special case of Catalan's conjecture dates back to Gersonides (Levi ben Gershon) in 1343.
Comment: This is excellent. (+1)
Comment: good old Levi ben Gershon and induction, wonder how many people ever realise that?
Answer: Clearly in this case Robert Israel's very elegant solution is perfect, but it is worth noting that what we have here is a special case of Catalan's conjecture (now a theorem, proved by Preda Mihăilescu) which states that the only solution of
$$x^a - y^b = 1$$ in integers (greater than 1) is given by $3^2-2^3 = 1$, so you are correct, there are no other solutions.
Comment: I do not like this answer because it uses a very difficult (and recently proved) theorem to prove a result that has a much more elementary proof.

Solve equation $ 1+2^x=3^y$


can i make Multiple FileStream objects to one file in the same time?

Question: why in fs2 object throw error ?? i already have written a FileShare.ReadWrite in fs object
     FileStream fs = new FileStream("hello.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.ReadWrite);

        mama();

        Console.ReadKey();

    }
    static void mama()
    {
        FileStream fs2 = new FileStream("hello.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
        fs2.Read(new byte[3], 0, 3);
    }

can any one tell me why this error ?
error = The process cannot access the file 'C:\Users\iP\documents\visual studio 2015\Projects\ConsoleApplication32\ConsoleApplication32\bin\Debug\hello.txt' because it is being used by another process.
Answer: You're getting that error because you're passing FileShare.None to the second call. If you change that to FileShare.ReadWrite to match the first call, you won't have that problem.
The reason for this is because the FileStream constructor calls CreateFileW underneath, and if you take a look at the documentation for that function, it states:

You cannot request a sharing mode that conflicts with the access mode
  that is specified in an existing request that has an open handle.
  CreateFile would fail and the GetLastError function would return
  ERROR_SHARING_VIOLATION.

You already have an open handle from the first request using FileAccess.ReadWrite as the access mode, which conflicts with FileShare.None in the second call.
Answer: Because your code never closes the file and has an open handle to it
If you can, always use the using statement, it will flush and close the file
using(var fs = new FileStream(...))
{
    // do stuff here
} // this is where the file gets flushed and closed

If 2 methods are working on the same file, pass the FileStream in
static void mama(FileStream fs )
{
    fs .Read(new byte[3], 0, 3);
}


Tools resolving complicated Gradle dependencies

Question: So I have a complicated dependency tree for one or more gradle projects / subprojects.
So I run gradle dependencies and it creates a big ole file ascii tree with dependencies.
But this is not very readable for my huuuuge gradle file.
Is there perhaps a tool that views this? Or a way to get a json formatted output instead?
Comment: maybe try running it for a concrete module like gradle :core-module:dependencies
Answer: If you use IntelliJ IDEA (I'd heavily recommend to do if you code Java), there is a Gradle View plugin that can display the dependency tree as a clickable tree.
Other than that, you can also give the dependencies task a concrete configuration with --configuration that should be displayed, or you can use the dependencyInsight task if it is more that you want to know where a specific dependency comes from.
Comment: yep i'm using this tool to make it so i can load my project in intelliJ.
Answer: It ended up that I really needed a Task to task dependency graph. Because sure I was pulling in a few too many jars in some spots... but the real problem was my tasks were depending on each other in stupid ways therefore pulling in pretty much every build task no matter what you built.
And there is a plugin here: https://github.com/mmalohlava/gradle-visteg
Creates graphviz file from your deps. Then you can use graphviz to render to image to see a picture of what's going on.


Pandas: How to return multiple columns with a custom apply function on a groupby object

Question: The basic idea is that I have a computation that involves multiple columns from a dataframe and returns multiple columns, which I'd like to integrate in the dataframe.
I'd like to do something like this:
df = pd.DataFrame({'id':['i1', 'i1', 'i2', 'i2'], 'a':[1,2,3,4], 'b':[5,6,7,8]})

def custom_f(a, b):
    computation = a+b
    return computation + 1, computation*2

df['c1'], df['c2'] = df.groupby('id').apply(lambda x: custom_f(x.a, x.b))

Desired output:
    id  a   b  c1     c2
0   i1  1   5  7      12
1   i1  2   6  9      16
2   i2  3   7  11     20
3   i2  4   8  13     24

I know how I could do this one column at a time, but in reality the 'computation' operation using the two columns is quite expensive so I'm trying to figure out how I could only run it once.
EDIT: I realised that the given example can be solved without the groupby, but for my use case for the actual 'computation' I'm doing the groupby because I'm using the first and last values of arrays in each group for my computation. For the sake of simplicity I omitted that, but imagine that it is needed.
Comment: hi! Is any one of the answers below working? If so & if you wish, you might consider [accepting](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) one of them to signal others that the issue is resolved. If not, you can provide feedback so they can be improved (or removed altogether)
Answer: df['c1'], df['c2'] = custom_f(df['a'], df['b']) # you dont need apply for your desired output here

Comment: Thanks, I see thought that my example might have been too simple. In my real use case I do the groupby because I need to know the start/end points of each array of the grouped data frames for my computation.
Answer: you can try:
def custom_f(a, b):
    computation = a+b
    return pd.concat([(computation + 1),(computation*2)],axis=1)

Finally:
df[['c1','c2']]=df.groupby('id').apply(lambda x: custom_f(x.a, x.b)).values

output of df:
    id  a   b   c1  c2
0   i1  1   5   7   12
1   i1  2   6   9   16
2   i2  3   7   11  20
3   i2  4   8   13  24


OpenLayers 7 Get all features in a vector layer

Question: I'm upgrading from a much earlier version of Openlayers, and just can't seem to figure out how to get all of the features in a vector layer.
For context what my ultimate goal is, is to set the visibility on each feature based on certain data criteria - so if there is another way to do that I would be interested in that too.
My code is:
pointType is an internal reference string to allow me to differentiate between layers / data. All of my layers have it as a key.
public getFeatures(pointType: string): any {
    const layer = this.getLayer(pointType);
    const source = layer.getSource();

    const features = null; //source.getFeatures();

    return features;
}

private getLayer(pointType: string): Layer {
    const layers = this.getLayers();
    for (let l = 0; l < layers.length; l++) {
        if (pointType === layers[l].get("pointType"))
            return layers[l];
    }
    return null;
}

private getLayers(): Layer[] {

    if (!this.map)
        return null;

    return this.map.getAllLayers(); // this.map is typeof ol/Map
}

The Layer I get back is of type Vectorlayer and the Source is VectorSource - So I think I'm close. But I can't seem to figure out how to make that last jump to the actual features.
Any help would be appreciated!
EDIT: Additional info.
source.getFeatures() results in the error:
Error  TS2339  (TS) Property 'getFeatures' does not exist on type 'Source'.
source is from ol/source/Source - do I need to convert / cast this to ol/source/Vector  - somehow?
EDIT2:
Simple fix! Just cast it to VecorSource
const features = (source as VectorSource).getFeatures();
Comment: `source.getFeatures()` is correct, but features may be loaded on demand, so whether all the features are available will depend on the visibility of the layer and how the source is loaded.
Comment: Thanks @Mike Adding info to the question regarding `source.getFetaures()`
Answer: Thanks to @Mike (see comments) I worked out that all I needed to do was cast ol/source/Source to ol/source/Vector to fix the issue.
Complete getFeatures() code:
public getFeatures(pointType: string): any {
    const layer = this.getLayer(pointType);
    const source = layer.getSource();

    const features = (source as VectorSource).getFeatures();

    return features;
}


Google API Console page is blank

Question: When I try to go to the Google API Console website to get a Google Maps API Key, all I get is a blank page. I've tried this, but it didn't work for me. Please help.
This is what the blank page looks like
Thanks in advance!
Answer: If the  API console webpage isn't working for you, you can easily go to this webpage and scroll down until you see the button that says "GET A KEY." Then follow the steps to create your google maps API key.
Hope this helps!

Google API Console page is blank


Can I use queryselector outside of the main function in dart?

Question: In many examples I see code like this:
InputElement task;

void main() {
  task = querySelector('#task');
  task.text = "blabla";
}

Doing it like this seems to have the same effect.
InputElement task = querySelector('#task');

void main() {
  task.text = "blabla";
}

I prefer the second way, but I'm not sure if there is any difference, or that the second way may break something.
Answer: Yes you can call querySelector at the top level.
However note the order of evaluation, as the DOM must be initialised first. Typically the dart script tag is placed at the end of the body, so main runs after the DOM has been created.
For a top level variable, the expression on the right hand side is evaluated when the variable is used the first time.
Consider the following example, which prints 1, 2, 3.
int i = foo();

foo() {
  print('#2');
  return 42;
}

main() {
 print('#1');
 int k = i;  // i is accessed for the first time, so foo() is called.
 print('#3');
}

Answer: Since Dart code isn't executed until the DOM is ready, both approaches work fine, and neither will break.


Is there a chance to lose all your enchantments when enchanting an item?

Question: In the first game, there was only one enchanter in the game who could enchant your items as many times as you want if you had the money and were brave enough to chance at losing all your enhancements.  The more you enchant an item, the more likely that he'd screw it up and you lose your enchantments on that item forever.
Fast forward to the next game, you have a limited amount of enchantments that can be applied to an item but you now have the option to remove enchantments for some money.
Is there a chance that attempting to enchant an item now can remove all enchantments on your item?
I've saved up enough money to enchant my best weapons so I will be enchanting as much as I can.  I'd just hate to lose everything.
Comment: I haven't played Torchlight 1 and I was confused that the enchanter always says something like `Fortune favors you` when you enchant an item in Torchlight 2, giving me the impression the enchant *could* fail, but this explains it :)
Answer: Enchanting is very different from what was found in Torchlight 1.  Enchanting adds magical properties that can also be removed (deliberately) by an enchanter.  But enchanting can no longer wipe an item; that is, enchanting cannot affect existing stats in any way.  The removal mechanic exists so you can spend gold to get an item "just right".
Comment: And for clarity's sake: no, attempting to add enchants cannot wipe your current enchants **nor** the base stats of the item. All a failure will do is consume your gold.
Comment: "Enchanting can no longer wipe an item".


Meaning of evt = (evt) ? evt : window.event

Question: What does this JavaScript snippet mean? The (evt) part is so confusing; evt is not a boolean. How it works?
function checkIt(evt) {
        evt = (evt) ? evt : window.event
        var charCode = (evt.which) ? evt.which : evt.keyCode

    }

Comment: if `evt` is set ie not `undefined` or `null` or `false` then that expression uses `evt` or else it picks up the `window event`
Comment: cause evt ? evt : window.event is more confusing...?
Answer: evt = (evt) ? evt : window.event is just the inline if syntax. It's equivalent to this code:
if (evt) {
    evt = evt;
} else {
    evt = window.event;
}

If evt is truthy, evt will be left alone. If evt isn't truthy, it will be replaced with window.event.
Comment: @amesh: Right, that's why I said *truthy*. If `evt` isn't `null`, `undefined`, `NaN` (I think), `0` or `false`, it's considered truthy. Basically, if `evt` has been set already, it's truthy.
Answer: It's for event listeners.
IE6-IE8 used a totally different event method than the W3C standard.
When an event fires, a W3C-standard browser will pass an event object in the callback:
function keyPressed (e) { /* do stuff with e */ }

In your case, it's keydown (or something else using keyCode).
IE didn't support this, instead it had window.event which was updated every time an event happened.
So your function is checking to see if an object was passed into it:
evt = (evt) ? evt : window.event;
// does `evt` exist, and is it anything but '', 0, false, null, undefined, NaN
// yes: evt = itself (W3C)
// no: evt = window.event (IE6-8)

Then the code asks if evt.which exists, to try to figure out where to get the keyCode from.
evt.keyCode is what you should be using for modern browsers, in the case of keydown and keyup.
Answer: Assignment expressions like that are evaluated from right to left, so this means:

if evt has a truthy value, assign this value back to evt
if not, assign the value of window.event regardless of its content to evt
Answer: It means: if the evt parameter has a value then keep the value, if it doesn't have a value then use window.event instead.
The ? and ':' symbols are part of the ternary if operator:
var w = x ? y : z;

so above you assign either y or z to w depending on whether x is considered to be a true or false value.
If the checkIt function was called without passing in an evt argument i.e. checkIt() then inside the function the evt variable will have the value of undefined which is treated as false within an if condition.


Ajax call only working on first page of webgrid

Question: Hi all,
I have a webgrid that has pagination. One of the column displays an icon that can be clicked and will trigger an ajax call. The ajax call works fine on the first page of the webgrid but it doesn't seem to be working on the next pages. I don't think it's even hitting the ajax call, the display would also jump on the top of the page. Can someone tell me what I'm doing wrong or how I can make it work on the other pages of the webgrid as well?
var Grid = new WebGrid(canPage: true, canSort: false, rowsPerPage: 25, ajaxUpdateContainerId: "gridContent");
Grid.Bind(Model.DataList);
Grid.Pager(WebGridPagerModes.NextPrevious);

var gridColumns = new List<WebGridColumn>();

gridColumns.Add(PaymentGrid.Column(columnName: "WavFile", header: " ", format:@<text>
@if (item.WavFile != null && item.WavFile != "")
{  }
else
{ @Html.Raw("") }</text>));
gridColumns.Add(Grid.Column(columnName: "EmployeeID", header: "EmpID"));
gridColumns.Add(Grid.Column(columnName: "LastName", header: "Last", canSort:
true));
gridColumns.Add(Grid.Column(columnName: "FirstName", header: "First", canSort: true));

@Grid.GetHtml(
tableStyle: "table table-striped table-hover",
headerStyle: "",
footerStyle: "",
alternatingRowStyle: "",
rowStyle: "",
mode: WebGridPagerModes.All,
columns: Grid.Columns(gridColumns.ToArray())
)


How do I untwist a very long, very twisted Ethernet cable?

Question: A few years ago I bought what should be a 45m flat Ethernet cable.
After a long period of disuse the cable has gotten very tangled but I need to use it again. I've unknotted the cable so it is now one long cable but the cable is incredibly twisted:

I've tried to very slowly untwist the cable starting from one end, but that just seems to make the problem worse. After a certain point it gets harder and harder to untwist and then I can't untwist it anymore, and then the rest of the cable gets even more twisted. No matter which way I twist the end of the cable just seems to get even more twisted.

Is there a clever way to untwist this cable? Or should I cut my losses and just buy a new one?
Comment: Pull the cable through your fingers. The friction will generate a bit of heat which will help the cable soften and return to its flat state. You'll have to pull the same stretch over and over and over and over... While you're doing this, you'll be _adding_ that twist to the rest of the cable, so you'll need to stop every few feet to "whip" the twist out. All in all, if you _really_ need it to lay flat, buy a new one. If not, use it as it - the electrons don't really care how twisted the housing is...
Comment: Flat cables like that get deformed and you'd have to heat them to soften them to fix the problem. This isn't a home improvement project, though.
Answer: Well, the good news is it does not appear that you've passed into "throw it away" levels of twisted yet. I've had users do things to innocent cables that I can't quite believe. I find out about them when the cable fails, usually.
Find a stairwell, or some other place you can let the cable dangle, hold, and wait. Since you probably don't have a 45m stairwell handy, you'll have to work in sections. Starting from the end is a problem unless you can let the whole thing dangle - you want to start as far into the middle as you can and let the end spin free, so that the twist gets "worked out".
Another approach is to wind the untwisted section of cable onto a core of some sort (essentially a small cable spool) and to spin that as needed to remove twist as you wind it on - you'll need to keep light tension on it so it can't snarl - you can tape it if you want to pause while working. Important to then unroll it, NOT spiral it off the side of the spool. Still likely to be easiest if you can hang the unspooled cable as much as possible so it twists freely.
Once you get it sorted, you may also want to look up various methods of coiling cables without adding twist when coiling. Various ways work, and the one I prefer may not be the one you prefer.
Comment: Excellent answer.  This is why cable and rope is wound on a drum, and then unwound in teh reverse fashion, to prevent corkscrewing.
Answer: Make a couple of cable holders that are shaped like the picture shows.
You can probably buy something like that for christmas light strings or extension cords.
Wind about 41 m of the twisted cable onto one, and secure with a rubber band, or have someone hold it.
Untwist the remaining length and wind onto the second, take-up holder, then secure with a rubber band on the take-up holder.
Unwind 4 more meters from the first holder and repeat.
Draping the cable over a ceiling hook, or down a stairway helps because the take-up holder can spin freely.


Model Explainability Monitor Job fails for endpoint having two production variants

Question: I have a sagemaker endpoint with two production variants (for A/B testing). After testing, one of the variant gets zero traffic and other gets 100% of the traffic. This results in zero data capturing for the first variant. When model explainability job runs, it searches for captured for the variant with zero traffic as well which causes it to fail.
Is there a way to run model explainability monitoring job with an endpoint having two production variants?
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: Model Monitor works with endpoint with single variants. If you are looking to do shadow deployment I would refer you look at this blog


How do I make a curtain rail on a curved bay window easy to use?

Question: We have a bay window with a curved curtain rail that goes round the bay.   At present it is very hard to pull the curtain along the rail, as the curtain hooks get stack often on the curve.
Solutions please...  (With or without replacing the rail)
Answer: If by "stack," you mean that the curtain hooks get out of order, which makes opening the curtains back up impossible, then you could put a small screw or nail in the top/window side of each hook (perhaps two in each hook if it is really bad.)  Or you could just get bigger hooks. That would make it would be impossible for them to overlap.
If the problem is that too much friction is created by pulling on the curtain material, then I would suggest finding a curtain pulley system (or attaching a rod to the middle-most hook on each side of the curtain.)  Such systems would create an entirely horizontal force on the curtain's hooks, as opposed to the diagonal downward force created by simply pulling on the curtain material, which will create friction between the hooks and the rail.  Or, if the rail and hooks are metal, you could simply try oiling them to reduce friction.
If the problem is something other than the hooks overlapping and becoming inseparable, please explain the problem... maybe even a picture would be in order!
Answer: Simply spray the track with--ideally--silicone spray, or furniture polish.  Dust builds up over time and the track no long runs smoothly.  If this doesn't work, the track is probably damaged; it can possibly be fixed but it depends what sort of track and if parts are available if it's an old one.  Try the spray first. Then see if any screws on the leading arms need tightening.


Writing a simple function function in Selenium

Question: I am a fresher in Selenium. I have lots of doubt about Selenium functions. I am using Selenium RC with Java and Eclipse.
I need to write one simple function for adding two numbers. Where will I write that function inside the test()?
How can I call that function if we want any other object for this function? Do we need to declare any header file for calling this function? Please help me.
Answer: I would look at this helpful tutorial part 1, part 2
Answer: Lets say the function is:
public void waitForElementExistance(final String elementLocator,
        final int seconds, final boolean exists) throws Exception {
    waitTimeFor(new Condition() {
        @Override
        public boolean verify() {
            return selenium.isElementPresent(elementLocator) == exists;
        }
    }, 10);
}

You write this function -- for example  -- just above the test()
You can call it in your test() like this:
waitForElementExistance("css=div.buttonlabel:contains(Upload)", 10, true);


Given that $\lim\limits_{\theta \to 0} \frac{\sin(\theta)}{\theta} = 1$, calculate $\lim\limits_{t \to 0} \frac{\sin(kt)}{kt}$

Question: I've solved this problem, but I'm unsure if my reasoning is correct. Please review my understanding of the problem and whether or not my reasoning is correct. Thank you.
We know that $\lim\limits_{\theta \to 0} \frac{\sin(\theta)}{\theta} = 1$.
We want to know $\lim\limits_{t \to 0} \frac{\sin(kt)}{t}$.
$\lim\limits_{t \to 0} \frac{\sin(kt)}{t}$ = (k) $\lim\limits_{t \to 0} \frac{\sin(kt)}{kt}$. This is because we are multiplying both the numerator and denominator by $k$. Therefore, by the limit laws, we are not changing the limit?
As $t$ goes to $0$, $kt$ goes to $0$:
(k) $\lim\limits_{t \to 0} \frac{\sin(kt)}{kt}$ = (k) $\lim\limits_{kt \to 0} \frac{\sin(kt)}{kt}$.
Let $kt = \theta$.
(k) $\lim\limits_{kt \to 0} \frac{\sin(kt)}{kt}$ = (k) $\lim\limits_{\theta \to 0} \frac{\sin(\theta)}{\theta}$ = (1)k = k
Comment: Please use MathJax to write the math: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: This is correct.
Comment: @Lovsovs I managed to fix it. Not sure how to include the thetas, though. :S
Comment: For greek letters, you write \greekletter.
Comment: @DavidBowman Thanks!
Comment: @ThePointer Great work!
Answer: Let $t = k\theta$ then if $\theta \to 0, t \to 0$ and so;
$$\lim_{\theta \to 0} \frac{\sin(k\theta)}{\theta} = \lim_{\theta \to 0} \frac{k}{k}\cdot \frac{\sin(k\theta)}{\theta} = k \cdot \lim_{\theta \to 0} \frac{\sin(k\theta)}{k\theta} = k \cdot \lim_{t \to 0} \frac{\sin (t)}{t} =k \cdot 1 = k$$
Comment: There is an error in your calculations?
Comment: Ok, it's fixed. Everything you did was basically correct, I just submitted this as an answer to close the question. You might want to look at your substitution though, that's where you error is.
Comment: Ok, thanks. Which substitution are you referring to?
Answer: Set $kt = x$
Hence your limit becomes
$$\lim_{x \to 0} \frac{\sin x}{x} = 1$$
Hence your limit is then $k$
Comment: Please elaborate on your answer. Specify exactly where my reasoning is incorrect.
Comment: @ThePointer It's not, sorry. You made a mess with not being able to write properly in LaTeX so I got confused.
Comment: My apologies. :(


Create an Array of Arrays with each Array indexed

Question: I would like to add Arrays together into an Array of Arrays. I would also like each Array to be indexed.
Input:
a = Array("a", "b", "c")
b = Array("d", "e", "f")
c = Array("g", "h", "k")

I want output like this:
a+b+c=> Array(("1",Array("a", "b", "c")),
              ("2",Array("d", "e", "f")),
              ("3",Array("g", "h", "k")))

Comment: Do you have a list of Arrays ? Like List(a,b,c)
Comment: Question seems a bit unclear. What is the output Array Type?, It is having `array[...]`. it seems to be a String. And it infers the output Array `Type`  as `Array[String]`
Comment: Thanks for your support. Actually, I have two fields in DB as Array[string], i want the combine them to reduce the query loading time with recursive . The output expect Array[{1, Array1[]},{2, Array2[]}]
Answer: Lets say you have a list of input arrays
val a = Array("a", "b", "c")
val b = Array("d", "e", "f")
val c = Array("g", "h", "k")
List(a,b,c)

You can arrive at your desired solution by applying a simple function as follows
List(a,b,c).zipWithIndex.map(x => (x._2.toString,x._1))

This will fetch you an output as
res0: List[(String, Array[String])] = List((0,Array(a, b, c)), (1,Array(d, e, f)), (2,Array(g, h, k)))

Comment: I accepted the answered with very clear to understand. Thanks all.
Answer: a = Array("a", "b", "c")
b = Array("d", "e", "f")
c = Array("g", "h", "k")

def outArr(a:Array[String],b:Array[String],c:Array[String]) =
 Array(a,b,c).zipWithIndex.map{
  case (Array(a,b,c),x)=>"{\""+(x+1)+"\", array[\""+a+"\", \""+b+"\", \""+c+"\"]}" }

In Scala REPL:
scala> outArr(a,b,c)
res8: Array[String] = Array({"1", array["a", "b", "c"]}, {"2", array["d", "e", "f"]}, {"3", array["g", "h", "k"]})


Why added value en each loop hasn't been stored on next iteration?

Question: Brief logic is the next: after clicking on 'li' element, request is sent, and based on response value of 'contacts', it should select if it's greater than 0, once such element is find, i need to break each loop. But currently, despite I set value, which should break each loop on next iteration (returns false). count[] has been restored with old values, what's an issue?
    cy.get('div[id=company_select]').then($el => {

        const count = []
        cy.wrap($el).click().find('li').each((element, index) => {
            cy.intercept('GET', '**/company/view-json**').as('getCompanyProps')

            cy.log(count.length)
            if (count.length > 0) {
                return false
            } else {
                cy.wrap(element).click().wait('@getCompanyProps').then((interception) => {
                    if (interception.response.body.contacts.length === 0) {
                        cy.wrap($el).find('button[vs__clear]').click()
                    } else {
                        count.push(1)
                        cy.log(count.length)
                    }
                })
            }
        })

    })

Answer: You can't early-exit with return false in this scenario, but you can use count to prevent inner execution after body.contacts.length > 0.
cy.intercept('GET', '**/company/view-json**').as('getCompanyProps') // this can be here

cy.get('div[id=company_select]').then($el => {

  const count = []
  cy.wrap(count).as('count')   // make an alias value of the count variable

  cy.wrap($el).click().find('li')
    .each((element, index) => {

      cy.get('@count').then(count => {  // retrieve count asynchronously
        if (count.length === 0) {       // no result yet?

          cy.wrap(element).click().wait('@getCompanyProps')
            .then((interception) => {
              if (interception.response.body.contacts.length === 0) {
                cy.wrap($el).find('button[vs__clear]').click()
              } else {
                count.push(1)
                console.log(count.length)
              }
            })
        }
      })
    })
})

The reason for this behaviour is the mixture of asynchronous commands like  .wait('@getCompanyProps') and synchronous code for checking the early exit.
If you use console.log() instead of cy.log() to debug the values, you'll see the logs before the early exit all run before the logs after count.push(1).
Answer: If I understand your question correctly, you wish to know why on the second pass of your cypress each loop cy.wrap($el).click().find('li').each((element, index) => { the cy.log(count.length) is equal to 0.
Even though further down inside another then loop cy.wrap(element).click().wait('@getCompanyProps').then((interception) => { you increase count by count.push(1) and right after cy.log(count.length) which returns 1.
The short answer is scope. If you change a variable within a cypress loop to return that variable you need to add something like this after .then( () =>{ cy.wrap(count)} My solution is below but I also changed the position of your const count = [] if you want to know why I suggest reading What is the difference between 'let' and 'const' ECMAScript 2015 (ES6)?
const count = []
cy.intercept('GET', '**/company/view-json**').as('getCompanyProps')
cy.get('div[id="company_select"]')
.then( ($el) => {
  cy.wrap($el)
  .click()
  .find('li')
  .each( ($el) => {
    if (count.length === 0){
        cy.wrap($el)
        .click()
        .wait('@getCompanyProps')
        .then((interception) => {
            if (interception.response.body.contacts.length === 0) {
            cy.wrap($el)
            .find('button[vs__clear]')
            .click()
            } else {
            count.push(1)
            cy.log(count.length)
            }
          })
        }
      })
      .then( () =>{
        cy.wrap(count).as('count')
    })
})
cy.get('@count')
.then( (count) =>{
  cy.log(count.length)
})


How to Asynchronously Show a Create New Button On a CRM Sub Grid?

Question: I need to hide the "Add New" button on a sub grid until certain criteria are met.    Calling Xrm.Page.ui.refreshRibbon will trigger my JS function defined in my Enable Rule, but I can't get the + button to show up.
Is this unsupported, or is there some methodology to get this to work?
Answer: Seems like you have to do few extra trick.

Refreshing the subgrid command bar
You will find that when the form is loaded, if there is a value in the attribute you have referenced in your enable rule, the Add New button will be visible. If however the value changes, the sub-grid command bar will not automatically refresh to reflect the new state. Upon adding or deleting rows in the sub-grid the command bar is refresh – but this isn't much use in this case.
The main form command bar can be refreshed using Xrm.Page.ui.refreshRibbon() however this will not refresh sub-grid command bars. Instead, we can add an onchange event to the fields that are used in our VaueRule and call:

Xrm.Page.data.save();

This will refresh the sub-grids and re-evaluate any of the EnableRules however it will also save any other dirty attributes and so should be used with caution if you do not have auto-save enabled.

Ref: https://ribbonworkbench.uservoice.com/knowledgebase/articles/489288-show-or-hide-the-add-new-button-on-form-sub-grid
Answer: Arun Vinoth did find a great article to describe the issue, but actually I've found that just calling refresh on the grid itself was all that was actually required.
It's important to note, that this does not re-run the enable rules, just shows the button if the state has changed.
Comment: @ArunVinoth Yes, I learned something new as well.  Also had the joy of yanking my hair out handling of this using requireJS which doesn't allow for a synchronous loading of a module.


SoupUI DS using groovy script parsing XML from URL

Question: I'm using SoapUI pro Datasource groovy script:
import groovy.util.slurpersupport.GPathResult

@Singleton
class UrlXmlParser {

    //def url = "http://www.xmlfiles.com/examples/plant_catalog.xml"
    def slurper  = new XmlSlurper()

    GPathResult parse(String url){
//      def xmlText = url.toURL().text
//      def content = slurper.parseText(xmlText)
        slurper.parse(url)
    }
}

def allPlants = UrlXmlParser.parse("http://www.xmlfiles.com/examples/plant_catalog.xml").PLANT

//
//log.info "it works"+allPlants.size()

def row = testRunner.testCase.testSteps["groovyDS"].currentRow

if(row < allPlants.size()){
    result["zone"]=content.PLANT[row].ZONE
    result["light"]=content.PLANT[row].LIGHT
    result["price"]=content.PLANT[row].PRICE

}

But I get an error because of the GPathResult:
No signature of method: static UrlXmlParser.parse() is applicable for
argument types: (java.lang.String) values:
[http://www.xmlfiles.com/examples/plant_catalog.xml] Possible
solutions: parse(java.lang.String), use([Ljava.lang.Object;), wait(),
grep(), any(), wait(long)

Comment: i don't know soapui:s behaviour, but are you sure, that AST Transformations like `@Singleton` are handled at all?  Could you just write it as a regular class or closure?
Answer: found the answer
import groovy.util.slurpersupport.GPathResult

@Singleton
class UrlXmlParser {

    def slurper  = new XmlSlurper()

    GPathResult parse(String url){
//      def xmlText = url.toURL().text
//      def content = slurper.parseText(xmlText)
        slurper.parse(url)
    }
}

def url = "http://www.xmlfiles.com/examples/plant_catalog.xml"
def allPlants = UrlXmlParser.instance.parse(url).PLANT

def row = testRunner.testCase.testSteps["groovyDS"].currentRow

if(row < allPlants.size()){
    result["zone"]=content.PLANT[row].ZONE
    result["light"]=content.PLANT[row].LIGHT
    result["price"]=content.PLANT[row].PRICE

}


AngularJS foreach - producing numerous null for unassigned values

Question: I have a array variable viewedprofiles= []; initialized.
I'll be assigning the profiles that have been viewed to this viewedprofiles array. Now if I try to display it (By assigning it to a $scope), I get NULL for other values that have not got assigned or touched.
  var viewedprofiles= [];

    angular.forEach(profiles, function(value, key){

        if(value.viewed== "yes") {
            viewedprofiles[value.id] = TRUE;
        }

    });

The output of viewedprofiles is as follows
 [NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,TRUE]

Output explanation :
Since the 9th id's profile viewed value was yes, the output returned TRUE at the 9th element of the viewedprofiles array.
Nothing wrong actually.
But I was wondering as far as the above code, the id was TRUE for 9th element. What if the id was some large number say 15640, Will there be 15639 NULLs before TRUE? Am I doing anything wrong or is there another way to work this out?
Answer: I found the answer.
What I was trying to do was basically wrong at the assigning part. I should push the element instead of assigning.
The following worked.
angular.forEach(profiles, function(value, key){

    if(value.viewed== "yes") {
        viewedprofiles.push(value.id);
    }

}, viewedprofiles);