Erro: The method getFragmentManager() is undefined for the type ActivitiesListAdapter

Question: Como chamo um Fragment a partir de um BaseAdapter?
Chamarei ele no click do botão, e também devo passar algumas informações.
Estou tentando chamar dessa maneira:
Fragment fr = new Fragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container, fr);
fragmentTransaction.commit();

Mas ele dá alguns erros:

The method getFragmentManager() is undefined for the type ActivitiesListAdapter

Aqui está o código de meu adapter, ele carrega dados de um json, monta uma lista e tem ícones nessa lista que farão alguma ação, no caso, o clique no CheckClickListener, está abrindo uma activity, e passando algumas informações, preciso abrir um fragment ao invés disso e passar as mesmas informações.
public class ActivitiesListAdapter extends BaseAdapter {

    private static final int        DEPLETED__RED    = 3;
    private static final int        DEPLETED__YELLOW = 2;
    private static final int        DEPLETED__GREEN  = 1;
    private static final DateFormat FMT_DATE;

    static {
        DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
        iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC"));

        FMT_DATE = iso8601Format;
    }

    private ArrayList<JSONObject>   dataProvider     = new ArrayList<JSONObject>();
    private String[]                jsonColumns;
    private LayoutInflater          inflater;
    private OptionsVO               options;
    private Context                 context;
    private int                     imageResource;
    private BaseListener            imageCallback;
    private String[]                columnsToCompare;
    private ActivitiesListFragment  fragment;

    public ActivitiesListAdapter(JSONArray array, String[] jsonColumns, AbstractListFragment fragment) {
        for(int index = 0; index < array.length(); index++) {
            try {
                this.dataProvider.add(array.getJSONObject(index));
            }
            catch(JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        this.jsonColumns = jsonColumns;
        this.context = fragment.getContext();
        this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.options = ApplicationOptionsManager.getOptions(fragment.getActivity(), fragment.getNetworkAction());
        this.fragment = (ActivitiesListFragment) fragment;
    }

    public void setImageCondition(int imageResource, BaseListener imageCallback, String... columns) {
        this.columnsToCompare = columns;
        this.imageResource = imageResource;
        this.imageCallback = imageCallback;
    }

    @Override
    public int getCount() {
        return this.dataProvider.size();
    }

    @Override
    public Object getItem(int position) {
        return this.dataProvider.get(position);
    }

    @Override
    public long getItemId(int position) {
        return ((JSONObject) getItem(position)).optLong("id");
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;

        if(convertView == null) {
            final ViewHolder holder = new ViewHolder();

            view = this.inflater.inflate(R.layout.custom_list_activities, parent, false);
            view.setTag(R.string.HOLDER, holder);

            holder.icoPlay = (ImageView) view.findViewById(R.id.actionPlay);
            holder.icoCheck = (ImageView) view.findViewById(R.id.actionCheck);
            holder.title = (TextView) view.findViewById(R.id.title);
            holder.data = (TextView) view.findViewById(R.id.data);
            holder.icoAbort = (ImageView) view.findViewById(R.id.actionAbort);
            holder.icoInfo = (ImageView) view.findViewById(R.id.actionInfo);
            holder.icoScaled = (ImageView) view.findViewById(R.id.bar);

            holder.icoPlay.setTag(R.string.HOLDER, holder);
            holder.icoCheck.setTag(R.string.HOLDER, holder);
            holder.icoAbort.setTag(R.string.HOLDER, holder);
            holder.icoScaled.setTag(R.string.HOLDER, holder);
            holder.icoInfo.setTag(R.string.HOLDER, holder);

        }

        final ViewHolder holder = (ViewHolder) view.getTag(R.string.HOLDER);
        JSONObject item = (JSONObject) getItem(position);

        try {
            item.putOpt("currIndex", position);
        }
        catch(JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        holder.icoPlay.setTag(R.string.JSON, item);
        holder.icoCheck.setTag(R.string.JSON, item);
        holder.icoAbort.setTag(R.string.JSON, item);
        holder.icoScaled.setTag(R.string.JSON, item);
        holder.icoInfo.setTag(R.string.JSON, item);

        int cdDepleted = item.optInt("cdDepleted", -1);
        if(cdDepleted == DEPLETED__RED) {
            view.setBackgroundColor(Color.argb(127, 255, 0, 0));
        }
        if(cdDepleted == DEPLETED__YELLOW) {
            view.setBackgroundColor(Color.argb(127, 255, 255, 0));
        }
        if(cdDepleted == DEPLETED__GREEN) {
            view.setBackgroundColor(Color.argb(127, 0, 255, 0));
        }

        int fkIdArticle = item.optInt("fkIdArticle", -1);
        if(fkIdArticle != -1) {
            holder.icoInfo.setVisibility(View.VISIBLE);
        }
        else {
            holder.icoInfo.setVisibility(View.INVISIBLE);
        }

        boolean flScaled = item.optBoolean("flScaled", false);
        if(flScaled == true) {
            holder.icoScaled.setVisibility(View.VISIBLE);
        }
        else {
            holder.icoScaled.setVisibility(View.INVISIBLE);
        }

        int cdStatus = item.optInt("cdStatus", 1);
        if(cdStatus == 1) {
            holder.icoPlay.setVisibility(View.VISIBLE);
            holder.icoCheck.setVisibility(View.GONE);
            holder.icoAbort.setVisibility(View.GONE);
        }
        else {
            holder.icoPlay.setVisibility(View.GONE);
            holder.icoCheck.setVisibility(View.VISIBLE);
            holder.icoAbort.setVisibility(View.VISIBLE);
        }

        holder.icoPlay.setOnClickListener(new PlayClickListener());
        holder.icoCheck.setOnClickListener(new CheckClickListener());
        holder.icoAbort.setOnClickListener(new AbortClickListener());
        holder.icoInfo.setOnClickListener(new InfoClickListener());

        try {
            Date dt = FMT_DATE.parse(item.optString("dtStart"));
            Time tm = new Time(dt, new Date());
            item.putOpt("dtStartFmt", tm.speak());

        }
        catch(ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        catch(JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if(this.columnsToCompare != null && this.columnsToCompare.length > 0) {
            final String[] colsToReturn = new String[this.columnsToCompare.length];
            boolean canShow = false;
            int i = 0;
            for(String col : this.columnsToCompare) {
                String optString = item.optString(col);
                if(optString != null && !optString.isEmpty()) {
                    canShow = true;
                }

                try {
                    colsToReturn[i++] = URLDecoder.decode(optString, "UTF-8");
                }
                catch(Exception e) {
                }
            }

            if(canShow) {
                holder.icoScaled.setVisibility(View.VISIBLE);
                holder.icoScaled.setImageDrawable(MobileUtils.getDrawable(this.context, this.imageResource));
                holder.icoScaled.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(imageCallback != null) {
                            try {
                                imageCallback.onCallback(new Object[] { colsToReturn });
                            }
                            catch(Exception e) {
                            }
                        }
                    }
                });
            }
            else {
                holder.icoScaled.setVisibility(View.GONE);
            }
        }

        try {
            holder.title.setText(URLDecoder.decode(decodeColumn(item, this.jsonColumns[0]).toString(), "UTF-8"));
            holder.assignCustomData(item, this.jsonColumns);
        }
        catch(Exception e) {
        }

        holder.icoAbort.setTag(R.id.tag_favorite_state, false);
        return(view);
    }

    private CharSequence decodeColumn(JSONObject item, String fieldName) {
        String rawValue = item.optString(fieldName);

        if(this.options != null && this.options.getDomains() != null && this.options.getDomains().length > 0) {

            OptionDomainVO[] domains = this.options.getDomains();
            outer: for(OptionDomainVO domain : domains) {
                String field = domain.getField();

                if(field != null && field.equals(fieldName)) {
                    OptionDomainValueVO[] values = domain.getValues();

                    for(OptionDomainValueVO val : values) {
                        if(val.getValue() != null && val.getValue().toString().equals(rawValue)) {
                            rawValue = val.getLabel();
                            break outer;
                        }
                    }
                }
            }
        }

        return rawValue;
    }

    class ViewHolder {
        ImageView icoPlay;
        ImageView icoCheck;

        TextView  title;
        TextView  data;

        ImageView icoAbort;
        ImageView icoInfo;
        ImageView icoScaled;

        public void assignCustomData(JSONObject item, String[] jsonColumns) {
            this.data.setText(null);
            this.data.setVisibility(View.GONE);

            extractValue(jsonColumns, 1, item);
            extractValue(jsonColumns, 2, item);
            extractValue(jsonColumns, 3, item);
            extractValue(jsonColumns, 4, item);
            extractValue(jsonColumns, 5, item);
            extractValue(jsonColumns, 6, item);
        }

        private void extractValue(String[] jsonColumns, int index, JSONObject item) {
            try {
                String col = jsonColumns[index];
                if(col != null && !col.isEmpty()) {
                    TextView line = getLine(index);
                    if(line != null) {
                        CharSequence value = decodeColumn(item, col);
                        if(value != null && !value.toString().isEmpty()) {
                            try {
                                line.setText(URLDecoder.decode(value.toString(), "UTF-8"));
                            }
                            catch(Exception e) {
                            }
                            line.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
            catch(ArrayIndexOutOfBoundsException e) {
            }
        }

        private TextView getLine(int index) {
            TextView text = null;

            switch(index) {
                case 1 :
                    text = this.data;
                    break;

            }

            return(text);
        }
    }

    public void clearItems() {
        this.dataProvider.clear();
        this.notifyDataSetChanged();
    }

    private class PlayClickListener implements OnClickListener {
        public void onClick(View v) {
            final ViewHolder holder = (ViewHolder) v.getTag(R.string.HOLDER);
            final JSONObject json = (JSONObject) v.getTag(R.string.JSON);
            holder.icoPlay.setVisibility(View.INVISIBLE);

            AbstractNetworkHandler handler = AbstractNetworkFactory.build(ActivitiesListAdapter.this.context, NetworkAction.ACTIVITIES_SAVE);
            handler.save(json, new HttpJsonObjectListener() {
                public void onRequestCompleted(JSONObject object, Integer httpStatus, CharSequence msg) {

                    boolean isOk = object.optBoolean("isOk", false);
                    boolean isNew = object.optBoolean("isNew", false);
                    int id = object.optInt("id", -1);

                    if(isOk == true) {
                        try {
                            json.put("cdStatus", 2);
                        }
                        catch(JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        ActivitiesListAdapter.this.fragment.runRunnableOnUIThread(new Runnable() {
                            public void run() {
                                holder.icoPlay.setVisibility(View.GONE);

                                holder.icoCheck.setVisibility(View.VISIBLE);
                                holder.icoAbort.setVisibility(View.VISIBLE);
                            }
                        });

                        if(isNew == true) {

                            try {
                                json.put("fkIdCallStep", id);
                            }
                            catch(JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }

                    }
                    else {
                        ActivitiesListAdapter.this.fragment.runToastOnUiThread("Não foi possível efetuar sua ação", Toast.LENGTH_LONG);
                    }

                }
            }, new HttpFailListener() {
                public void onRequestCompleted(Exception e, Integer httpStatus, CharSequence msg) {
                    ActivitiesListAdapter.this.fragment.runToastOnUiThread("Erro de conectividade", Toast.LENGTH_LONG);
                }
            });
        }
    }

    private class AbortClickListener implements OnClickListener {
        public void onClick(View v) {
            final JSONObject json = (JSONObject) v.getTag(R.string.JSON);
            final ActivitiesListAdapter self = ActivitiesListAdapter.this;
            final ViewHolder holder = (ViewHolder) v.getTag(R.string.HOLDER);
            // holder.icoPlay.setVisibility(View.VISIBLE);

            AbstractNetworkHandler handler = AbstractNetworkFactory.build(ActivitiesListAdapter.this.context, NetworkAction.ACTIVITIES_SAVE);
            handler.save(json, new HttpJsonObjectListener() {
                public void onRequestCompleted(JSONObject object, Integer httpStatus, CharSequence msg) {

                    boolean isOk = object.optBoolean("isOk", false);
                    boolean isNew = object.optBoolean("isNew", false);
                    int id = object.optInt("id", -1);

                    if(isOk == true) {
                        try {
                            json.put("cdStatus", 1);
                        }
                        catch(JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        ActivitiesListAdapter.this.fragment.runRunnableOnUIThread(new Runnable() {
                            public void run() {
                                holder.icoPlay.setVisibility(View.VISIBLE);

                                holder.icoCheck.setVisibility(View.GONE);
                                holder.icoAbort.setVisibility(View.GONE);
                            }
                        });

                        if(isNew == true) {

                            try {
                                json.put("fkIdCallStep", id);
                            }
                            catch(JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }

                    }
                    else {
                        ActivitiesListAdapter.this.fragment.runToastOnUiThread("Não foi possível efetuar sua ação", Toast.LENGTH_LONG);
                    }

                }
            }, new HttpFailListener() {
                public void onRequestCompleted(Exception e, Integer httpStatus, CharSequence msg) {
                    ActivitiesListAdapter.this.fragment.runToastOnUiThread("Erro de conectividade", Toast.LENGTH_LONG);
                }
            });
        }
    }

    private class InfoClickListener implements OnClickListener {
        public void onClick(View v) {
            HomeActivity home = (HomeActivity) context;
            Intent intent = new Intent(context, InfoFragment.class);

            intent.putExtra("EXTRA_INFO", "infomação extra");

            context.startActivity(intent);

            final JSONObject json = (JSONObject) v.getTag(R.string.JSON);
            final ActivitiesListAdapter self = ActivitiesListAdapter.this;
            /*
             * AbstractNetworkHandler handler = AbstractNetworkFactory.build(ActivitiesListAdapter.this.context, NetworkAction.ACTIVITIES_ABORT); handler.update(json, new HttpJsonObjectListener() { public void onRequestCompleted(JSONObject object, Integer httpStatus, CharSequence msg) { ActivitiesListAdapter.this.fragment.runRunnableOnUIThread(new Runnable() { public void run() { self.dataProvider.remove(json.optInt("currIndex")); self.notifyDataSetChanged(); } }); } }, new HttpFailListener() { public void onRequestCompleted(Exception e, Integer httpStatus, CharSequence msg) { ActivitiesListAdapter.this.fragment.runToastOnUiThread("Erro de conectividade", Toast.LENGTH_LONG); } });
             */
        }

    }

    private class CheckClickListener implements OnClickListener {
        public void onClick(View v) {
            final JSONObject json = (JSONObject) v.getTag(R.string.JSON);
            final ActivitiesListAdapter self = ActivitiesListAdapter.this;

            final boolean flQuick = json.optBoolean("flQuick", false);
            final String nmForm = json.optString("nmForm", "sem nmForm");

            AbstractNetworkHandler handler = AbstractNetworkFactory.build(self.context, NetworkAction.ACTIVITIES_QUICK_FINISH);

            handler.update(json, new HttpJsonObjectListener() {
                public void onRequestCompleted(JSONObject object, Integer httpStatus, CharSequence msg) {
                    ActivitiesListAdapter.this.fragment.runRunnableOnUIThread(new Runnable() {
                        public void run() {

                            if(flQuick == false) {
                                Intent intent = new Intent(context, NewActivity.class);

                                intent.putExtra("fkIdCallStep", json.optInt("fkIdCallStep"));
                                intent.putExtra("currIndex", json.optInt("currIndex"));
                                intent.putExtra("flQuick", flQuick);
                                intent.putExtra("nmForm", nmForm);

                                context.startActivity(intent);

                            }
                            else if(flQuick == true) {
                                // remover da lista do check
                                self.dataProvider.remove(json.optInt("currIndex"));
                                self.notifyDataSetChanged();
                            }

                            /*
                             * Animation anim = AnimationUtils.loadAnimation(context, android.R.anim.slide_out_right); anim.setDuration(500);
                             *
                             * View listItem = self.fragment.getChildAt(itemPosition); listItem.startAnimation(anim);
                             *
                             * new Handler().postDelayed(new Runnable() { public void run() { self.dataProvider.remove(itemPosition); self.notifyDataSetChanged(); } }, anim.getDuration());
                             */
                        }

                    });
                }
            }, new HttpFailListener() {
                public void onRequestCompleted(Exception e, Integer httpStatus, CharSequence msg) {
                    self.fragment.runToastOnUiThread("Erro de conectividade", Toast.LENGTH_LONG);
                }
            });
        }
    }

    public void addAll(JSONArray array) {
        for(int index = 0; index < array.length(); index++) {
            try {
                this.dataProvider.add(array.getJSONObject(index));
            }
            catch(JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        this.notifyDataSetChanged();
    }
}

Comment: Não entendo a sua pergunta. A forma de "chamar" um Fragment é igual qualquer que seja o local de onde o chama.
Comment: Estou tentando chamar dessa maneira: Fragment fr = new Fragment();
        FragmentManager fm = getFragmentManager();
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        fragmentTransaction.replace(R.id.container, fr);
        fragmentTransaction.commit();
Comment: Mas ele dá alguns erros: The method getFragmentManager() is undefined for the type ActivitiesListAdapter
Comment: Adicione à pergunta o código do Adapter e o erro que dá.
Comment: coloquei o adapter na pergunta
Answer: Você está a tentar aceder ao método getFragmentManager() que não existe na classe ActivitiesListAdapter.
getFragmentManager() é um método que existe nas classes Activity e Fragment.
O trecho de código postado funciona quando está a ser usado em uma dessas classes.
Neste seu caso terá de se socorrer do objecto fragment, passado no construtor, para obter o FragmentManager.
Fragment fr = new Fragment();

//Linha alterada
FragmentManager fm = fragment.getFragmentManager();

FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container, fr);
fragmentTransaction.commit();

Esta alteração resolverá o erro apresentado.
Se o seu código tem ou não mais algum problema não sei porque ele está muito confuso: acho que o seu adapter tem demasiadas responsabilidades.


How to correct my over fitted spline curve in python

Question: I have a data set and I've been asked to assign a smooth curve over its bar graph.
However my created graph seems very overfitted. they asked me to assign some sort of graph which can join some adjacent minimums and maximums and I don't know how to do that. Any help would be appreciated.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.interpolate import spline

fig, ax = plt.subplots()
fig.set_size_inches(13,7, forward=True)

width=1.0

data=pd.DataFrame({'x':[-29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
                   'y':[0.002383790226460071, 0.002383790226460071, 0.005164878823996822, 0.004370282081843465, 0.005164878823996822, 0.002383790226460071, 0.003178386968613429, 0.005959475566150178, 0.005959475566150178, 0.006754072308303536, 0.007945967421533572, 0.003575685339690107, 0.001986491855383393, 0.003575685339690107, 0.003972983710766786, 0.00278108859753675, 0.005959475566150178, 0.007151370679380214, 0.004767580452920143, 0.005164878823996822, 0.003575685339690107, 0.004370282081843465, 0.007945967421533572, 0.01311084624553039, 0.01072705601907032, 0.01430274135876043, 0.01231624950337704, 0.01589193484306714, 0.02264600715137068, 0.09654350417163289, 0.05164878823996821, 0.0166865315852205, 0.01549463647199046, 0.01350814461660707, 0.01191895113230036, 0.01191895113230036, 0.00874056416368693, 0.01152165276122368, 0.007151370679380214, 0.009137862534763607, 0.006356773937226857, 0.007151370679380214, 0.00834326579261025, 0.006356773937226857, 0.005562177195073501, 0.006754072308303536, 0.005164878823996822, 0.005164878823996822, 0.005959475566150178, 0.004767580452920143, 0.00278108859753675, 0.007945967421533572, 0.001589193484306714, 0.00278108859753675, 0.003178386968613429, 0.003575685339690107, 0.003178386968613429, 0.004370282081843465, 0.005562177195073501, 0.004370282081843465]})

plt.bar(data['x'],data['y'],width, color='r',  alpha=0.95)
x=data['x']
y=data['y']

x_new = np.linspace(x.min(),x.max(),300)

y_smooth =spline(x,y,x_new, order=3,kind='smoothest')

plt.plot(x_new,y_smooth, color='b')

Comment: What kind of fit are you looking to get?  Try [`scipy.optimize.curve_fit`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html).
Answer: Here is my fitting and plotting code for a variation of the Lorentzian peak equation from equation search of over 80 peak equations. This code uses scipy's differential_evolution genetic algorithm to estimate initial parameters for the non-linear solver in curve_fit(). That scipy genetic algorithm module uses the Latin Hypercube algorithm to ensure a thorough search of parameter space and requires bounds within which to search, here those bounds are taken from the data max and min values.
import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.optimize import differential_evolution
import warnings

xData = numpy.array([-29.0, -28.0, -27.0, -26.0, -25.0, -24.0, -23.0, -22.0, -21.0, -20.0, -19.0, -18.0, -17.0, -16.0, -15.0, -14.0, -13.0, -12.0, -11.0, -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0])
yData = numpy.array([0.002383790226460071, 0.002383790226460071, 0.005164878823996822, 0.004370282081843465, 0.005164878823996822, 0.002383790226460071, 0.003178386968613429, 0.005959475566150178, 0.005959475566150178, 0.006754072308303536, 0.007945967421533572, 0.003575685339690107, 0.001986491855383393, 0.003575685339690107, 0.003972983710766786, 0.00278108859753675, 0.005959475566150178, 0.007151370679380214, 0.004767580452920143, 0.005164878823996822, 0.003575685339690107, 0.004370282081843465, 0.007945967421533572, 0.01311084624553039, 0.01072705601907032, 0.01430274135876043, 0.01231624950337704, 0.01589193484306714, 0.02264600715137068, 0.09654350417163289, 0.05164878823996821, 0.0166865315852205, 0.01549463647199046, 0.01350814461660707, 0.01191895113230036, 0.01191895113230036, 0.00874056416368693, 0.01152165276122368, 0.007151370679380214, 0.009137862534763607, 0.006356773937226857, 0.007151370679380214, 0.00834326579261025, 0.006356773937226857, 0.005562177195073501, 0.006754072308303536, 0.005164878823996822, 0.005164878823996822, 0.005959475566150178, 0.004767580452920143, 0.00278108859753675, 0.007945967421533572, 0.001589193484306714, 0.00278108859753675, 0.003178386968613429, 0.003575685339690107, 0.003178386968613429, 0.004370282081843465, 0.005562177195073501, 0.004370282081843465])

def LorentzianPeakG_Offset(x_in, a, b, c, Offset): # from zunzun.com peak equation search
    temp = 0.0
    temp = a/ (1.0 + numpy.power((x_in-b)/c, 2.0))
    temp += Offset
    return temp

# function for genetic algorithm to minimize (sum of squared error)
def sumOfSquaredError(parameterTuple):
    warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm
    val = LorentzianPeakG_Offset(xData, *parameterTuple)
    return numpy.sum((yData - val) ** 2.0)

def generate_Initial_Parameters():
    # min and max used for bounds
    maxX = max(xData)
    minX = min(xData)
    maxY = max(yData)
    minY = min(yData)

    parameterBounds = []
    parameterBounds.append([minX, maxX]) # seach bounds for a
    parameterBounds.append([minX, maxX]) # seach bounds for b
    parameterBounds.append([minX, maxX]) # seach bounds for c
    parameterBounds.append([0.0, maxY]) # seach bounds for Offset

    # "seed" the numpy random number generator for repeatable results
    result = differential_evolution(sumOfSquaredError, parameterBounds, seed=3)
    return result.x

# generate initial parameter values
geneticParameters = generate_Initial_Parameters()

# curve fit the test data
fittedParameters, pcov = curve_fit(LorentzianPeakG_Offset, xData, yData, geneticParameters)

print('Parameters', fittedParameters)

modelPredictions = LorentzianPeakG_Offset(xData, *fittedParameters)

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()

##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData), 250)
    yModel = LorentzianPeakG_Offset(xModel, *fittedParameters)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)

This is the result:
Comment: thanks much for your time and the solution. Is there any way to have some smooth up and down on the bottom part of the curve. this curve just has one Maximum and there aren't any other local minimum and maximums.
Comment: You might consider modeling the left and right sides of the peak separately and using those two models together, switching from one to the other when X is below or above the peak's center value.
Answer: This is the answer that I ended up with:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline

fig, ax = plt.subplots()
fig.set_size_inches(13,7, forward=True)

width=1.0

#data=pd.read_excel("h:/projects/psc/output/data.xlsx")

data=pd.DataFrame({'x':\[-29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30\],
                   'y':\[0.002383790226460071, 0.002383790226460071, 0.005164878823996822, 0.004370282081843465, 0.005164878823996822, 0.002383790226460071, 0.003178386968613429, 0.005959475566150178, 0.005959475566150178, 0.006754072308303536, 0.007945967421533572, 0.003575685339690107, 0.001986491855383393, 0.003575685339690107, 0.003972983710766786, 0.00278108859753675, 0.005959475566150178, 0.007151370679380214, 0.004767580452920143, 0.005164878823996822, 0.003575685339690107, 0.004370282081843465, 0.007945967421533572, 0.01311084624553039, 0.01072705601907032, 0.01430274135876043, 0.01231624950337704, 0.01589193484306714, 0.02264600715137068, 0.09654350417163289, 0.05164878823996821, 0.0166865315852205, 0.01549463647199046, 0.01350814461660707, 0.01191895113230036, 0.01191895113230036, 0.00874056416368693, 0.01152165276122368, 0.007151370679380214, 0.009137862534763607, 0.006356773937226857, 0.007151370679380214, 0.00834326579261025, 0.006356773937226857, 0.005562177195073501, 0.006754072308303536, 0.005164878823996822, 0.005164878823996822, 0.005959475566150178, 0.004767580452920143, 0.00278108859753675, 0.007945967421533572, 0.001589193484306714, 0.00278108859753675, 0.003178386968613429, 0.003575685339690107, 0.003178386968613429, 0.004370282081843465, 0.005562177195073501, 0.004370282081843465\]})

plt.bar(data\['x'\],data\['y'\],width, color='r',  alpha=0.95)

x=data\['x'\]
y=data\['y'\]
x_new = np.linspace(x.min(),x.max(),300)
spl=UnivariateSpline(x,y)
spl.set_smoothing_factor(0.001)
y_smooth =spl(x_new)
plt.plot(x_new,y_smooth, color='b', alpha=0.95)][1]


Checar se usuário já existe codeigniter

Question: Olá, estou com um dificuldade para verificar se o nome de um dependente já foi cadastrado.
Tenho um formulário onde a pessoa pode adicionar até 5 nomes de dependentes e apos isso é gerado uma guia com os nomes.
Campo do formulário, tem um botão para adicionar mais campos.
<code>    <input type="text" name="nome_dep[]" id="nome_dep" placeholder="Nome do Dependente" class="form-control>
</code>
Pagina do Controller
<code>$nome = $this->input->post('nome_dep');
$nbanco = "SELECT `nome_dependente` FROM `beneficios_dependentes` WHERE `nome_dependente` IN ? ";

    $nome_existe = $this->db->query($nbanco,array($nome))->result_array();

    if (empty($nome_existe))
    {
        echo "Não tem nome no banco";
    }
    else
    {
        echo "Tem nome no banco";
    }
</code>
Minha dificuldade está em consultar se o nome do dependente já foi cadastrado, por exemplo: ele cadastrou joão - OK, mas outro dia ele cadastrou João e a Maria está caindo que já tem o nome cadastrado no banco.
Eu preciso fazer um insert caso ele não foi cadastrado e um update se já estiver cadastrado
Comment: Mas Existem homônimos, o correto não sería adicionar o `nome_dependente` e o `cpf_dependente`, para que você possa comparar os CPF's e não os nomes?
A final existem muitos "Luiz Inácio Lula", mas nem todos roubam países. alguns só querem programar.
Comment: kkkk, vou trocar o nome do perfil kkkk, então os dependentes estão vinculados com um associado, será que consigo algo nesse sentido?
Comment: Acho que ficaria menos "correto", suponha que um associado tenha filhos gêmeos com o mesmo nome... ele não poderia colocar os dois filho porque eles tem os mesmos nomes?
Porque o `SELECT nome_dependente FROM beneficios_dependentes WHERE nome_dependente = $nome AND associado_id = $id_do_associado` não serviria?
Como estão suas tabelas?
Comment: Tabela beneficios_dependentes tem: id_beneficios_dependentes, nome_dependente, associado_dependentes (FK), o problema é que o nome vem num array name="nome_dep[]", eu preciso separar cada um e verificar na tabela. A questão dos gêmeos acredito que não terá problema, mas vc deu uma ideia de adicionar o RG
Comment: Eu nunca usei o codeignite, mas se o problema é como fazer o `select` para todos os nomes de um `array`, você usa algum laço de repetição como o `foreach()`. vou publicar a resposta como acredito que ficaria.
Answer: Pelo que entendi, seu problema é em executar a pesquisa pela quantidade de beneficiarios que chegarem pelo post
<code>$nomes = $this->input->post('nome_dep');
  foreach ($nome as $nome) {

    $nbanco = "SELECT `nome_dependente` FROM `beneficios_dependentes` WHERE `nome_dependente` = $nome";

    $nome_existe = $this->db->query($nbanco,array($nome))->result_array();

    if (empty($nome_existe))
    {
      echo "Não tem nome no banco";
    }
    else
    {
      echo "Tem nome no banco";
    }
  }
</code>
Testa aí e me dá um retorno
Comment: eu arrumei é deu certo, muito obrigado por sua ajuda
Comment: Se puder marca como resposta certa
Answer: <code>foreach ($nomes as $nome)
    {
        $this->db->select('nome_dependente');
        $this->db->where('nome_dependente', $nome);
        $query = $this->db->get('beneficios_dependentes');
        $resultado = $query->result();
        if (empty($resultado))
        {
          $insere = $this->beneficios_model->insere($id, $dados, $nome);
        }
        else
        {
          echo "Tem nome no banco";
        }
    }
</code>
eu fiz assim, estou arrumando, mas deu certo

Checar se usuário já existe codeigniter


Running into an issue scraping off of an API page?

Question: I had previously been able to run this code, but it looks like something has changed. I'm attempting to scrape JSON from a website — the goal is to iterate through a bunch of numbers and compile the information on my end.
For my purposes, this is the part of the code that is breaking:
"https://api.mtgstocks.com/prints/11521/prices" %>%
  readLines()

This generates the error:
Error in file(con, "r") :
  cannot open the connection to 'https://api.mtgstocks.com/prints/11521/prices'
In addition: Warning message:
In file(con, "r") :
  cannot open URL 'https://api.mtgstocks.com/prints/11521/prices': HTTP status was '403 Forbidden'

I run into similar issues using GET and geturl. I realize that I may be blocked, but the confusing part is that I'm able to access the page and all the data from my browser.
Answer: I got the same error using a variety of different ways. My guess is that they recently changed their policy. Here's a way that still worked for me using RSelenium to automate a browser to access the data:
# load libraries
library(RSelenium)
library(rvest)
library(magrittr)
library(jsonlite)

# define target url
url <- "https://api.mtgstocks.com/prints/11521/prices"

# start RSelenium ------------------------------------------------------------

rD <- rsDriver(browser="firefox", port=4550L, chromever = NULL)
remDr <- rD[["client"]]
remDr$open()

# Navigate to webpage -----------------------------------------------------
remDr$navigate(url)

# click on raw data tab ------------------------------------
remDr$findElement(using = "css",value = "#rawdata-tab")$clickElement()

# pull the webpage html
# then read it
page_html <- remDr$getPageSource()[[1]] %>%
  read_html()

# find the html element where the json data is stored
# then extract the text
json_text <- page_html %>%
            html_node(".data") %>%
             html_text()

# read in the data using a json reading function
data <- fromJSON(json_text)


strange duel chances and my analysis

Question: There is two guy, A and B they are shooting each other by turns, A shoot first, A has 30 percent chances to shoot and kill B and 70 percent to miss, B has 50 percent chances to kill A and 50 percent to miss.  A takes the first shot.
So I first encounter this kind of questions, here is my analysis:
first attempt: I think A has 30 percent to kill B, then if he succeed, then he will not die, so his prob of death is 0, but if he missed, next round B will take the gun, so A can see he might die at next round is 70 percent of miss multiply 50 percent of B's shot, which equas to 35 percent, then next round......... Don't laugh I realized this is an endless loop and you don't know when the game will over because it's a probability game, of course my statistics grade in my school is so bad...
next attempt: So I try to understand this thing, normally if I am in this duel I would like to take first shot, I don't know why, cause if I am lucky and shoot that motherfucker to death at first round then I don't have to worry about dying, so I think the person first shoot has some advantage? I don't do any calculation at this attempt.
last attempt: Okay I feel the person first shoot has some advantages somehow but I don't really know, so I choose to ignore it and some how I figured an equation like $$\dfrac{\dfrac1{0.3}}{\dfrac1{0.3}+\dfrac1{0.5}}$$ as B's chance of winning? I feel it's not right either...
It's really some tough question, cuz I never encounter this thing before, and it seems easy but I can't find the direction to solve it, anyone can help a brother out? thx!
Comment: The probability that A kills B is:
$6/13$ and therefore the probability that B kills A is $7/13$

Think it in terms of geometric series
Answer: Nope, $B$ has a higher chance of winning. I just distributed percents to each person.
Round $1$:

$A$ has a $30\%$ chance of winning, so they get $30\%$
$B$ takes $50\%$ of the remaining $70\%$, so he gets $35\%$
Totals so far: $A-30\%$, $B-35\%$

Round $2$:

$A$ takes $30\%$ of the remaining $35\%$, so he gets $10.5\%$
$B$ takes $50\%$ of the remaining $24.5\%$, so he gets $12.25\%$
Totals so far: $A-40.5\%$, $B-47.25\%$

Round $3$:

A takes $30\%$ of the remaining $12.25\%$, so he gets $3.675\%$
B takes $50\%$ of the remaining $8.575\%$, so he gets $4.2875\%$
Totals so far: $A-44.125\%$, $B-51.5375\%$

By this time, $B$ is already over $50\%$, so we conclude that $B$ has a higher chance of winning. Also, $A$ has a $\frac 6{13}$ chance of winning and $B$ has a $\frac 7{13}$ chance of winning.
Comment: I fully understand your 3 rounds you state, but how come that directly jumps to `Also, A has a 6/13 chance of winning and B has a 7/13chance of winning.`?
Comment: The ratio will be preserved, so the limiting answer (with no cap on the number of rounds) is just 7/13 of the time B wins, 6/13 of the time A wins. The calculations for two more rounds were not necessary.
Comment: @Ian I just wanted to make the answer clearer
Comment: The percentages of A and B near  6/13 and 7/13 the number of rounds $\rightarrow ∞$
Answer:
So I first encounter this kind of questions, here is my analysis: first attempt: I think A has 30 percent to kill B, then if he succeed, then he will not die, so his probability of death is 0, but if he missed, next round B would take the gun, so A can see he might die at next round is 70 percent of miss multiply 50 percent of B's shot, which equals 35 percent, then next round......... Don't laugh I realized this is an endless loop and you don't know when the game will over because it's a probability game, of course, my statistics grade in school is terrible...

An endless loop, or as we prefer to call it, an iteration.
Let $p_{A\mid A}$ be the probability that $A$ ultimately wins given it is her turn to shoot. This happens if $A$ immediately wins, or if that fails then $A$ survives $B$'s shot and ultimately wins given its then $A$'s shoot again.   This defines $p_{A\mid A}$ by the iteration: kill, or miss and live to try again.
$$\begin{align}p_{A\mid A} ~=~& 0.30 + 0.70\cdot0.50\cdot p_{A\mid A} \\[1ex] 20 p_{A\mid A}~=~& 6+7p_A \\[2ex]\therefore\qquad p_{A\mid A}~=~&\dfrac{6}{13}\end{align}$$

And yes, this is a purely theoretical result.

I don't have to worry about dying, so I think the person first shoot has some advantage?

Well if $B$ shoots first then, $p_{B\mid B}=0.5+0.5\cdot 0.7 p_{B\mid B} \implies p_{B\mid B}={10}/{13}$, which means that $A$ has a much worse probability of ultimately winning when $B$ shoots first than if $A$ shoots first.
$$p_{A\mid B} = \dfrac 3{13}$$
So $A$ does have an advantage if she shoots first, but she's still a lousy shooter.
Comment: yeah that makes some sense it's an iteration, so I wonder if the iteration is like this: denote p(n) is the chance of winning of A in nth round, then  `p(1) = 30; p(2) = 0.3 + 0.5*0.7*p(1), then we can generally get p(n) = 0.3 + 0.5 * 0.7 * p(n-1) then we find the fixed point (I learned iteration before) of this iteration by making p(n)=p(n-1)`. the thing still confuse me is that I know in the  `p(n) = 0.3 + 0.5 * 0.7 * p(n-1) `, 0.3 is the basic possiblity of his shot,
Comment: and `0.5 * 0.7` is he got to live for next shot, but `0.5 * 0.7 * p(n-1)` confuses me, why the next chance to give a shot shot is multiply the previous possibility of winning? shouldn't it multiply the 0.3 instead? What can I say, I am a confused man...
Comment: The conditional probability of ultimately winning when given that $A$ survived the first turn is equal to the probability of ultimately winning at the start of the duel.  $$\mathsf P(A\text{ wins}\mid A\text{ goes next}) \\~=~ \mathsf P(A\text{ hits }B)+\mathsf P(A\text{ misses }B)\,\mathsf P(B\text{ misses }A)\,\mathsf P(A\text{ wins}\mid A\text{ goes next})$$
Comment: Oh I get it now, thx buddy!
Answer: This problem has a highly optimized mathematical solution.
Let us write it in formulas:
pX = pA + (1-pA) * (1-pB) * pX

We can divide both sides of this equation by pX:
1 = pA / pX + (1-pA) * (1-pB)

and therefore:
1 - (1-pA) * (1-pB) = pA / pX

pX = pA / (1 - (1-pA) * (1-pB))

or put it in other manner:
pX = pA / (pA + pB - pA * pB)

P.S. It's pretty funny to give an answer to last year's question ... But nevertheless, I ran into this problem myself and decided to share this solution) I found out about it on codeabbey.com

strange duel chances and my analysis


Adding two contextual filters (Content : nid)

Question: I want to display two type of contents : News and Events.
So I added them in the filters criteria. This works great.
Now I want them to be further filtered on the basis of the category the News and Events lie in. For example, I only want to display News and Events having category "xyz".
So what I did is, I added a reverse relationship for News and a contextual filter of Content : nid having the relationship that I made. This works OK and shows the desired news.
BUT
when I try to add another relationship and contextual filter, all the data disappears.
Any help in this regard would be highly appreciated!
Thanks!
Here are the sceenshots :
Comment: This is the correct and expected behavior. When you add two contextual filters, views expects to receive two contextual parameters. Your url should look something like this `example.com/pages/%/%` and both percent signs should hold a nid (and two different nids will probably result in no results as no node has two different ids. Can you update the question with the reset of the View?
Comment: Neo, thanks for getting back. Can you please let me know the way around on how to get the desired content?
Also, what do you mean by updating the question with "reset of thew view""?
Thanks again!
Comment: I meant 'the rest', a complete screenshot of all elements. From there we can get a better overview of what you have already.
Comment: Sure. I have added all of the screenshots that might help you here:
https://www.dropbox.com/s/6fgoarzh3m4d5y1/For%20Neo.zip?dl=0
Comment: Please edit the question and place them there. It is easier for us to answer and more helpful for future visitors running into the same problem.
Comment: Done. Please have a look at them now. Let me know in case you need other screenshots. Its allowing me to add only two.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/40487/discussion-between-waris-ali-and-neograph734).
Answer: When you add two contextual filters, views expects to receive two contextual filters. Currently in your preview area you are only supplying one (you need to add the second contextual filter (article filter: content nid) as well and separate them with a /). If you use the Provide nid from url filters it might work on the page, but in the preview you still need to provide both values.
However this is not the correct way to proceed, you should be doing something like this:
Since your block should only show on the industry page, you need to obtain the nid of the industry you are looking at. Use one contextual filter, and fill if with the default value: content id from url. This will load the industry nid you are looking at.
Then, since this industry has two different content types attached, you need to add relations to both of them. If the content relates to the industry (likely scenario) you should be using the reversed relationship as you currently do. If the industry links to the content, you should use the non-reversed relationship. I guess you did this step right.
The biggest problem here is that you do not use your relationships for the filters. So Your content > -365 days is not filtering the articles or news, but applies to the industry. The same happens with your content type. You want to display nodes of articles or news, but instead you filter the node you are looking at to be of those types (which fails as it an industry).
So edit your filters and set them to use the related content's fields.
You can only set one relation for each filter, so you'd have to create each filter twice (once for articles and once for news). Then use the drop down button above the Filters section to create an And / or group and drag the items in a way so the type is of article or news.


How do I programmatically get the URL of an entity referenced media image field using on a custom_preprocess_html() hook on THEME.theme?

Question: Reason: I need to create an Open graph meta tag og:image and pass the URL as content.
On THEME_preprocess_html(), I loaded the node using
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
      $nid = $node->id();
      if($node->hasField('field_image')){
        $image_id = $node->field_image->target_id;
        $image = \Drupal::entityTypeManager()->getStorage('file')->load($image_id);
      }
}

I have loaded the node and I was able to get the field_image_entity_id as shown. I want to get the URL of the image field of entity referenced field.
The below code gives me NULL. How can I load the media entity and get this value?
$image = \Drupal::entityTypeManager()->getStorage('file')->load($entity_img_id);

Comment: Possible duplicate of [Getting the image URL from a field\_image on a node](https://drupal.stackexchange.com/questions/137319/getting-the-image-url-from-a-field-image-on-a-node)
Comment: @GiorgosK I want to get the url first then I can print it. I am trying to get this in a preprocess hook and will use the twig template to render it.
Comment: I have tried the solution suggested by Berdir on that page but I am unable to load the url. $node->field_image->entity->getFileUri()
Comment: What do you mean by `its displaying the wrong file located in public directory`, your question perhaps is missing some vital information.  How are you getting the `entity_img_id` ?
Comment: Hi Giorgosk, I am getting the entity_image_id from $node->field_image->target_id; I am loading the entity using Media::load($field_image_id); this returns NULL, I used \Drupal::entityTypeManager()->getStorage('file')->load($entity_img_id); and this returns the wrong file.
Answer: ok, here is what worked for me. After digging through stack overflow, found that I was missing the ImageStyle and this resulted in not rendering the url.
I added
use Drupal\media\Entity\Media;
use Drupal\image\Entity\ImageStyle;
use Drupal\media_entity\MediaInterface;
use Drupal\node\Entity\Node;

and then on preprocess function, I loaded the media using the target_id that I got form the $node->field_image->target_id;
Then, I loaded the ImageStyle using
$media = Media::load($image_id);
$media_url = ImageStyle::load('TYPE_OF_CROP')->buildUrl($media->image->entity->getFileUri());
$variables['media_url'] =  $media_url;

Hopefully this helps people.
Answer: file_create_url has been deprecated. Use \Drupal::service('file_url_generator') instead.
$image_uri = $node->field_my_media->entity->field_media_image->entity->getFileUri();

$image_url = \Drupal::service('file_url_generator')->generateAbsoluteString($image_uri);

Comment: This helped me with an image field in Drupal 10. I already had `$node->field_my_media->entity` but it had no `getFileUri()`. Only going deeper `...->entity->field_media_image->entity` gave me the `entity` that I could call `getFileUri()` on. The first `entity` is `Drupal\media\Entity\Media`, the second entity is `Drupal\file\Entity\File`.
Answer: Just tested the following code and was able to get the image URL from field_image of the current node.
function THEMENAME_preprocess_html(&$variables) {
  //get the current node
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    if($node->hasField('field_image')){
      $image_url = file_create_url($node->field_image->entity->getFileUri());
    }
  }
}

Comment: Hi Giorgosk, Thanks for the response. I have tried this but it doesn't work. I am getting "Website is having an unexpected error" when I check logs, I don't see any errors logged. From what I notice, when the field_image tries to get to the entity($node->field_image->entity) it throws this error.

I have used all the necessary classes on the theme file, including Node, Entity, Media, EntityManager
Comment: The answer above is a working solution of what I see in your question.  Are you trying to get the image field of the current node and pass to twig for displaying ?
Please revise your question with all details about the image field and the node and fields setup and what you are trying to accomplish might help to understand better your problem.
Comment: Hi Giorgosk, I have updated the question again to best represent the issue.
Comment: Still the title of your question is very different from what you are asking in the question.  Please revise.  Is `$entity_img_id = 2581;` known ? how did you get it ?
Comment: As mentioned I got the image id from the $node->field_image->target_id. Thanks for the input
Comment: I have tried to give context as much as I can. Let me know if this makes sense.
Answer: In more recent version of Drupal 8, you can use:

$image_field = $node->get('field_image');
if ($image_field->isEmpty())
  return;
$media_entity = $image_field->referencedEntities()[0];
$uri = $media_entity->get('field_media_image')->entity->uri->value;
$variables['image_url'] = file_create_url($uri);


Recognize handwritten equations - OCR

Question: I am writing an app that recognizes handwritten equations on photos, I need a model that, with this photo as input:

Would return the following string: 9 - 3 / 1 / 3 + 1 =.
I already have a TensorFlow model, that can recognize digits, but it was trained with the "mnist" dataset, which means it won't be able to work with "real world data". My question is: where can I find good data sets to train my model and what are the alternatives to TensorFlow I could use to create it?
P.S I don't need my model to recognize complex symbols like the integral one.
Only simple symbols like +, -, =, /, * and the sqrt one
Answer: How about writing a program to generate random equations and creating an image out of it by replacing the digits with images from the MNIST data-set. Here is your equation with the digits replaced with images from the MNIST data-set, for better clarification:
Comment: Yes, but  how will my main model know how to convert 3 % 1 (fraction bar) 3 to 3 / 1 / 3

Recognize handwritten equations - OCR


RCM Exam Popular Selection Note Modifications

Question: For a piano RCM exam (let's say level 8), would an examiner likely reduce your score for making small adjustments to a "popular" piece to make the piece slightly easier to play?  For example, if the left hand is playing a 4 note arpeggio pattern, and you swapped the 4th note with a different note to make it easier to play, (1) Would the examiner likely notice? (2) If they did notice, would like likely reduce your score, (3) if they did, by how much?
Comment: One would hope the examiner would be marking on the performance of that particular version of the piece, chosen specifically for its position in the grading system. Any divergences would be marked down. Probably the *interpretation* would be open to conjecture, as those performance marks - pp, mf, rall, other dynamics, etc., are open to different interpretations, to a certain degree.
Answer: Summary

Yes, the examiner would very likely notice.
Yes, your score could change, but depending on the number and nature of the changes.
Small, unobtrusive changes — like changing a single note in a single arpeggio — would affect the score very little.

Based on my own experience as an adjudicator and a test prep teacher, I don't see a few small changes as causing significant problems.
Adjudicators are primarily looking for musicality and technical accuracy. So for a few minor changes, the adjudicator is likely to notice them — they're more than familiar with the music and will have a copy in front of them — but will probably just see it as a mistake. Score modifications shouldn't be significant unless 1) the performance of the piece is disrupted, 2) there are a substantial number of "mistakes", or 3) the changes are somehow enough to actually drop the grade of the piece.
However, a word of caution: if you find yourself needing to make changes, then you may not be ready for that level of exam. The exception to this would be a physical limitation, such as a hand-span that can't reach wide intervals.
Comment: Absolutely agree. If a piece needs to be changed, though, I'd advocate choosing a different one to present. There's always plenty to choose from!
Comment: If it's a popular piece then the examiner will have heard lots of unmodified performances, making the tweaked performance really obvious.
Comment: @BrianTHOMAS, RCM allows you to substitute an etude for what it calls a "popular" piece which is more like a "modern" piece from pop music, movies or video games.   I didn't mean "popular" like a well-known classical piece (like Fur Elise or something).  Here's the 2022 list is here: https://rcmusic-kentico-cdn.s3.amazonaws.com/rcm/media/main/about%20us/rcm%20publishing/popularselectionlist2022.pdf


How to determine an active screen (monitor) of my Application (window) using python PyQt5?

Question: I am working on an application which is using many widgets (QGroupBox, QVBoxLayout, QHBoxLayout). Initially it was developed on normal HD monitors. But, recently many of us upgraded to 4K resolution monitors. Now some of the buttons and sliders are compressed so small that they are unusable.
Now I tried to make some changes so that the application can be used with both HD and 4K monitors.
I started reading the link below:
https://leomoon.com/journal/python/high-dpi-scaling-in-pyqt5/enter link description here
I thought whenever my window is opened in a particular monitor I can call the following code:
if pixel_x > 1920 and pixel_y > 1080:
  Qapp.setAttribute(Qt.AA_EnableHighDpiScaling, True)
  Qapp.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
else:
  Qapp.setAttribute(Qt.AA_EnableHighDpiScaling, False)
  Qapp.setAttribute(Qt.AA_UseHighDpiPixmaps, False)

Then I tried to get the monitor resolution (pixel_x and pixel_y) using below code from using related post here.
import sys, ctypes

user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
screen_width  = 0 #78
screen_height = 1 #79
[pixel_x , pixel_y ] = [user32.GetSystemMetrics(screen_width), user32.GetSystemMetrics(screen_height)]

screen_width = 0, screen_height = 1 gives me the resolution of my primary monitor(mostly laptops in our case which are HD). screen_width = 78, screen_height = 79 gives me the combined resolution of virtual machines. But I do not understand how I can dynamically get these values depending upon where my application opened.
My application window is developed in such a way that it will open in the same monitor where it was closed last time. The problem is now I want to get the active monitor resolution whenever my GUI is called and adapt to that resolution. I would be glad if someone can help me out.
I am interested to know if I can call the screen resolution calculation every time that I drag my window from an HD monitor to a 4K monitor and Vice versa.
Edit: I have found something similar in this post here But I could not get much from this.
Edit2: Based on @Joe solution, Primary Screen Detection, Why is my primary screen always my laptop resolution even though I run the application on a 4K screen?

I just tried to get the dpi of all the screens using the code below:
def screen_selection():
  app = QApplication(sys.argv)
  valid_screens = []
  for index, screen_no in enumerate(app.screens()):
    screen = app.screens()[index]
    dpi = screen.physicalDotsPerInch()
    valid_screens.append(dpi)
  return valid_screens

Comment: PEOPLE please see this post, you thank me later: https://stackoverflow.com/questions/20243637/pyqt4-center-window-on-active-screen
Answer: One solution I came across is to use a temporary QApplication():
import sys
from PyQt5 import QtWidgets, QtCore, QtGui

# fire up a temporary QApplication
def get_resolution():

    app = QtWidgets.QApplication(sys.argv)

    print(app.primaryScreen())

    d = app.desktop()

    print(d.screenGeometry())
    print(d.availableGeometry())
    print(d.screenCount())

    g = d.screenGeometry()
    return (g.width(), g.height())

x, y = get_resolution()

if x > 1920 and y > 1080:
  QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
  QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
else:
  QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, False)
  QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, False)

# Now your code ...

This function will detect all attached screens:
# fire up a temporary QApplication
def get_resolution_multiple_screens():

    app = QtGui.QGuiApplication(sys.argv)
    #QtWidgets.QtGui
    all_screens = app.screens()

    for s in all_screens:

        print()
        print(s.name())
        print(s.availableGeometry())
        print(s.availableGeometry().width())
        print(s.availableGeometry().height())
        print(s.size())
        print(s.size().width())
        print(s.size().height())

    print()
    print('primary:', app.primaryScreen())
    print('primary:', app.primaryScreen().availableGeometry().width())
    print('primary:', app.primaryScreen().availableGeometry().height())

    # now choose one

You can use the hints here and here to get the screen where the application is running.
But I think primaryScreen should also return this:

primaryScreen : QScreen* const
This property holds the primary (or default) screen of the
  application.
This will be the screen where QWindows are initially shown, unless
  otherwise specified.

(https://doc.qt.io/qt-5/qguiapplication.html#primaryScreen-prop)
Comment: added links to my answer
Comment: Thanks for the answer. Unfortunately this is not working. I tried to implement the above function in Spyder IDE. I run the application in 4K monitor but still it returns my laptop resolutions.
Comment: Was the 4K attached to the laptop as second screen?
Comment: yes and my active application is opened in 4K monitor
Comment: Please try the other function I attached. Also check the `app.primaryScreen()` to see which screen is used.
Comment: your second code is working fine in detecting all screens. I find that, though I run my application in 4K screen (connected monitor), my laptop screen is detecting as primary screen. Please find the edit part to find a attachment
Comment: Unfortunately not, it is showing my laptop screen as primary screen always, irrespective of where I run my program.
Comment: Is it maybe related to the primary Windows screen?
Comment: Exactly, In this link it mentioned, primary screen is where OS is installed, may be it is detecting same
https://www.bestusbpoweredmonitor.com/2017/12/11/how-to-change-primary-monitor/
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/204035/discussion-between-joe-and-rohithsai-sai).
Answer: Well, after creating the MainWindow, you can just call QMainWindow.screen(). This returns the current screen the MainWindow is on. This would at least allow you to check the screen resolution at the start of your application.
Right now there is no such thing as a screenChangeEvent. However i am sure you can create one by subclassing the MainWindow and overloading the QMainWindow.moveEvent
For example:
    class MainWindow(QtWidgets.QMainWindow):
        screenChanged = QtCore.pyqtSignal(QtGui.QScreen, QtGui.QScreen)

        def moveEvent(self, event):
            oldScreen = QtWidgets.QApplication.screenAt(event.oldPos())
            newScreen = QtWidgets.QApplication.screenAt(event.pos())

            if not oldScreen == newScreen:
                self.screenChanged.emit(oldScreen, newScreen)

            return super().moveEvent(event)

This checks if the screen has changed. If it has it emits a signal. Now you only need to connect this signal to a function that sets your dpi attributes. The event gives you access to the old and to the new screen.
Warning:
One of the screen can be None at the start of your application because there is no oldScreen when you first start your application. So please check this.
Comment: Körnet thank you for the solution. But, there is no method called  QMainWindow.screen() in PyQt5 atleast what I have understood. If am wrong kindly show me some link for python (PyQt5)
Comment: I also couldn't find it in the documentation. However every `QWidget` supports this method as you can see [here](https://doc.qt.io/qt-5/qwidget.html#screen). `QMainWindow` subclasses `QWidget.`
I have also tested my code and it worked. Please just checks if it works for you as well.
Comment: I would also recommend using the solution with subclassing the `QMainWindow` and overloading the `moveEvent`. This works 100% and provides more functionality for you. You can just take the code i provided and use it. The piece of code works fine and i get correct `screenChanged` signal whenever i move the ``MainWindow` on another screen.
Comment: I am interrested to know how you said tested and worked. Firstly when I use QMainWindow.screen() it throws an error saying it has no attribute. Secondly for moveEvent getting an error 'QApplication' has no attribute 'screenAt'. I want to understand if you have implemmented in Python.
Comment: Yes of course i am using python. My `PyQt5` version is 5.13.2
You can see right [here](https://www.riverbankcomputing.com/static/Docs/PyQt5/api/qtgui/qguiapplication.html) that the official PyQt5 reference also lists the `QApplication.screenAt` method.
Answer: Though i could not get the direct solution I am able to develop a method to get what I was looking. With the help of few links and previous post I am able to achieve. with this post I got an idea of tracking the mouse event.
I developed a method to track all the monitors and respective staring positions. if my variable naming is not appropriate I am happy to accept the changes
def get_screen_resolution():
  app = QApplication(sys.argv)
  screen_count = QGuiApplication.screens()
  resolutions_in_x = []

  for index, screen_names in enumerate(screen_count):
    resolution = screen_count[index].size()
    height = resolution.height()
    width = resolution.width()
    resolutions_in_x.append(width)

  low_resolution_monitors = {}
  high_resolution_monitors = {}

  for i, wid_res in enumerate(resolutions_in_x):
    if wid_res > 1920:
      high_resolution_monitors.update({i: wid_res})
    else:
      low_resolution_monitors.update({'L': wid_res})
  temp_value = 0
  high_res_monitors_x_position = []
  low_res_monitors_x_position = []
  for i in range(len(screen_count)):
    temp_value = temp_value+resolutions_in_x[i]
      if resolutions_in_x[i] in high_resolution_monitors.values():
        high_res_monitors_x_position.append(temp_value-resolutions_in_x[i])
      else:
        low_res_monitors_x_position.append(temp_value-resolutions_in_x[i])

  total_width_res = []
  pixel_value = 0
  first_pixel = 0
  for i, wid_value in enumerate(resolutions_in_x):
    pixel_value = pixel_value + wid_value
    total_width_res.append(tuple((first_pixel, pixel_value-1)))
    first_pixel = pixel_value

  return high_res_monitors_x_position, low_res_monitors_x_position, total_width_res

def moveEvent(self, event):

screen_pos = self.pos()
screen_dimensions = [screen_pos.x(),screen_pos.y()]
super(MainWindow, self).moveEvent(event)

Window_starting_pt = screen_pos.x()
for i, value in enumerate(self.total_width_res):
  if value[0]<=Window_starting_pt+30 <=value[1] or value[0]<=Window_starting_pt-30 <=value[1]: #taking 30pixels as tolerance since widgets are staring at some negative pixel values
    if value[0] in self.high_res_monitors_x_position:
      QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
      QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
    else:
      QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, False)
      QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, False)

With aboe two functions am able to track my application(window) position and also able to track when ever it is dragged among windows


Finiteness of Improper integral

Question: How do I show that if $t> 1/2$, then
$$\int_R \dfrac{1}{(1+x^2)^t}dx $$ is finite?
I tried to use the p-test, but since $\int_R \dfrac{1}{x^p}$ diverges for all $p$, I could not show the finiteness of above integral
Answer: HINT:
For $t>0$ and $x\ne 0$, we have
$$(1+x^2)^t>x^{2t}\implies \frac{1}{(1+x^2)^t}\le \frac{1}{x^{2t}}$$
And we have $$\int_0^L \frac{1}{(1+x^2)^t}\,dt=\int_0^1 \frac{1}{(1+x^2)^t}\,dt+\int_1^L \frac{1}{(1+x^2)^t}\,dt$$
Answer: As soon as $t\geq 0$ the integral $\int_{-1}^{1}\frac{dx}{(1+x^2)^t}$ is bounded by the constant $2$, so there are no integrability issues close to the origin. And as soon as $t>\frac{1}{2}$ we have
$$ 0\leq \int_{-\infty}^{-1}\frac{dx}{(1+x^2)^t}=\int_{1}^{+\infty}\frac{dx}{(1+x^2)^t}\leq \int_{1}^{+\infty}\frac{dx}{x^{2t}}=\frac{1}{2t-1}.$$
The exact value of the integral is given by $\frac{\Gamma\left(t-\frac{1}{2}\right)}{\Gamma(t)}\sqrt{\pi}$ due to Euler's beta function.
For moderately large values of $t$ we have $\int_{\mathbb{R}}\frac{dx}{(1+x^2)^t}\approx\sqrt{\frac{\pi}{t}}\left(1-\frac{3}{8t}\right)^{-1}.$
Answer: $\displaystyle\Re\left(-2t + 1 < 0\right) \implies
\bbox[10px,#ffe,border:1px dotted navy]{\displaystyle\Re\left(t\right)\ >\
{1 \over 2}}$.

Finiteness of Improper integral


Earliest hook to generate content during user registration

Question: During the user registration process in Drupal 7, at which point can I access the newly created UID to create 'default content' for that user?  I would like to do this as early on as possible.  Preferably before the user has been approved by an admin or before they have verified their email address.
Answer: You can use hook_user_insert(), it should be early enough for you.
Technically speaking, hook_user_presave() is the first hook called from user_save() (even before the user is written to the database), but according to the documentation it is "primarily intended for modules that want to store properties in the serialized {users}.data column". More importantly, it is also invoked when a user account is updated, so that wouldn't fit your use case.
Answer: Implement hook_user_insert().


How to clear file input on button click in react class component?

Question: I want the selected file to be removed when I click the button. Using the below example
<code>this.state{ file:null}

 <input type="file" onChange={this.handleFile}/>

<button type="submit" onClick={this.handleSubmit}>Continue</>

handleSubmit (){
      this.setState({file: null})
      }
</code>
Comment: Does this answer your question? [How can I clear an HTML file input with JavaScript?](https://stackoverflow.com/questions/1703228/how-can-i-clear-an-html-file-input-with-javascript)
Answer: It is basically impossible to change the text in an input/type=file field. The reason for this is that it would open up a huge security hole.
Try using an <input type=reset> button?


How do I check an objects property types?

Question: Sorry for the title, I couldn't find a better way to write it =/
I am receiving a error object called ErrorBase.
If there is only one error it will return me the following:
public 'ErrorBase' =>
      public 'CODIGO_ERRO' => string '1' (length=1)
      public 'MENSAGEM_ERRO' => string 'Autenticação Inválida' (length=24)
      public 'TIPO_ERRO' => string 'Usuario' (length=7)

But if there is more than one error, it will return me a array of objects like this:
public 'ErrorBase' =>
array
  0 =>
    object(stdClass)[30]
      public 'CODIGO_ERRO' => string '1' (length=1)
      public 'MENSAGEM_ERRO' => string 'Autenticação Inválida' (length=24)
      public 'TIPO_ERRO' => string 'Usuario' (length=7)
  1 =>
    object(stdClass)[31]
      public 'CODIGO_ERRO' => string '002' (length=3)
      public 'MENSAGEM_ERRO' => string 'teste 002' (length=9)
      public 'TIPO_ERRO' => string 'tipo 002' (length=8)
  2 =>
    object(stdClass)[32]
      public 'CODIGO_ERRO' => string '003' (length=3)
      public 'MENSAGEM_ERRO' => string 'teste 003' (length=9)
      public 'TIPO_ERRO' => string 'tipo 003' (length=8)
  3 =>
    object(stdClass)[33]
      public 'CODIGO_ERRO' => string '004' (length=3)
      public 'MENSAGEM_ERRO' => string 'teste 004' (length=9)
      public 'TIPO_ERRO' => string 'tipo 004' (length=8)

How can I work with these situations?
How do I check if there is a array of objects or only a object?
Thanks in advance for any help.
Comment: so the class `ErrorBase` also has a property called `ErrorBase` ? in that case `if(is_array($instanceOfErrorBase->ErrorBase)) { /* stuff */ }`
Comment: What is ErrorBase ? Your pseudo-code is not very clear.
Comment: is just a class...this is a var_dump() of the returned class
Answer: Try... is_object() and is_array()
Comment: Both ways will return me a object, as it is, I need to check the property type, thanks ;)
Answer: is_array($variable) returns true if $variable contains an array, and false otherwise.
Comment: it won't work because I'll always have a object as return and this object have a array inside, I need to check if what is inside this object is a array of objects
Answer: To test the class of an object :
if ($var instanceof ErrorBase) {

To test if it is an array :
if (is_array($var)) {

Answer: Use is_array() :
if (is_array($this->ERROR_BASE))

Comment: it won't work because its a class, it will always return me a object with arrays inside it
Comment: I have checked for the type on both results and both returns me a object, no t a array.
Answer: use gettype() to returns the vars type.
or use is_array/is_object to test for each
Comment: it will return a object always...I need to check what is inside that object...not what the object is...


Entities, bundles and fields

Question: I've created entities and bundles through Entity Construction Kit UI, and now I'm trying to re-create everything with code, in a module.
I managed to generate entity with Drupal console, added fields, and everything works well.
The problem is when I try to create bundles for an entity, with different fields.
In ECK, I can create an entity, then bundles, and add different fields to each bundle.
However, I can't understand how to do it in the code, and after reading tons of documentation, it feels like bundles are only configuration entities and can't have fields.
So my questions are :

Is there something I don't understand ?
How can I mimic ECK "bundles with fields" in code ? My goal is to create profiles, like the profile module can do for users, but referenced from an other entity, and with specific behavior, so I'd prefer create my own entities.
Comment: I finally found https://drupal.stackexchange.com/questions/204261/how-to-create-custom-eck-entity-class-per-bundle?rq=1 that explains it's not managed by Drupal, and ECK is using tricks to make this work.
Comment: At the moment define entity types in code and "bundles with fields" in /config/install/*.yaml. It was planned from the beginning to make bundles with fields possible in code, but work is still in progress, see this issue https://www.drupal.org/node/2346347
Comment: @4k4 Thanks for your answer and for the link, this answers my question.
Answer: Yes, the bundle entities themself are not fieldable.
But bundle config entities in the end only exist to manage bundles for the content entity type, and as far as content entities are concerned, bundles are basically just a string (and a bit of metadata like a title). It's even possible to have bundles based on plugins or other things.
Per-bundle fields (usually configurable fields defined only in config, but it would be possible to define them in code as well, currently not trivial) are then attached to a content entity type + specific bundle. Fields actually consist of two definitions: field storage, which is tied to the entity type and defines name and storage-level settings, and the field, which is for a bundle and has bundle-level settings, label and so on. Base field definitions defined in the baseFieldDefinitions() method are exposed as both the field storage and field definition.
Haven't yet read it in detail, but http://www.daggerhart.com/drupal-8-custom-entities-bundles/ is a recent (as in, ~1h old) extensive resource on how to build entity types with bundles.

Entities, bundles and fields


Bash - read case with multiple selections

Question: I'm using the following code in a script.
#!/bin/bash

while true; do
    read -p "Do your Choice: [1] [2] [3] [4] [E]xit: " choice
    case "$choice" in
        [1]* ) echo -e "$choice\n"; break;;
        [2]* ) echo -e "$choice\n"; break;;
        [3]* ) echo -e "$choice\n"; break;;
        [4]* ) echo -e "$choice\n"; break;;
        [Ee]* ) echo "exited by user"; exit;;
        * ) echo "Are you kidding me???";;
    esac
done

My question is, how can I get the script to accept multiple Choices.
so input like: 1,4, would run case [1] and [4]?
Answer: Set IFS to include commas:
IFS=', '

Then process the choices in a loop (note the -a flag for read so the input is treated as an array):
while true; do
    read -p "Do your Choice: [1] [2] [3] [4] [E]xit: " -a array
    for choice in "${array[@]}"; do
        case "$choice" in
            [1]* ) echo -e "$choice\n";;
            [2]* ) echo -e "$choice\n";;
            [3]* ) echo -e "$choice\n";;
            [4]* ) echo -e "$choice\n";;
            [Ee]* ) echo "exited by user"; exit;;
            * ) echo "Are you kidding me???";;
        esac
    done
done

Comment: I guess OP's code uses the `break` to exit from the `while` loop.


Set scrollHeight on HTML page?

Question: I have a lot of empty space at the bottom of my HTML page, most likely because there is a transparent flash move loaded as a fallback. Is it possible to set the scrollHeight so there is no useless empty space at the bottom of the screen?
Answer: Set display:none on the HTML element that serves as the container for the flash fallback content.

Set scrollHeight on HTML page?


How to access a layout within a listView in android

Question: I have a ListView in an Activity and in that ListView I have another Layout which gives the list its content. Here is the code
SimpleAdapter adapter = new SimpleAdapter(this.getActivity(),listvalue,
                 R.layout.singlepost,v,s);
list.setAdapter(adapter);

singlepost is the layout I load into the listView but this singlepost has a couple of buttons I want to access but i cannot access thebuttons because it is not loaded with the activity containing the ListView so when i try to access the button like this
ImageButton star = (ImageButton)findViewById(R.id.star);

It Tells me the View you are trying to access is not within this activity. I know it is impossible to use two setContentView(R.layout.activity_main); except you use Fragments. so how do I access the button in the singlepost layout.
Note: When I mean Access, I mean to click and have the button do something and I have done all the necessaries declarations and instantiations all i need is a way to access that button. Thanks. Hope My question is clear enough.
Answer: I am pretty you will have to make your own adapter that extends some Adapter (SimpleAdapter, ArrayAdapter, ...). And in the getView() method set any neccessary listeners:
public class MySimpleArrayAdapter extends ArrayAdapter<String> {

    private final Context context;
    private final String[] values;
    private LayoutInflater inflater;

    public MySimpleArrayAdapter(Context context, String[] values) {
        super(context, R.layout.row_layout, values);
        this.context = context;
        this.values = values;
        this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if(convertView == null){
            convertView = inflater.inflate(R.layout.row_layout, parent, false);
        }

        Button button = (Button) convertView.findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
               public void onClick(View v) {
                  // Perform action on click
               }
            });

        return convertView;
    }

}

EDIT: Or an example with SimpleAdapter. Note that I haven't tried it, but it should theoretically work I believe.
public class MyAdapter extends SimpleAdapter {

    private List list;

    public MyAdapter(Context context, List  list, int resource, String[] from, int[] to) {
        super(context, list, resource, from, to);
        this.list = list;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = super.getView(position, convertView, parent);

        Button button = (Button) convertView .findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
            }
        });

        return convertView;
    }
}

Comment: so do I take out my initial SimpleApadter declaration and replace with this new class?
Comment: yes, but if you extend `ArrayAdapter` as in this example, you will have to set all the `TextView`s as well.
Comment: @daviestobialex or see edit for an example with `SimpleAdapter`.
Comment: @daviestobialex yeah sorry that did suppose to say convertView.findViewById(); Which example gives you NPE?