text:
Q: Retaining and retrieving value in a EditText in CustomListView I am trying to create a ListActivity that has a CheckBox, TextView and EditText in a row in a custom list.
I need to get the user's input in my EditText and save that value in a database when the CheckBoxfor that row is selected.  If the CheckBoxis not selected then the EditText is disabled.  The latter I can do, but I'm not able to retain the value of the EditText and store it in database.
Currently, if I input anything in EditText and press backbutton to minimize the keypad the EditText goes back to its previous value.
I have coded the below till now for displaying the custom ListView and selecting and unselecting the checkbox. I just need help me with the EditText part.
EditExepense.Java
package h.pkg.main;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class EditExpense extends ListActivity {
    int eid, tid, mid;
    String etyp,amount;
    float eamt;
    DBAdapter db;
    ArrayList<Integer> memmid = new ArrayList<Integer>();
    ArrayList<String> memname = new ArrayList<String>();
    ArrayList<Float> memcexp = new ArrayList<Float>();
    List<Model> list = new ArrayList<Model>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button Save = (Button)findViewById(R.id.Save);
        //ListView l1= (ListView)findViewById(R.id.listView1);
        setContentView(R.layout.eexp);
        Bundle idata = getIntent().getExtras();
        db = new DBAdapter(this);

        if (idata !=null)
        {
            eid=idata.getInt("EID");
            tid=idata.getInt("TID");
            etyp=idata.getString("ETYP");
            eamt=idata.getFloat("EXAMT");
            amount = "" + eamt;
        }

        try {
            db.open();
            Cursor c = db.getAllmem(tid);
            float nofm = (float)(c.getCount());
            float evenshareamt = eamt/nofm;
            db.close();

            if (c != null ) {
                if  (c.moveToFirst()) {
                    do {
                        String MN = c.getString(c.getColumnIndex("NAME"));
                        mid = c.getInt(c.getColumnIndex("MID"));
                        String ceamts = String.valueOf(evenshareamt);

                        list.add(get(MN,ceamts,true));

                        memname.add(MN);
                        memmid.add(mid);
                        memcexp.add(evenshareamt);
                    } while (c.moveToNext());
                }
            }

            c.close();
        } finally {
        }

        ArrayAdapter<Model> adapter = new InteractiveArrayAdapter(this,list);
        setListAdapter(adapter);

        RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
        RadioButton rbs = (RadioButton) findViewById(R.id.Shared);
        RadioButton rbc = (RadioButton) findViewById(R.id.Custom);

        radioGroup.setOnCheckedChangeListener( new OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rbs = (RadioButton) findViewById(R.id.Shared);

                if (rbs.isChecked()) {
                    //DisplayToast("Option 1 checked!");
                } else {
                    //DisplayToast("Option 2 checked!");
                }
            }
        });
    }

    public void expUpdate(View V) {
        setResult(RESULT_OK);
        finish();
    }

    private Model get(String memn, String ceam, boolean sel) {
        return new Model(memn,ceam,sel);
    }
}

InteractiveArrayAdapter.Java
package h.pkg.main;
import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

public class InteractiveArrayAdapter extends ArrayAdapter<Model> {
    private final List<Model> list;
    private final Activity context;

    public InteractiveArrayAdapter(Activity context, List<Model> list) {
        super(context, R.layout.listview, list);
        this.context = context;
        this.list = list;
    }

    static class ViewHolder {
        protected TextView memnames;
        protected EditText ceamount;
        protected CheckBox checkbox;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            view = inflator.inflate(R.layout.listview, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.memnames = (TextView) view.findViewById(R.id.memname1);
            viewHolder.ceamount = (EditText) view.findViewById(R.id.expamt1);
            viewHolder.checkbox = (CheckBox) view.findViewById(R.id.chkbox1);
            viewHolder.checkbox.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                                                            boolean isChecked) {
                    Model elementc = (Model) viewHolder.checkbox.getTag();
                    elementc.setSelected(buttonView.isChecked());
                    boolean edenable = buttonView.isChecked();
                    if(edenable)
                    {
                        viewHolder.ceamount.setEnabled(true);
                    } else {
                        viewHolder.ceamount.setText("");
                        viewHolder.ceamount.setEnabled(false);
                    }
                }
            });

            view.setTag(viewHolder);
            viewHolder.checkbox.setTag(list.get(position));
        } else {
            view = convertView;
            ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
        }

        ViewHolder holder = (ViewHolder) view.getTag();
        holder.memnames.setText(list.get(position).getName());
        holder.ceamount.setText(list.get(position).getCeamt());
        holder.checkbox.setChecked(list.get(position).isSelected());
        return view;
    }
}

Model.Java
package h.pkg.main;

public class Model {
    private String name;
    private String ceexpamt;
    private boolean selected;

    public Model(String name, String ceexpamt, boolean selected) {
        this.name = name;
        this.ceexpamt = ceexpamt;
        this.selected = selected;
    }

    public String getName() {
        return name;
    }

    public String getCeamt() {
        return ceexpamt;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setCeamt(String ceamt) {
        this.ceexpamt = ceamt;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

    public void enableEditText()
    {

    }
}

A: Hi All thanks for the answers.. But Since am already using a Model class... I tried to achieve the task done through that example itself... Please see the modified InteractiveArrayAdapter.Java this works fine in retaining the value of the edittext in the correct row after editing.
I have just added this method.. to my InterativeArrayAdapter.java
viewHolder.ceamount.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // TODO Auto-generated method stub
                 if (!hasFocus){
                     viewHolder.ceamount.setFocusable(true);
                     Model elemente = (Model) viewHolder.ceamount.getTag();
                     final EditText custamt = (EditText) v;
                     elemente.setCeamt(custamt.getText().toString());
                }
            }
        });

Please see below for the complete code..
package h.pkg.main;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

public class InteractiveArrayAdapter extends ArrayAdapter<Model> {

    private final List<Model> list;
    private final Activity context;

    public InteractiveArrayAdapter(Activity context, List<Model> list) {
        super(context, R.layout.listview, list);
        this.context = context;
        this.list = list;
    }

    static class ViewHolder {
        protected TextView memnames;
        protected EditText ceamount;
        protected CheckBox checkbox;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            view = inflator.inflate(R.layout.listview, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.memnames = (TextView) view.findViewById(R.id.memname1);
            viewHolder.ceamount = (EditText) view.findViewById(R.id.expamt1);
            viewHolder.checkbox = (CheckBox) view.findViewById(R.id.chkbox1);
            viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(CompoundButton buttonView,
                                boolean isChecked) {
                            Model elementc = (Model) viewHolder.checkbox.getTag();
                            elementc.setSelected(buttonView.isChecked());
                            boolean edenable = buttonView.isChecked();
                            if(edenable)
                            {
                            viewHolder.ceamount.setEnabled(true);
                            }
                            else
                            {
                                viewHolder.ceamount.setText("");
                                viewHolder.ceamount.setEnabled(false);
                            }

                        }
                    });

            viewHolder.ceamount.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                     if (!hasFocus){
                         viewHolder.ceamount.setFocusable(true);
                         Model elemente = (Model) viewHolder.ceamount.getTag();
                         final EditText custamt = (EditText) v;
                         elemente.setCeamt(custamt.getText().toString());
                    }
                }
            });
            view.setTag(viewHolder);
            viewHolder.memnames.setTag(list.get(position));
            //viewHolder.memnames.setId(position);
            viewHolder.checkbox.setTag(list.get(position));
            //viewHolder.checkbox.setId(position);
            viewHolder.ceamount.setTag(list.get(position));
            //viewHolder.ceamount.setId(position);
        } else {
            view = convertView;
            ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
            ((ViewHolder) view.getTag()).memnames.setTag(list.get(position));
            ((ViewHolder) view.getTag()).ceamount.setTag(list.get(position));
        }

        ViewHolder holder = (ViewHolder) view.getTag();
        holder.memnames.setText(list.get(position).getName());
        holder.ceamount.setText(list.get(position).getCeamt());
        holder.checkbox.setChecked(list.get(position).isSelected());
        return view;
      }
}

A: In your adapter , use Map<Integer,Boolean> and Map<Integer,String> to store the status of checkbox and the value of editText

A: A Map is a link between two data types, so a Map from Integer to Boolean is a one-to-one function from a particular integer value to a corresponding Boolean value ( 1 -> true , 2 -> false etc.) So this would essentially allow you to maintain a "mapping" for each list position to the status of the checkbox.
The way to implement a Map in java is thus:
Map<Integer,Boolean> listMap = new HashMap<Integer,Boolean>();

and when you wish to add a mapping from one list element to it's boolean status then you'd have to use this code:
listMap.put(yourListPositionInIntValue, statusOfCheckboxInTrueOrFalse);

and when you wish to modify the boolean value in the map all you have to do is repeat the above line of code with the same ListPosition and the updated boolean value.


text:
Q: Should we able to keep edits when rejecting and editing? Context:
Today I encountered an issue when reviewing an edit. The edit itself was on a poorly formatted question, and it fixed the formatting, but added another question from the editor. My semi-viable options were to:

*

*Improve the edit, then remove the new question raised by the editor. This (in my opinion) wouldn't be the best course of action due to the +2 reputation gain which may encourage bad edits

*Reject and improve, which may be alright, but the code was incredibly long. Choosing to reject and edit would reset all previous changes by the edit suggester. I found it very inconvenient to have to reindent and format

*Reject altogether then going back to edit the indentation, thus leading to the same problem mentioned above and would need 2 others to do the same

None of these options seemed perfect. I leaned towards rejecting and editing as it wouldn't give +2, but as mentioned above I would have to reindent everything. I finally opted to improve the edit, removing the extra question, but I felt the +2 shouldn't have been given.
Proposal:
Before I start, I was wondering what happened to this "feature". This would probably solve the problem.
The problem I'm experiencing is that when I see an okay suggested edit, but there's one part that invalidates the suggestion, I would have to reject and redo the good part of the edit if I were to reject and edit. Others would probably recommend to just improve the edit, but what if that one bad part of the edit doesn't warrant the +2 given when improving an edit?
My proposal is to have a button, when rejecting an editing, that restores the suggested edit:

So, in the above situation, instead of having to reindent and reformat (the good part of the edit) when rejecting and editing, I could just restore the suggesting and edit out the additional question (the bad part of the edit). This would not reward the user with +2 and would ultimately be the better choice in my opinion.

A: Something of a workaround:

*

*Click Improve Edit to get the edit box.

*Select and copy all the text (Ctrl+A, Ctrl+C).

*Click the "cancel" link to get back to the main review task view.

*Click Reject and Edit to get an edit box for rejection.

*Replace the text with the suggestion on your clipboard (Ctrl+A, Ctrl+V).

*Edit as necessary and submit.

The suggestion is considered rejected, but you didn't have to redo all the good parts in the body. You do have to manually handle the title and tags, though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WooCommerce: Get meta fields from product attributes on product page I want to display a specific product attribute on my product page in WooCommerce.
But I want to show not only the name but some extra information like a description and an image.
At the moment I'm using wc_get_product_terms for that:
<?php
    global $product;
    $values = wc_get_product_terms( $product->id, 'pa_attribute', array( 'fields' =>  'all' ) ); if( $values ) : ?>

                <?php foreach ( $values as $term ) : ?>

                    <?php $icon = get_field('pa_attribute_icon', 'pa_attribute_'.$term->term_id); if( !empty($icon) ): ?>

<img src="<?php echo $icon['url']; ?>" alt="<?php echo $icon['alt']; ?>" />

                    <?php endif; ?>

<?php echo $term->name; ?>

                <?php endforeach; ?>

    <?php endif; ?>

I have read, that wc_get_product_terms is deprecated. Is there a better/newer solution to display the attributes with the additional informations?

A: wc_get_product_terms is not deprecated. woocommerce_get_product_terms it is.


text:
Q: How do I prevent a ListView from receiving clicks when another View or Fragment is over it? I have a ListView that displays some data. The rows can be clicked as well.
I also have a custom Fragment at the bottom of the screen that "hovers" over the ListView all the time. I want this Fragment to also pick up click events so that I can do stuff when it's clicked.
The issue is that I can't figure out how to do that, and the ListView ends up getting the click instead, even when the Fragment covers that particular row.
Basically, I want to make sure that when there is a Fragment (or even another View) on top of the ListView, that Fragment registers the click when I click on it, and not the ListView.
How do I do this?

A: If another View or Fragment is over it, you can prevent clicks from reaching through by setting the android:clickable attribute to true on the root of the layout that is presented on top of something else clickable.
The same goes for the layout inflated in the Fragment displayed on top of something else, just set android:clickable to true on the root of the inflated layout.
android:clickable="true"


text:
Q: Where can I find stories from people moving from a Windows OS? I am seeking a place where to find stories of individuals and businesses that may have switched from a Windows OS to Ubuntu and were/are happy with their switch and why?

A: I switched from using windows XP almost exclusively, to using Ubuntu exclusively about a year ago.  I made the switch because my installation of XP broke.  A re-install was not possible because I lost the product key.
The switch to Ubuntu was pretty brutal.  I needed my computer for college work etc. and it really took me a while to get used to.  Naturally I was looking for a windows like UI so I decided to try Kubuntu after a while.  This I did not like for some reason.  (KDE is a bit cumbersome I think).
I decided to try openSUSE because of their commitment to KDE, but I couldn't get used to YaST.  I tried some others (Debian and Arch Linux), but due to my rather limitted knowledge of the Linux OS I didn't get very far.  Eventually, I ended up using good ol' ubuntu again.  Since I hadn't used Ubuntu in the GNOME 2 era, Unity did not bother me so much.
When 12.10 came out I upgraded (which broke my install).  Rather than re-install ubuntu I figured I should try some other linux flavours.  Eventually I stuck with Arch Linux.  I stuck with it because I loved the minimalistic system I was able to build, as well as the pacman package manager.
On my laptop I still use Ubuntu because it requires much less maintainance than arch, and handles WI-FI connectivity out of the box.
At work I also use Ubuntu (I had no choice really), but I use the xfce desktop environment because it runs smoother on the hardware.
I have also recently re-installed windows (windows seven this time) for compatibility reasons, and because I like gaming.
My conclusion is that, unless you are intending to game or require specific software, Linux (which distro does not matter so much) is a superior OS, especially for software development.
As for Ubuntu itself, it is certainly not my favourite distro, (I prefer more lightweight alternatives) but with the xfce or lxde desktop environment it is very usable.  By far my favourite though is Arch Linux.
https://wiki.archlinux.org/index.php/Arch_Linux


text:
Q: Delegate.BeginInvoke Thread I Know that Delegate.BeginInvoke() initiates the asynchronous call on a separate thread taken from the ThreadPool. But i still have a confusion whether that thread must be always different from caller thread or both method can be on the same thread.

A: The function is called asynchronously (so it must be on a different thread). You can execute something in between and possibly wait for the asynchronous operation to finish with EndInvoke.


text:
Q: shifting a DIV under position:fixed divs I'm not entirely sure how to explain my question, so I'll just provide you with a demo of my problem: http://voxldesigns.com/jbg-test/
As you can see, the two header bars are overlapping the text area. How would I shift the text area downwards so it is underneath the header bars, without overlapping?
Thanks.


text:
Q: How to convert part of a big std::string into a float efficiently? void OBJLoader::load_vec(const char* line_prefix) {
size_t jump = 0;
size_t strpos = 0;
if (line_prefix == "v ") {
    while ((strpos = buffer.find(line_prefix, strpos)) != string::npos) {
        strpos++;
        vcoord_vec.emplace_back(stof(&buffer.at(strpos), &jump));
        strpos += jump;
        vcoord_vec.emplace_back(stof(&buffer.at(strpos), &jump));
        strpos += jump;
        vcoord_vec.emplace_back(stof(&buffer.at(strpos), &jump));
        strpos += jump;
    }
    return;
}
//(...)

This is the code I use to convert the text inside buffer string to float and put it inside a vector. The important part of the string itself has such structure:
v -0.893339 0.784809 0.891470
v -0.893339 -0.784809 0.891470
v -0.692655 -0.634043 0.017402
v 0.692655 0.586786 -0.017402
v -0.710057 0.651445 0.000000
v 0.710057 -0.604188 0.000000
v 0.017402 -0.571364 -0.674429
v -0.017402 0.618621 0.674429
v 0.000000 -0.636023 0.691831

using vcoord_vec.emplace_back(stof(&buffer.at(strpos), &jump)) it takes about 200ms to load a single value into a vector while this:
void OBJLoader::load_vec(const char* line_prefix) {
    char* cbuffer = const_cast<char*>(buffer.c_str());
    if (line_prefix == "v ") {
        while (cbuffer = strstr(cbuffer, line_prefix)) {
            cbuffer++;
            vcoord_vec.emplace_back(strtof(cbuffer, &cbuffer));
            vcoord_vec.emplace_back(strtof(cbuffer, &cbuffer));
            vcoord_vec.emplace_back(strtof(cbuffer, &cbuffer));
        }
        return;
    }
//(...)

loads 4 718 598 of them in 489ms. What would be the "C++ way" of converting a part of a string at known index into whatever type of number with comparable efficiency?

A: You are using std::stof wrong. You are passing it a char* when it is expecting a const std::string&.
The result of that is an implicit conversion from char* to std::string in each call to std::stof, copying the whole content of buffer starting at strpos to its null-terminator into the temporary created by the conversion for the function parameter.
Prefer std::from_chars if available (C++17) and otherwise I'd suggest sticking with std::strtof for the conversion (that does not mean you have to keep using strstr). std::stof is specified to call std::strtof anyway.

A: For really basic formats with space-delimited values like you're using, you can use C++ streams:
#include <sstream>

/*...*/

char id;
float v[3];

std::istringstream iss("v 123.4 12.5 0262.2");
iss >> id;
if (id == 'v') {
    iss >> v[0] >> v[1] >> v[2];
}

A: Here's a utility class that I use within my 3D Graphics engines. For this to work with my example you'll need to have a version of the GLM library available, otherwise you can comment out all of the GLM related stuff to do simple basic conversion of single values. However, I'm showing it here as a demonstration of how to convert from a string to different numerical types including user defined types.
You can not construct an instance of this Utility class object as its constructor is deleted and it has no member variables. It is only a collection of similar or related functions, mostly string manipulation methods.
If you take the time to read through the class you will see that I am using static functions to convert from string to the wanted types.
The class does have 2 private function templates, string_to_value which is defined in the header outside of the class and get_value which is defined in the cpp file as there are 3 overloaded or template specialization functions based on the return types. They are int, unsigned and float, respectively. I have also included overloaded operator<<'s for all of the glm vector types for easy printing.
It is within the get_value functions that I use std::stof, std::stoi and std::stoul. If you want to add the ability to convert to double it shouldn't be that hard to add it to this class.
My class is much bigger than this, but to keep it short I've omitted at least half of it.

Now for the code...
Application and Output
main.cpp
#include <iostream>
#include "Utility.h"

int main() {
    using namespace util;

    try {
        std::string str1("3,4,5");
        std::string str2("-4,-2,7");
        std::string str3("2.4,7.8,9.2");

        glm::uvec3 uvec3 = Utility::convert_to_uvec3(str1);
        glm::ivec3 ivec3 = Utility::convert_to_ivec3(str2);
        glm::vec3   vec3 = Utility::convert_to_vec3(str3);

        std::cout << uvec3 << '\n';
        std::cout << ivec3 << '\n';
        std::cout <<  vec3 << '\n';

        // test an exception case:
        glm::vec4 v4 = Utility::convert_to_vec4(str2);

    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

Output
(3,4,5)
(-4,-2,7)
(2.4,7.8,9.2)
util::Utility::convert_to_vec4 Bad conversion of [-4,-2,7] to vec4

Utility Class
Utility.h
#ifndef UTILITY_H
#define UTILITY_H

#include <string>
#include <algorithm>
#include <glm/glm.hpp>

namespace util {

    class Utility {
    public:
        static std::string to_upper(const std::string& str);
        static std::string to_lower(const std::string& str);
        static std::string trim(const std::string& str, const std::string elements_to_trim = " \t\n\r");

        static unsigned     convert_to_unsigned(const std::string& str);
        static int          convert_to_int(const std::string& str);
        static float        convert_to_float(const std::string& str);

        static glm::vec2    convert_to_vec2(const std::string& str);
        static glm::vec3    convert_to_vec3(const std::string& str);
        static glm::vec4    convert_to_vec4(const std::string& str);

        static glm::ivec2   convert_to_ivec2(const std::string& str);
        static glm::ivec3   convert_to_ivec3(const std::string& str);
        static glm::ivec4   convert_to_ivec4(const std::string& str);

        static glm::uvec2   convert_to_uvec2(const std::string& str);
        static glm::uvec3   convert_to_uvec3(const std::string& str);
        static glm::uvec4   convert_to_uvec4(const std::string& str);

    private:
        Utility() = delete;
        Utility(const Utility& c) = delete;
        Utility& operator=(const Utility& c) = delete;

        template<typename T>
        static bool string_to_value(const std::string& str, T* value, unsigned num_values);

        template<typename T>
        static T get_value(const std::string& str, std::size_t& remainder);
    };

    template<typename T>
    static bool Utility::string_to_value(const std::string& str, T* value, unsigned num_values) {
        int num_commas = std::count(str.begin(), str.end(), ',');
        if (num_commas != num_values - 1) return false;

        std::size_t remainder;
        value[0] = get_value<T>(str, remainder);

        if (num_values == 1) {
            if (str.size() != remainder) {
                return false;
            }
        } else {
            std::size_t offset = remainder;
            if (str.at(offset) != ',') {
                return false;
            }

            unsigned last_indx = num_values - 1;
            for (unsigned u = 1; u < num_values; ++u) {
                value[u] = get_value<T>(str.substr(++offset), remainder);
                offset += remainder;
                if ((u < last_indx && str.at(offset) != ',') ||
                    (u == last_indx && offset != str.size())) {
                    return false;
                }
            }
        }
        return true;
    }

} // namespace util

std::ostream& operator<<(std::ostream& out, const glm::ivec2& v2Value);
std::ostream& operator<<(std::ostream& out, const glm::ivec3& v3Value);
std::ostream& operator<<(std::ostream& out, const glm::ivec4& v4Value);

std::ostream& operator<<(std::ostream& out, const glm::vec2& v2Value);
std::ostream& operator<<(std::ostream& out, const glm::vec3& v3Value);
std::ostream& operator<<(std::ostream& out, const glm::vec4& v4Value);

std::ostream& operator<<(std::ostream& out, const glm::uvec2& v2Value);
std::ostream& operator<<(std::ostream& out, const glm::uvec3& v3Value);
std::ostream& operator<<(std::ostream& out, const glm::uvec4& v4Value);

#endif // UTILITY_H

Utility.cpp
#include "Utility.h"

#include <exception>
#include <sstream>

namespace util {
    std::string Utility::to_upper(const std::string& str) {
        std::string result = str;
        std::transform(str.begin(), str.end(), result.begin(), ::toupper);
        return result;
    }

    std::string Utility::to_lower(const std::string& str) {
        std::string result = str;
        std::transform(str.begin(), str.end(), result.begin(), ::tolower);
        return result;
    }

    std::string Utility::trim(const std::string& str, const std::string elements_to_trim) {
        std::basic_string<char>::size_type first_index = str.find_first_not_of(elements_to_trim);
        if (first_index == std::string::npos) {
            return std::string(); // nothing left
        }

        std::basic_string<char>::size_type last_index = str.find_last_not_of(elements_to_trim);
        return str.substr(first_index, last_index - first_index + 1);
    }

    template<>
    float Utility::get_value(const std::string& str, std::size_t& remainder) {
        return std::stof(str, &remainder);
    } // getValue<float>

    template<>
    int Utility::get_value(const std::string& str, std::size_t& remainder) {
        return std::stoi(str, &remainder);
    } // getValue<int>

    template<>
    unsigned Utility::get_value(const std::string& str, std::size_t& remainder) {
        return std::stoul(str, &remainder);
    } // getValue<unsigned>

    unsigned Utility::convert_to_unsigned(const std::string& str) {
        unsigned u = 0;
        if (!string_to_value(str, &u, 1)) {
            std::ostringstream stream;
            // __FUNCTION__ works on windows otherwise user can exchange - modify to use __PRETTY_FUNCTION__
            stream << __FUNCTION__ << " Bad conversion of [" << str << "] to unsigned";
            throw std::exception(stream.str().c_str());
        }
        return u;
    }

    int Utility::convert_to_int(const std::string& str) {
        int i = 0;
        if (!string_to_value(str, &i, 1)) {
            std::ostringstream stream;
            // __FUNCTION__ works on windows otherwise user can exchange - modify to use __PRETTY_FUNCTION__
            stream << __FUNCTION__ << " Bad conversion of [" << str << "] to int";
            throw std::exception(stream.str().c_str());
        }
        return i;
    }

    float Utility::convert_to_float(const std::string& str) {
        float f = 0;
        if (!string_to_value(str, &f, 1)) {
            std::ostringstream stream;
            // __FUNCTION__ works on windows otherwise user can exchange - modify to use __PRETTY_FUNCTION__
            stream << __FUNCTION__ << " Bad conversion of [" << str << "] to float";
            throw std::exception(stream.str().c_str());
        }
        return f;
    }

    glm::vec2 Utility::convert_to_vec2(const std::string& str) {
        glm::vec2 v2;
        if (!string_to_value(str, &v2[0], 2)) {
            std::ostringstream stream;
            // __FUNCTION__ works on windows otherwise user can exchange - modify to use __PRETTY_FUNCTION__
            stream << __FUNCTION__ << " Bad conversion of [" << str << "] to vec2";
            throw std::exception(stream.str().c_str());
        }
        return v2;
    }

    glm::vec3 Utility::convert_to_vec3(const std::string& str) {
        glm::vec3 v3;
        if (!string_to_value(str, &v3[0], 3)) {
            std::ostringstream stream;
            // __FUNCTION__ works on windows otherwise user can exchange - modify to use __PRETTY_FUNCTION__
            stream << __FUNCTION__ << " Bad conversion of [" << str << "] to vec3";
            throw std::exception(stream.str().c_str());
        }
        return v3;
    }

    glm::vec4 Utility::convert_to_vec4(const std::string& str) {
        glm::vec4 v4;
        if (!string_to_value(str, &v4[0], 4)) {
            std::ostringstream stream;
            // __FUNCTION__ works on windows otherwise user can exchange - modify to use __PRETTY_FUNCTION__
            stream << __FUNCTION__ << " Bad conversion of [" << str << "] to vec4";
            throw std::exception(stream.str().c_str());
        }
        return v4;
    }

    glm::ivec2 Utility::convert_to_ivec2(const std::string& str) {
        glm::ivec2 v2;
        if (!string_to_value(str, &v2[0], 2)) {
            std::ostringstream stream;
            // __FUNCTION__ works on windows otherwise user can exchange - modify to use __PRETTY_FUNCTION__
            stream << __FUNCTION__ << " Bad conversion of [" << str << "] to ivec2";
            throw std::exception(stream.str().c_str());
        }
        return v2;
    }

    glm::ivec3 Utility::convert_to_ivec3(const std::string& str) {
        glm::ivec3 v3;
        if (!string_to_value(str, &v3[0], 3)) {
            std::ostringstream stream;
            // __FUNCTION__ works on windows otherwise user can exchange - modify to use __PRETTY_FUNCTION__
            stream << __FUNCTION__ << " Bad conversion of [" << str << "] to ivec3";
            throw std::exception(stream.str().c_str());
        }
        return v3;
    }

    glm::ivec4 Utility::convert_to_ivec4(const std::string& str) {
        glm::ivec4 v4;
        if (!string_to_value(str, &v4[0], 4)) {
            std::ostringstream stream;
            // __FUNCTION__ works on windows otherwise user can exchange - modify to use __PRETTY_FUNCTION__
            stream << __FUNCTION__ << " Bad conversion of [" << str << "] to ivec4";
            throw std::exception(stream.str().c_str());
        }
        return v4;
    }

    glm::uvec2 Utility::convert_to_uvec2(const std::string& str) {
        glm::uvec2 v2;
        if (!string_to_value(str, &v2[0], 2)) {
            std::ostringstream stream;
            // __FUNCTION__ works on windows otherwise user can exchange - modify to use __PRETTY_FUNCTION__
            stream << __FUNCTION__ << " Bad conversion of [" << str << "] to uvec2";
            throw std::exception(stream.str().c_str());
        }
        return v2;
    }

    glm::uvec3 Utility::convert_to_uvec3(const std::string& str) {
        glm::uvec3 v3;
        if (!string_to_value(str, &v3[0], 3)) {
            std::ostringstream stream;
            // __FUNCTION__ works on windows otherwise user can exchange - modify to use __PRETTY_FUNCTION__
            stream << __FUNCTION__ << " Bad conversion of [" << str << "] to uvec3";
            throw std::exception(stream.str().c_str());
        }
        return v3;
    }

    glm::uvec4 Utility::convert_to_uvec4(const std::string& str) {
        glm::uvec4 v4;
        if (!string_to_value(str, &v4[0], 4)) {
            std::ostringstream stream;
            // __FUNCTION__ works on windows otherwise user can exchange - modify to use __PRETTY_FUNCTION__
            stream << __FUNCTION__ << " Bad conversion of [" << str << "] to uvec4";
            throw std::exception(stream.str().c_str());
        }
        return v4;
    }

} // namespace util

std::ostream& operator<<(std::ostream& out, const glm::ivec2& v2Value) {
    out << "("
        << v2Value.x << ","
        << v2Value.y << ")";
    return out;
}

std::ostream& operator<<(std::ostream& out, const glm::ivec3& v3Value) {
    out << "("
        << v3Value.x << ","
        << v3Value.y << ","
        << v3Value.z << ")";
    return out;
}

std::ostream& operator<<(std::ostream& out, const glm::ivec4& v4Value) {
    out << "("
        << v4Value.x << ","
        << v4Value.y << ","
        << v4Value.z << ","
        << v4Value.w << ")";
    return out;
}

std::ostream& operator<<(std::ostream& out, const glm::vec2& v2Value) {
    out << "("
        << v2Value.x << ","
        << v2Value.y << ")";
    return out;
}

std::ostream& operator<<(std::ostream& out, const glm::vec3& v3Value) {
    out << "("
        << v3Value.x << ","
        << v3Value.y << ","
        << v3Value.z << ")";
    return out;
}

std::ostream& operator<<(std::ostream& out, const glm::vec4& v4Value) {
    out << "("
        << v4Value.x << ","
        << v4Value.y << ","
        << v4Value.z << ","
        << v4Value.w << ")";
    return out;
}

std::ostream& operator<<(std::ostream& out, const glm::uvec2& v2Value) {
    out << "("
        << v2Value.x << ","
        << v2Value.y << ")";
    return out;
}

std::ostream& operator<<(std::ostream& out, const glm::uvec3& v3Value) {
    out << "("
        << v3Value.x << ","
        << v3Value.y << ","
        << v3Value.z << ")";
    return out;
}

std::ostream& operator<<(std::ostream& out, const glm::uvec4& v4Value) {
    out << "("
        << v4Value.x << ","
        << v4Value.y << ","
        << v4Value.z << ","
        << v4Value.w << ")";
    return out;
}

Note:
In my string_to_value function I'm using a comma as a delimiter or string separator. You can easily change this to a space or some other character and it should give you the same functionality...


text:
Q: Creating scheduled tasks from command line (using parameters) I am trying to create a scheduled task from command line, although I can create in fine when defining the executable, I have problems when trying to add a parameter for that executable:
schtasks /Create /SC DAILY /TN TestRun /TR "C:\Program Files\Test\test.exe" C:\

I am effectively trying to launch "test.exe C:\"

A: schtasks /Create /SC DAILY /TN TestRun /TR "'C:\Program Files\Test\test.exe' 'C:\'"

You can read details in help:
schtasks /Create /?


text:
Q: 3 Gravity Forms on one page I'm currently displaying three gravity forms on a page, "display:none;", and setting them to "block" when one of the three corresponding buttons are clicked.
You can view the example on http://b2bsauce.com/
The problem is that on validation, the AJAX part reloads, with the error messages and again displays the form as hidden, which obviously, in this case, does not make sense.
Is there any way I can hook into the validation process and set the form to display or should I have gone about this in another way?
JS
var form = jQuery(this).attr('href');
jQuery('.gform_wrapper').not(form).css('display','none');
jQuery(form).slideDown();

HTML
Each form is contained in this wrapper, which is set to "display:none".

A: Submit buttons don't have the href attribute (assuming that's what is being clicked), are you trying to get the action of the form or just save the form instance itself to a variable?
I think you are trying to save the form element to a variable so I would change your code to:
var $form = jQuery(this).parents('form'); // use $ prefix to show it's a jQuery object
jQuery('.gform_wrapper').not($form).css('display','none');
jQuery($form).slideDown(); // not sure if you need this line if the form is already showing

but I'm not sure if that's all you need or not without some sort of self contained example that can be edited.

A: Gravity forms can be a bit tricky at time and I eventually found the error.
I used a "click" eventListener on the ".button" class to switch between hidden/block of the forms. However, the submit button in Gravity Forms also has a button class attached, hence it was hiding the form every time the submit button was clicked.
I thus made sure that the click listener is only attached to the three buttons at the top.


text:
Q: Find mean of Weibull 3 distribution in R Given alpha, lambda and phi (shape, scale and "guarantee"time (time before any failures), how do I find the mean of the distribution?
qweibull3 gives the median.
rweibull3 makes a nice random sample that approximates the mean, but is not the theoretical value.

A: Looking for definitions from wiki: https://en.wikipedia.org/wiki/Weibull_distribution
weibull3_mean <- function(gtime, shape, scale) {
    gtime + scale*gamma(1.0+1.0/shape)
}


text:
Q: Terminology: What's the difference between a class and a component? Within the OO paradigm, we choose to use classes because they help us to break the system down, and provide nice side benefits such as encapsulation, separation of responsibilities, inheritance, modularity, etc.
If we look at a software system at the component level, can we simply treat components in the same conceptual way, i.e. a component is simply a "Big Class"? Or is there more to it than that?
What extra considerations must be given when designing components?
EDIT:
I know that a class and a component are different things. I also understand that a component may contain many many classes, each of which have their own roles and responsibilities.
I'll see if I can explain myself better.

*

*Classes allow us to solve bigger problems because they allow us to think and design more abstractly.

*There are rules & techniques to determine how to break down and assign data and functionality to classes.

This seems like a very similar situation to that of component design, just at a higher level of abstraction. Do the techniques used to determine what classes are needed scale up to components, and/or are there other things that affect a high-level system design that don't apply at the class abstraction level?

A: I often think of Component in the UML sense (see Wikipedia description), whereby it represents a "modular part of a system".  In this sense it tends to represent a larger piece of functionality than a class and could in fact be composed from multiple classes.
Considerations I would give to designing components are:

*

*How it could be re-used.  In particular what are the use cases that warrant implementing something as a component rather than bespoke code (As a grad I used to make everything re-useable!)

*Providing sensible interface(s), and in some cases additional simplified interfaces, perhaps using the Facade pattern.

Hope that helps.

A: what about using the project phase or role to differentiate them?
For example a component is a design-time unit (system architects, designers) whereas a class is an implementation-time unit (programmers). So designers speak about components (or subsystems or modules, the hight-level boxes in your architecture drawing) whereas programmer speak about components and classes (that implements components).
Under this view a component is implemented by one or more classes.

A: In this (hypothethical) context a component can be thought of as a series of classes.
However depending on the technology you use, components can be more then a set of classes.
i.e. They may have additional properties and functionality which is not part of the classes which form them.
e.g. a COM+ component.
So it depends on a specific situation really.

A: According the UML v2 specification:

8.3.1 Component (from BasicComponents, PackagingComponents)
A component
represents a modular part of a system
that encapsulates its contents and
whose manifestation is replaceable
within its environment.
A component
defines its behavior in terms of
provided and required interfaces. As
such, a component serves as a type
whose conformance is defined by these
provided and required interfaces
(encompassing both their static as
well as dynamic semantics). One
component may therefore be substituted
by another only if the two are type
conformant. Larger pieces of a
system's functionality may be
assembled by reusing components as
parts in an encompassing component or
assembly of components, and wiring
together their required and provided
interfaces.

When you use this definition, components appear to be all about Inversion Of Control.
Looking at the .NET framework for an example, the IComponent interface indeed provides IComponent.Site.GetService to achieve inversion of control through the service provider pattern. A more light-weight alternative is dependency injection.

A: Eh?
The "File Uploading" component may consist of lots of classes: Page to receive the file, class to save it, etc.

A: components are subsystems of classes.Classes provide the basic low level blueprint of an object interface while components adds some functionality to it.


text:
Q: Add/subtract data frame row from another data frame r I'm sure this has been asked before, but I'm having a hard time finding it. I need to subset a data frame to a single row and subtract those values from the corresponding columns.
I actually did find Subtract values of a single row from all relevant columns in a data frame, which provided a solution (see below), but there has to be a simpler way, right? A tidyverse solution would be most appreciated.
Sample
Here is a sample data frame:
df <- as_tibble(matrix(1:9, 3, 3))
## A tibble: 3 x 3
#     V1    V2    V3
#  <int> <int> <int>
#1     1     4     7
#2     2     5     8
#3     3     6     9

Subtracting equal sized data frames is no problem.
df - df
#  V1 V2 V3
#1  0  0  0
#2  0  0  0
#3  0  0  0

Problem
But when I subset df to one row and try to subtract, it is unable to subtract uneven data frames. I subset df as
df[1, ]
## A tibble: 1 x 3
#     V1    V2    V3
#  <int> <int> <int>
#1     1     4     7

My desired solution will subtract 1 from each value in the first column, 4 from each value in the second and 7 from each in the third, such that this is the result:
## A tibble: 3 x 3
#     V1    V2    V3
#  <int> <int> <int>
#1     0     0     0
#2     1     1     1
#3     2     2     2

Trying this results in an error:
df - df[1, ]
#Error in Ops.data.frame(df, df[1, ]) :
#  '-' only defined for equally-sized data frames

In the link above, I found this solution, which works:
as_tibble(Map(`-`, df, df[1, ]))
## A tibble: 3 x 3
#     V1    V2    V3
#  <int> <int> <int>
#1     0     0     0
#2     1     1     1
#3     2     2     2

But this solution seems really complicated and isn't easily incorporated into a series of pipes.
Does anyone have any ideas?

A: We can replicate the row base don the col index of dataset.  This makes both the datasets to have same length/dimension
df - unlist(df[1,])[col(df)]
#   V1 V2 V3
#1  0  0  0
#2  1  1  1
#3  2  2  2

if we need a tidyverse option, map2 can be used
library(purrr)
library(dplyr)
map2_df(df, df[1, ], `-`)
# A tibble: 3 x 3
#     V1    V2    V3
#  <int> <int> <int>
#1     0     0     0
#2     1     1     1
#3     2     2     2

Or another option is uncount
df - uncount(df[1, ], nrow(df))

Or using pipe
df %>%
  slice(1) %>%
  uncount(nrow(df)) %>%
  {df - .}
#  V1 V2 V3
#1  0  0  0
#2  1  1  1
#3  2  2  2

Or with mutate_all
df %>%
    mutate_all(list(~ . - first(.)))
# A tibble: 3 x 3
#     V1    V2    V3
#  <int> <int> <int>
#1     0     0     0
#2     1     1     1
#3     2     2     2

A: If you are just trying to subtract the first row of a data.frame, then it's better to think about just subtracting the first value from each column. You can do that easily with dplyr
library(dplyr)
df %>% mutate_all(~.-first(.))


text:
Q: ASP.NET Web API - Return Object - Property Missing I'm using ASP.NET Web API to return a custom class object. The class has several properties, one of which takes an optional parameter. All the properties except the one with the optional parameter are available in the resulting JSON response. If I remove the optional parameter the other property is then available as well. Any way to return the other property with the optional parameter in place? Thanks!
Here is the specific property I'm having trouble with:
Public Class customer

...

Public ReadOnly Property photoSrc(Optional shape As String = Nothing) As String
        Get
            Dim srcString = "/Images/User.png"
                If shape = "square" Then
                    srcString = "/Images/UserSquare.png"
                End If
            Return srcString
        End Get
    End Property

...

End Class

And here is the api controller function I'm using to return json:
Public Function GetCustomer(id As Integer) As Object
    Dim customer As customer = New customer(id)
    Return customer
End Function

A: A property with a parameter is called an indexed property, or indexer.  By design, Json.Net (which is used by Web API for JSON serialization) does not serialize indexed properties, even if the index parameter is optional.  (You can see this for yourself in the source code for the GetSerializableMembers method of the DefaultContractResolver class.)
The simplest workaround is to add a separate non-indexed property to your class which calls the indexer with the parameter value you want it to have when serialized.  You can make the property private if you want; if you do, you just need to mark it with a <JsonProperty> attribute to allow the serializer to "see" it.  You can also use this attribute to give the alternate property the same name in the JSON as the indexed property it is replacing.
Public Class Customer

    ...

    <JsonProperty("photoSrc")>
    Private ReadOnly Property defaultPhotoSrc As String
        Get
            Return photoSrc()
        End Get
    End Property

    Public ReadOnly Property photoSrc(Optional shape As String = Nothing) As String
        Get
            Dim srcString = "/Images/User.png"
            If shape = "square" Then
                srcString = "/Images/UserSquare.png"
            End If
            Return srcString
        End Get
    End Property

    ...

End Class

Fiddle: https://dotnetfiddle.net/ffNs9D


text:
Q: loading data into session: will it be there I have a master page with the following code:
protected void Page_Init(object sender, EventArgs e)
{
  if (Session["SessionUserPreferences"] == null)
     {
        MyHelper.LoadInitialUserData(6);
     }
}

In my code behind, I use some of the data that's loaded in SessionUserPreferences to display the page in the Page_Load event. The Page_Init event of the master page comes before the Page_load event of the aspx page so in theory the data should be in the session when I reach the code behind. But is that always going to be the case? Can the time needed to load the data from the DB be greater than the time the Page_load event will trigger? I'm using InProc Session.
Thanks.

A: Page_Load wont execute until Page_Init finishes. You should still check if it is null in Page_Load though.

A: FYI, Order of events MSDNx
So to answer your question:
If the master page's init event is firing, then the rest of the master and children events will fire in sequential order as described in the article link above...


text:
Q: @attribute [AllowAnonymous] in Blazor server-side component has no effect I have created a fresh Blazor server-side project with .NET Core 3.0 and have closed down the application for non-authenticated users.
I am now trying to allow anonymous access to Index.razor component by placing [AllowAnonymous] at the top of the file. This however, does not seem to do anything.
Scenario
After using the default Blazor template "WeatherForecast" I added the following to Startup.cs
services.AddMvcCore(options =>
{
    var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
    options.Filters.Add(new AuthorizeFilter(policy));
});

This piece of code blocks all requests toward my application if the user is not authenticated.
After adding that piece of code I would like to open up the default Index.razor component for non-authenticated users. I do that by adding @attribute [AllowAnonymous] to Index.razor:
@page "/"
@attribute [AllowAnonymous]

Hello, world!

Welcome to your new app.

App.razor
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
    <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
    <CascadingAuthenticationState>
        <LayoutView Layout="@typeof(MainLayout)">

Sorry, there's nothing at this address.

        </LayoutView>
    </CascadingAuthenticationState>
</NotFound>
</Router>

Expected result
When running my application non-authenticated users would be allowed to visit the index page at https://localhost:XXXX
Actual result
My users are forwarded to my OpenIdConnect URI.


text:
Q: Is there bulletproof way to copy another workbook using vba? This is bothering me for a years now, I would like to open another workbook using VBA and copy worksheet to the current workbook and close it. Another workbook can be also macro enabled workbook. My method is following:
Application.DisplayAlerts = False
Dim workBookName1 As String
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Application.AutomationSecurity = msoAutomationSecurityLow
Workbooks.Open fileName:="C:\test.xlsm", ReadOnly:=True
workBookName1 = ActiveWorkbook.Name

'some work with copying, filtering, etc.

With Workbooks(workBookName1)
    .Close
End With

BUT the issue is that is not bulletproof -> sometimes this procedure closes all opened workbooks.
is there any other way to deal with this, maybe another method to try it?

A: If you declare and use objects properly, you will not face this problem as you will be working with only those objects. Here is an example
Option Explicit

Dim wbThis As Workbook, wbThat As Workbook

Set wbThis = ThisWorkbook
Set wbThat = Workbooks.Open(Filename:="C:\test.xlsm", ReadOnly:=True)

'
' Do some copying. For example see how I am using the objects below
' wbThat.Sheets("Sheet1").Copy After:=wbThis.Sheets(wbThis.Sheets.Count)
'

'~~> Close specific workbook when you are done
wbThat.Close (False)


text:
Q: Drupal - Grabbing and Looping NID of CCK Nodereference field cant seem to work out how i grab multiple nids of a node reference field.
$node->field_name[0]['nid'] picks up the node id of the cck node reference field.
however when that cck node reference field has more than one value i get stuck!
my php is abit sketchy atm so working with arrays and loops is being quite difficult!
here is my code:
<?php foreach ((array)$node->field_industry as $item) { ?>

<a href="../industry/company/<?php print --NODEID--?>"><?php print  $item['view'] ?>

<?php } ?>

A: unless I am missing something, the following should work
<?php foreach ($node->field_industry as $item) { ?>

<a href="../industry/company/<?php print $item['nid']?>"><?php print  $item['view'] ?>

<?php } ?>

A: as far as i know you can't add multiple references within one node reference field... however i would simply create my own textfield (field_multireferences) where i would type in my references: 12;43;65;21;...
now...
$myArray = explode(';', $node->field_multireferences[0]['view']);
foreach($myArray as....)
...
of course that wouldn't support auto completion etc.


text:
Q: Ununderstandable Pandas groupby results Coming from R and been working with the tidyverse mostly, I wonder how does pandas groupby and aggregations work. I have this code and the results are heartbreaking to me.
import pandas as pd
df = pd.read_csv('https://gist.githubusercontent.com/ZeccaLehn/4e06d2575eb9589dbe8c365d61cb056c/raw/64f1660f38ef523b2a1a13be77b002b98665cdfe/mtcars.csv')
df.rename(columns={'Unnamed: 0':'brand'}, inplace=True)

Now I would like to calculate the average displacement (disp) by cylinders, like that:
df['avg_disp'] = df.groupby('cyl').disp.mean()

Which results in something like:
    cyl disp    avg_disp
31  4   121.0   NaN
2   4   108.0   NaN
27  4   95.1    NaN
26  4   120.3   NaN
25  4   79.0    NaN
20  4   120.1   NaN
7   4   146.7   NaN
8   4   140.8   353.100000
19  4   71.1    NaN
18  4   75.7    NaN
17  4   78.7    NaN
29  6   145.0   NaN
0   6   160.0   NaN
1   6   160.0   NaN
3   6   258.0   NaN
10  6   167.6   NaN
9   6   167.6   NaN
5   6   225.0   NaN
13  8   275.8   NaN
28  8   351.0   NaN
4   8   360.0   105.136364
24  8   400.0   NaN
23  8   350.0   NaN
22  8   304.0   NaN
21  8   318.0   NaN
6   8   360.0   183.314286
11  8   275.8   NaN
16  8   440.0   NaN
30  8   301.0   NaN
14  8   472.0   NaN
12  8   275.8   NaN
15  8   460.0   NaN

After searching for a while, I discovered the transform function which leads to the correct value for avg_disp by assigning the mean value to each row according to the grouping cyl var.
My point is... why can't it be done easily with the mean function instead of using .transform('mean') on the grouped data frame?

A: If you want to add the results back to the ungrouped dataframe you could use .transform:

... and return a DataFrame having the same indexes as the original object filled with the transformed values.

df['avg_disp'] = df.groupby('cyl').disp.transform('mean')


text:
Q: How can I Mount Drive in Unsafe State? Operation not Permitted I have a drive that is starting to fail. I'm using Ubuntu to try and recover files.
Right now I am running into issues. I know the files are there as yesterday, on a boot usb, I managed to mount read only and see the files. Although I couldn't access the mount because of lacking permissions.
Today I have installed Ubuntu on a drive and am not lacking permission to mount as read only. Except now when I try to mount read only it says I need to specify the file type.
How can I the file type to check the files?
Ubuntu smart data and self tests says the disk is ok but that there is one bad sector.
I just want to mount the drive So that I can get the file off of it. It's a secondary drive, no windows installed.
Any suggestion? Thanks.
The exact commands I've used so far are as follows.
To mount readonly:
sudo mkdir /media/3TB
sudo mount -o ro /dev/sdb2 /media/3T

"Mount: you must specify file system type"
To try and mount/fix the drive:
Ntfsfix /dev/sdb2

"Mounting volume... Error opening '/dev/sdb2': Permission denied
Failed
Attempting to correct errors... Error opening '/dev/sdb2': Permission Denied
Failed
Failed to startup volume: Permission denied
Volume is corrupt. You should run chkdsk."

This is a command I found for check disk. Not sure it's right.
Fsck /dev/sdb2
"Fsck from util-Linux 2.20.1
Efsck 1.42.9 (4-few-2014)
Fsck.ext2: permission denied while trying to open /dev/sdb2

You must have r/w access to the filesystem or be root."

A: You got permission denied from ntfsfix because you didn't use sudo.  Mount is telling you that it can't figure out what kind of filesystem it is ( which does not bode well for being able to access your filesystem at all ) and so it wants to you tell it with -t ntfs, but since it couldn't figure this out on its own, this likely won't work either because your filesystem is so damaged.  In this case, you're going to have to restore from backup.


text:
Q: Does $\int _1 ^\infty\frac {f(x)} x\,dx$ converge or diverge? Let $f(x)$ be continuous in $[1, \infty)$ and $\int_{1}^{\infty} f(x)\,dx$ converge. I need to prove or disprove this: $\int_{1}^{\infty}\frac{f(x)}{x}\,dx$ converge.
I think this is true but I don't know how to prove this. Someone can give me a hint how to prove this.

A: Abel's theorem: let $g = fh$ be defined on $[a, b)$ with $b \in (a, \infty]$. If it holds that:

*

*$h$ is continuous, positive, decreasing and $\lim_{x \to b} h(x) = 0$

*$f$ is locally integrable on $[a, b)$ (i.e. integrable in the neighbourhood of any point) and $F$ is bounded on $[a, b)$, where $F: [a,b) \to \Bbb R$,
$$F(x) = \int_a^x f(t) dt$$
Then, $\int_a^b g(x)dx$ is convergent.
Use this with $a = 1$, $b = \infty$, $h(x) = 1/x$

A: Define $F(x):= \int_{1}^{x}f(t) \, dt$ and notice that $F$ is bounded and continuously differentiable on $[1,\infty)$.
Perform an integration by parts $$\int_{1}^{x}\frac{f(t)}{t} \, dt = \frac{F(x)}{x} + \int_{1}^{x}\frac{F(t)}{t^{2}} \, dt$$ What happens when you let $x\rightarrow \infty$?

A: Consider using the integral test. If you can prove that the series is always less than a convergent integral, then it must converge. You are given that $f(x)$ converges, and $\frac{f(x)}{x}$ will be less than $f(x)$ for all $x > 1$. Since the lower bound on your summation is $1$ ,$\frac{f(x)}{x} < f(x)$, and the series converges by the integral test.


text: Q: How to train LSTM model with multi-time series in timestamps I have a problem, I don't know how to perform LSTM training in my case. I have flight data in the form of a time series, I have the complete route of the flight and what I need is to use this data to predict the time of arrival. But I don't understand very well how to make the prediction since in the examples I see they always make predictions seen 1 month, 1 year. And what I need, given a route that is not complete, is to say what time I estimate the plane will arrive.


text:
Q: Redirecting with a different HTTP method I have an endpoint to update a given entity, and the response should be the updated entity.  I hterefore tried the following, however, the redirect is another PUT request.  How do I respond with a GET request?
$app->put('/foo/{id:[0-9]+}', function (Request $request, Response $response, $args) {
    $this->foo->update($args['id'], $request->getParsedBody());
    return $response->withRedirect("/foo/$args[id]");
});

A: You can use a 303 redirect:

The response to the request can be found under another URI using the GET method. When received in response to a POST (or PUT/DELETE), the client should presume that the server has received the data and should issue a new GET request to the given URI.

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#303
$app->put('/foo/{id:[0-9]+}', function (Request $request, Response $response, $args) {
    $this->foo->update($args['id'], $request->getParsedBody());
    return $response->withStatus(303)->withRedirect("/foo/$args[id]");
});


text:
Q: Desktop Launcher executing a sequence of commands after opening a terminal I've created a .desktop launcher as shown below which successfully opens terminal. What I want to do next is to run the following commands such as cd home/userA/scripts then PACKAGE_PATH=/home/userA/package1 then source setdefaults.sh through this .desktop launcher through the terminal after opening it.
My run.desktop:
#!/usr/bin/env xdg-open
[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
Icon[en_AU]=/usr/pics/pic1.png
Name[en_AU]=RUN
Exec=gksu -u userA /usr/bin/gnome-terminal
Comment[en_AU]=comment
Name=RUN
Comment=comment
Icon=/usr/pics/pic1.png

So what I want to do is to automatically run a sequence of commands and scripts (through  terminal) after executing the first command which opens the terminal. If anyone could please advise.

A: Try creating a .sh file with all your commands in it, and then use "x-terminal-emulator -e script.sh" to run it all in the terminal.

A: Another tip— running gnome-terminal.real in a script opens the GUI Terminal app.

A: If you would like to keep the terminal open from the Desktop Launcher so you can see the commands being executed or whatnot, first you need to create a script that has all of the commands you want the desktop launcher to perform, such as cd home/userA/scripts and so forth. Move the newly created script to /script/path/here and make sure it is executable. Now You need to tell the Desktop Launcher to open terminal and run that script. To do so is actually quite simple. Open up your .desktop file and replace
Exec=gksu -u userA /usr/bin/gnome-terminal

With:
Exec=gnome-terminal --execute bash -c "/script/path/here ; bash"

This should do open the terminal, keep it open, and run the script with all the commands you would like it to perform. Hope this helped!


text:
Q: How to deploy Meteor and Phusion Docker to Digital Ocean with Docker? What is a workflow for deploying to Digital Ocean with Phusion Docker and Node/Meteor support?
I tried :
FROM phusion/passenger-nodejs:0.9.10

# Set correct environment variables.
ENV HOME /root

# Use baseimage-docker's init process.
CMD ["/sbin/my_init"]

# ssh
ADD private/keys/akey.pub /tmp/your_key
RUN cat /tmp/your_key >> /root/.ssh/authorized_keys && rm -f /tmp/your_key

## Download shit
RUN apt-get update
RUN apt-get install -qq -y python-software-properties software-properties-common curl git build-essential
RUN npm install fibers@1.0.1
# install meteor
RUN curl https://install.meteor.com | /bin/sh

# Clean up APT when done.
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Enable nginx
# RUN rm -f /etc/service/nginx/down

#setup app
RUN mkdir /home/app/someapp
ADD . /home/app/someapp
WORKDIR /home/app/someapp
EXPOSE 4000
CMD passenger start -p 4000

But nothing is working and then I'm not sure how to really manage update/deploy/running?
E.g, how would you also handle updating the app without rebuilding the docker image?

A: Here is my suggested workflow:

*

*Create an account on Docker Hub, you can get 1 private repository for free. If you want a complete private repository hosted on your own server, you can run an entire docker registry and use it to host your images.

*Create your image on your development machine (locally or on a server), then push the image to the repository using docker push

*Update the image when needed and commit your changes with docker commit then push the updated image to your repository (you should properly version and tag all your images)

*You can start a digital ocean droplet with docker pre-installed (from applications tab) and simply pull your image and run your container. Whenever you update and push your image from your development machine, simple pull it again from the droplet.
For large and complex infrastructure, I would recommend looking into Ansible to configure your docker containers and manage digital ocean droplet as well.
Be aware that your data will be lost if you stop the container, so consider defining a volume in your container that is mapped to a shared folder on your host machine

A: I suggest you test your Dockerfile in a local VirtualBox VM. I wrote a tutorial about deploying node.js app with Docker. I build several images (layers) instead of just 1. When you update your app, you just need to rebuild the top layer. Hope it helps. http://vinceyuan.blogspot.com/2015/05/deploying-web-app-redis-postgres-and.html


text:
Q: How to add edition to ebook title when saving ebook to disk using Calibre? I want to include the edition, e.g., (4th ed), in the file names of my ebooks. How can I do this in Calibre?

A: This question was asked in 2014. Now, in 2019, there does exist a sophisticated feature to customize a book's saved file name and even directory path.
In your case, since edition may not be a default metadata field (it isn't in my version), this may be a two-step process.
First, look under preferences for add your own columns and create a new metadata element edition. Calibre may insist on re-loading in order to apply the changes.
Then, also under preferences, look for the section saving books to disk, and see that you are provided with the opportunity to create what they call a "template" to customize the file and directory name by any combination of metadata. In your case, you can insert your new custom metadata field using the format string {#edition}, so an example template might be {author}_-_{title}_{#edition}.


text:
Q: Postgres CAST macaddr Lets say I have two tables in Postgres:
Name: table_rad
Column    Type
id        integer
username  character varying(64)

Name: table_mac
Column    Type
id        integer
mac       macaddr

I want to do to a join:
SELECT * FROM table_rad WHERE username = mac;

Postgres will complain:
ERROR: operator does no exist: character varying = macaddr
LINE 1: ...ELECT * from table_rad WHERE username = mac;
                                                 ^
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.

Sofar I have googled for a solution and I know I have to CAST. But how can I cast type macaddr as varhcar?

A: Formal style: CAST(mac AS varchar)
PostgreSQL-style: mac::varchar
e.g.:
SELECT * FROM table_rad JOIN table_mac ON username = CAST(mac AS varchar)

A: You can do it by ::text like below:
SELECT * FROM table_rad WHERE username = mac::text;


text:
Q: Target lock/release on XBox 360 controller I just started playing Dark Souls 3 on PC. I get it's meant to be played on gamepad, so I grabbed my X360.
But I can't figure out which button is used for target lock/release. It says R, with an arrow above it pointing down. I tried RB and RT but obviously it's not it. So which button shouls I use?

A: It's the other R button: clicking the right control stick into the controller.


text:
Q: Inserir um ID no SQL+PHP Estou fazendo um formulário onde o usuário insere os dados e o mesmo recebe a confirmação junto com um registro ID no php com sql, só não estou conseguindo essa confirmação final junto com o id, alguém pode me ajudar?
sei que no mysql é assim.
$exec_sql = mysql_query($select);

if (!$exec_sql) {
    print mysql_error();
}
else {
    $id = mysql_insert_id();
    print '
Registro #'.$id.' inserido com sucesso
';

mas e no sql?

A: Um exemplo de código para está ação.
<?php
//Define as variáveis do banco
$servername = "localhost";
$username = "username";
$password = "password";

// Cria a conexão
$conn = new mysqli($servername, $username, $password);

//Verifica a conexão
if($conn->connect_error){
    die("Connection failed: " . $conn->connect_error);
}else{
echo "Conexão ok";
}
//Atribui a consulta a uma variável, você está usando select como nome de variável, mas é presumível um INSERT
$select = "INSERT INTO minhaTabela (colunaFoo, colunaBar)
VALUES ('dadoFoo', 'dadoBar')";

//Executa a consulta
$exec_sql = mysqli_query($conn, $select);

if(!$exec_sql){
print mysqli_error($conn);
}
else{
$id = mysqli_insert_id($conn);
print '
Registro #'.$id.' inserido com sucesso
';
}

//Fecha a conexão
mysqli_close($con);
?>

Espero que ajude.


text:
Q: Actualizar datos de un while Hola buen dia Mi problema es que tengo una tabla de tipo de vehiculos y placas y necesito que actualizen por medio de un boton  solo me funciona con el primer dato mostrado por el while, pero no lo cambia con los demás

MI JAVASCRIPT
function enviarplacas () {

         var tipo_vehiculo;
         var placa;
        datosactualizados2 = {

        tipo_vehiculo : $ ('.vehiculo').val(),
        placa : $ ('.placa').val(),

        idinsp

        };

    $.post('php/formularioactualiza/editar_placas.php', datosactualizados2, function(rtaactualiza2) {
        console.log(rtaactualiza2)
          if (rtaactualiza2 == 2){
          alert('se ha actualizado correctamente las placas');
          return;
        }

        if (rtaactualiza2 == 1){
          alert('No se pudo procesar las placas');
          return;
        }
    });

    console.log(datosactualizados2)
}

MI PHP
<?php

if (isset($_POST['inspeccionID'])    )  {

  $inspeccion_id = $_POST['inspeccionID'];

include("conexion.php");

   $result = mysqli_query($mysqli," SELECT * FROM vehiculo_inspeccion WHERE  id_inspeccion = '$inspeccion_id' ");

    if (!empty($result)) {

        if (mysqli_num_rows($result) > 0) {

        while ($fila = mysqli_fetch_array($result)){
               $fila_array['tipo_vehiculo']= $fila['tipo_vehiculo'];
               $fila_array['placa']= $fila['placa'];
               $fila_array['id_veh_ins']= $fila['id_veh_ins'];

echo "

         <input type='text' class='form-control vehiculo'  disabled='true' id='tipveh".$fila_array['id_veh_ins']."' value='".$fila_array['tipo_vehiculo']."'>
         <input type='text' class='form-control placa' disabled='true' id='plc".$fila_array['id_veh_ins']."' value='".$fila_array['placa']."'>
         <input type='button' class='btn btn-success' id='".$fila_array['id_veh_ins']."' onclick='activarplaca(this)' value='Editar'></button>

    ";

               }

        } else {

echo "

            No se encontraron placas en la inspeccion seleccionada.

     ";

        }

    } else {

echo "

           No se encontraron placas en la inspeccion seleccionada.

    ";

    }
  } else {
    echo "Error";
  }

?>

MI HTML

   Tipo vehiculo
    Placa
    EDITAR

  <button type="button" id="guardardatos" class="btn btn-info" onclick="enviarplacas()"> ACTUALIZAR PLACAS</button>

A: Hola compañero el problema en tu código es que al momento de recibir los datos en tu objeto "datosactualizados2" de la forma que lo estas haciendo solo vas a recibir el primer valor de cada de uno de los elementos que contengan esas clases (".vehiculo",".placa"). Lo mas sencillo que se me ocurrió de acuerdo a como generas cada linea es agrupar los datos por cada uno de los row generados (tr) es decir tr[0](input1,input2,button1),"tr[1](input2,input2,button2)" una vez que tengo esto lo recorres con un ".each", luego con el metodo Find.()
busco los elementos que necesito y cargo los valores al objeto correctamente. Perdón si soy malo explicando. Saludos

function enviarplacas(){
 var datosactualizados2 = [];
 $(".datosplaca tr").each(function() {
  var inputVeh = $(this).find(".vehiculo");
  var inputPla = $(this).find(".placa");
  var inputBtn = $(this).find(":button");
  datosactualizados2.push( {
    tipo_vehiculo: inputVeh.eq(0).val(),
    placa: inputPla.eq(0).val(),
    idinsp: inputBtn.eq(0).attr('id')
     });
 });
}
// el Resultado seria algo asi
0: {tipo_vehiculo: "tipo1", placa: "placa1", idinsp: "id1"}
1: {tipo_vehiculo: "tipo2", placa: "placa2", idinsp: "id2"}


text:
Q: not able to access access-token and uid from response headers I am trying to fetch access-token and uid from response headers of a post request, which looks like this

this is how i am trying to achieve it from service side
signup(postObj: any){
let url = environment.apiBaseUrl + "/v1/leads";
return this.http.post(url, postObj,{observe: 'response'});
}

Component side code
this.apartmentService.signup(obj).subscribe(data => {
console.log(data);
this.toastr.success('Registered successfully');
console.log(this.citydata,'this.citydata');

}

The method is not giving any response headers. Itried many solutions on internet but nothing works for me.
Any lead would be very helpful

A: Please try once with the below component side code and check whether required response headers are getting fetched or not -
this.apartmentService.signup(obj).subscribe((data: any) => {
console.log('access token: ', data.headers.get('access-token'));
console.log('uid: ', data.headers.get('uid'));
});

OR
this.apartmentService.signup(obj).subscribe((data: any) => {
console.log('access token: ', JSON.parse(data.headers.get('access-token')));
console.log('uid: ', JSON.parse(data.headers.get('uid')));
});


text:
Q: How to show catgories name on woocommerce order emails Table list I want to show custom value on woocommerce order email. See this screen shot https://s.nimbus.everhelper.me/share/1115381/uotnwxg567yh8pnt0e9o   if any one know solutions then please inform me. How can i show custom value woocommerce order email.
Thanks,
Ketan.


text:
Q: Architecture for scheduler jobs in AWS ECS I saw that coursers develop a scheduler for run job in the ECS AWS. As far as I know, it is not available for download. I know that AWS has a component called AWS Data Pipeline.
I search and not found another option to schedule jobs on ECS AWS.
Is there another third-part scheduler for ECS?
So my options until now are:

*

*AWS Data Pipeline

*Single machine with Cron installed (I didnt test this solution, and I dont know if it is viable)

A: I think the cleanest approach may be to use Scheduled AWS Lambda events to kickoff an ecs start-task
http://docs.aws.amazon.com/lambda/latest/dg/with-scheduled-events.html
AWS Lambda Scheduled Tasks

A: As per your requirement use custom scheduler like Mesos or Jenkins.


text:
Q: Java - If word ends with user-entered delimiters, then do x I am new to Java and am currently writing a program that takes use-entered arguments for delimiters of a text file containing sentences, and then determines the number of sentences within that text file based on the provided delimiters.
When running my Main.java I want the user to be able to do the following (where -d is the flag for delimiter and the characters following are the delimiters):
java Main -d !?. or java Main -d .?
Or any other combination. My questions are:

*

*Is the best way to store the delimiters as a string or array?

*How do I cleanly tell my program to use the delimiters being passed? Currently my program does the following:

Checks to see if a word ends with any of the delimiters specified. Like:
 if (word.endsWith(".")  || word.endsWith("!")  || word.endsWith("?")) {
           sentenceCount++
 }

But instead I would want it to be something like:
if (word.endsWith(delimitersStringorArray.contains())  {
           sentenceCount++
     }

I hope this makes sense and I can provide any further clarification if necessary. I tried searching but did not find my specific question.
Thanks!

A: Probably the best is to have as delimiter a String array.
That because the method endsWith use a String as a parameter.
The problem is that the actual version of endsWith in the class java.lang.String doesn't accept an array of possible delimiters, but it is possible to create a custom code to do the same like the following:
public class StringUtility {
    public static boolean endsWith(String str, String[] delimiters) {
        for (String delimiter : delimiters) {
            if (str.endsWith(delimiter)) {
                return true;
            }
        }
        return false;
    }
}

And to call it use a code like the following
String[] delimiters = { ".", "!", "?" };
if (StringUtility.endsWith("yourWord", delimiters)) {
    // Do something
}

Note that this is a more general code then what you requested because you can check if the passed string ends with delimiters of more than one characters.

A: If your delimiter is only one character long, you could store the delimiters in a List, then check if the last character of the String is in this list :
List<Character> delimiters = new ArrayList<Character>();
delimiters.add('.');
delimiters.add('!');
delimiters.add('?');

if(delimiters.contains(word.charAt(word.length() - 1))){

  sentenceCount++;
}


text:
Q: import .pde file (processing file) into blender I have a "Processing" file (written in "Processing" i.e. a pde file) which has a model and its transformations such as open, close, scale, rotate ..
How can I import this file into Blender 2.49?

A: I dont think so. You have to create your model in processing and then export it with a additional library in a format blender can import. There is a lib for exporting dxf files and i guess toxicLib has also the possibility to export 3d files as stl files.

A: Use the modelbuilder library and UGeometry.
You'll import modelbuilder e.g. :
import unlekker.util.*;
import unlekker.modelbuilder.*;
import unlekker.modelbuilder.filter.*;
import ec.util.*;

Load UGeometry:
UNav3D nav;
UGeometry model;

And write with the UGeometry.writeSTL method.


text:
Q: Change location Controllers\Auth I make project in Laravel 7.
I change location Http\Controllers\Auth to Http\Controllers**Admin**\Auth
In all files in Auth directory I change namespaces:
from:
namespace App\Http\Controllers\Auth;

to
namespace App\Http\Controllers\Admin\Auth;

Them I make composer dump-autoload.
Login work fine.
Now when I try logout with my code:
Wyloguj
                    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                        @csrf
                    </form>

I have error:

Illuminate\Contracts\Container\BindingResolutionException Target class
  [App\Http\Controllers\Front\Auth\LoginController] does not exist.

My RouteServiceProvider:
class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * The path to the "home" route for your application.
     *
     * @var string
     */
    public const HOME = '/';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //

        parent::boot();
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();

        if(config('app.admin_only'))
        {
            $this->mapAdminOnlyRoutes();
        }
        else
        {
            $this->mapWebRoutes();
            $this->mapAdminRoutes();
        }
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
            ->namespace($this->namespace. '\Front')
            ->group(base_path('routes/web.php'));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace)
            ->group(base_path('routes/api.php'));
    }

    protected function mapAdminRoutes()
    {
        Route::prefix(config('app.admin_prefix'))
            ->middleware('web')
            ->namespace($this->namespace.'\Admin')
            ->group(base_path('routes/admin.php'));
    }

    protected function mapAdminOnlyRoutes()
    {
        Route::middleware('web')
            ->namespace($this->namespace. '\Admin')
            ->group(base_path('routes/admin.php'));
    }
}

What is wrong? How can I repair it?

A: What you have changed is all from the front side of your application but when the vendor/directory is calling it's still trying to access the Auth related classes from the same namespace i.e
namespace App\Http\Controllers\Auth;

To successfully alter the namespace of your Auth file you need to tell Laravel where to access these files from the file AuthServiceProvider.php located in
app\Providers\AuthServiceProvider.php

Then there won't be that class not found issue


text:
Q: Why is this throwing an internal server error? I have a function that checks if a row exists in MySQL.
It's returning an Internal Server Error to AJAX.
I'm running a similar function in another script that works fine.
I've tested that $mysqli is opening fine, and that the query itself works. It seems to be the
if (mysqli_result($result, 0) !== '0') return true;

line throwing the error, but this line works fine on the other script.
Anything obvious I'm missing here?
function exists($mysqli,$id)
{
    $query="SELECT COUNT(*) FROM `table` WHERE `id`='". $id ."'";
    if (!$result=$mysqli->query($query)) send(3236,"e");
    if (mysqli_result($result, 0) !== '0') return true;
}

if(exists($mysqli,$id)) send("exists","e");

Here's another example where it's working fine:
$query="SELECT COUNT(`premium`) FROM `codes` WHERE `premium`='$code'";
if (!$result=$mysqli->query($query))
{
    $errMsg="There was a problem checking your code - please contact support";
}
else
{
    if (mysqli_result($result, 0) !== '0')
    {
        echo 'premium'
    }
    else
    {
        echo 'non-premium'
    }

}

Thanks for your time and help.


text:
Q: Gitlab with Azure AD auth So I'm trying to auth my GitLab with the Azure AD auth.
This is my /etc/gitlab/gitlab.rb
`gitlab_rails['omniauth_enabled'] = true
gitlab_rails['omniauth_allow_single_sign_on'] = ['azure_oauth2']
# gitlab_rails['omniauth_sync_email_from_provider'] = 'saml'
# gitlab_rails['omniauth_sync_profile_from_provider'] = ['saml']
# gitlab_rails['omniauth_sync_profile_attributes'] = ['email']
# gitlab_rails['omniauth_auto_sign_in_with_provider'] = 'saml'
# gitlab_rails['omniauth_block_auto_created_users'] = true
gitlab_rails['omniauth_auto_link_ldap_user'] = true
# gitlab_rails['omniauth_auto_link_saml_user'] = false
# gitlab_rails['omniauth_external_providers'] = ['twitter', 'google_oauth2']
gitlab_rails['sync_profile_from_provider'] = ['azure_oauth2']
gitlab_rails['sync_profile_attributes'] = ['name', 'email', 'location']
gitlab_rails['omniauth_providers'] = [
  {
    "name" => "azure_oauth2",
    "args" => {
      "client_id" => "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      "client_secret" => "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb=",
#    "args" => { "access_type" => "offline", "approval_prompt" => "" }
      "tenant_id" => "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
    },
#    "base_azure_url" => "https://login.microsoftonline.com"
  }
]

In my azure portal, I have this config:
Azure AD Free
One app in the Azure AD Free.
I have the reply URL to http://myaplicationdomain/auth/oauth2_generic and also http://myappauth.com/users/auth/azure_oauth2/callback
When i try to login with the azure auth I received the following error:

AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application:

So I just want to know if somebody else tried this and have some solution.
ruby -v
ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux]

There's no bundler because is an Azure installation.

A: You haven't included your app registration information, but from the error message you're sharing it looks like the Reply Url configured for the app registration doesn't match the reply Url you're passing with your request. A few ideas from someone who hasn't used Gitlab before.
Watch this video which specifically addresses reply url configuration in Azure: https://www.youtube.com/watch?v=A9U1VGyztEM&t=9s
Use fiddler or some other proxy to see what value you're sending to the Azure endpoint for the redirect_uri parameter. It'll need to match a configured reply url in the app.
Finally, refer to this article which suggests that you need to configure a well-known redirect url in the app registration following the format https://mygitlab.mycorp.org/users/auth/azure_oauth2/callback


text:
Q: Finding a recursion for a sum of Legendre polynomials The polynomial
$a_n(x):=P_n(x)-\frac{n-1}{n}P_{n-2}(x)$
where $P_n(x)$ is a Legendre polynomial came up while I was investigating methods for estimating the error in Gaussian quadrature.
I am wondering if a recursion relation (homogeneous/inhomogeneous, three terms or more) might be found for the $a_n(x)$. Of course I can obviously just generate them directly after performing the recursion for Legendre polynomials, but I'm wondering if there might be a way to generate this sequence of polynomials from the first few members, for instance $a_1(x)=x$ and $a_{2}(x)=\frac{3}{2}x^2-1$...
I have heard of Sister Celine's method; my understanding of it however is that one must first have a representation for your polynomials of interest in terms of a hypergeometric function. So an alternative question might be: can $a_n(x)$ be represented as a single hypergeometric function, most probably with one of the numerator parameters being -n?

A: (this is a variation on Darij's answer)
Note that "holonomic" generating functions $f(x)$, i.e. generating functions satisfying a linear differential equation with polynomial coefficients (in $x$) enjoy rich closure properties.
For a (very brief) summary, see Table 1 of a paper on guessing (sorry, I couldn't find a better reference, but there should be one...).  Moreover, all these closure properties can be made "effective": if we know the order and the degree of the coefficients of the diffential equation for $f(x)$ and for $g(x)$, we can (easily) compute bounds for order and coefficient degree of the differential equation for $f+g$, $f\cdot g$, etc.
Moreover, it turns out that the (Taylor) coefficient sequence of a holonomic generating function satisfies a linear recurrence with polynomial coefficients, i.e., is P-recursive, and the P-recursive sequences are precisely the coefficient sequences of holonomic generating functions.
Thus, to find such a recurrence (or differential equation), it is often easiest to use gfun for Maple by Bruno Salvy and Paul Zimmermann, or the Mathematica equivalent by Mallinger (I think).  Unfortunately, the FriCAS package described in 1 only does the guessing part, i.e., you would need to compute the bounds yourself and then check.  In the case at hand the results are below.
However, you also asked, whether the solution is hypergeometric.  To check this, you simply feed the recurrence you found below into Petkovsek's program Hyper, it will tell you whether there is a hypergeometric solution.  (most probably no, because if the degree of the coefficient polynomials of the hypergeometric solution are not huge, guessPRec and guessHolo would have found it.)
In case you are dealing with orthogonal polynomials, the Askey Wilson scheme by Koekoek and Swarttouw is a great reference to find the basic information.

(1) -> guessHolo(cons(x, [(legendreP(n, x)-(1-1/n)*legendreP(n-2, x)) for n in 2..30]), variableName==t)

   (1)
   [
     [
         n
       [t ]f(t):
                 4     2  2     5     3           4     2  ,,
           ((- 2t  - 2t )x  + (t  + 6t  + t)x - 2t  - 2t )f  (t)

         +
                 3       2      4      2           3       ,
           ((- 3t  - 7t)x  + (3t  + 15t  + 2)x - 8t  - 2t)f (t)

         +
              2      2     3            2
           ((t  - 3)x  + (t  + 3t)x - 4t  + 2)f(t)
           =
           0
       ,
                    2           2 3      2       3 4      3 2     3
                3t x  - 2t   15t x  - 13t x   35t x  - 39t x  + 6t       4
      f(t)= x + ---------- + -------------- + --------------------- + O(t )]
                     2              6                   8
     ]
                                              Type: List(Expression(Integer))
(2) -> guessPRec cons(x, [(legendreP(n, x)-(1-1/n)*legendreP(n-2, x)) for n in 2..30])

   (2)
   [
     [
       f(n):
                 4      3      2             2     4      3      2
             ((4n  + 28n  + 67n  + 63n + 18)x  - 4n  - 28n  - 68n  - 68n - 24)
          *
             f(n + 2)
         +
                    4      3       2              3
               (- 8n  - 52n  - 118n  - 107n - 30)x
             +
                  4      3       2
               (8n  + 52n  + 120n  + 114n + 36)x
          *
             f(n + 1)
         +
             4      3      2             2     4      3      2
         ((4n  + 24n  + 51n  + 46n + 15)x  - 4n  - 24n  - 52n  - 48n - 16)f(n)
           =
           0
       ,
                       2
                     3x  - 2
      f(0)= x, f(1)= -------]
                        2
     ]
                                              Type: List(Expression(Integer))

A: There is a general tactics for this. Recall that the three-term recurrence for the Legendre polynomials comes from a differential equation for their generating function.
The general background:
Generally, if a power series $f=\sum\limits_{i=0}^{\infty} p_it^i$ (where the coefficients $p_i$ belong to some field $K$ (for example, we can have $K=\mathbb Q$ or $K=\mathbb C\left(x\right)$ or whatever)) satisfies a differential equation $\sum\limits_{k=0}^n a_kf^{(k)}=0$ with coefficients $a_k\in K\left[t\right]$ (that's right, they can be polynomials in $t$), then we get a recurrence equation for the coefficients $p_i$ of $f$ in the following way:
Since $f=\sum\limits_{i=0}^{\infty} p_it^i$, we have $f^{(k)}=\sum\limits_{i=0}^{\infty} \left(i+k\right)\left(i+k-1\right)...\left(i+1\right)p_{i+k}t^i$. Hence, the equation $\sum\limits_{k=0}^n a_kf^{(k)}=0$ becomes $\sum\limits_{k=0}^n a_k\sum\limits_{i=0}^{\infty} \left(i+k\right)\left(i+k-1\right)...\left(i+1\right)p_{i+k}t^i=0$. Now write each $a_k$ as a polynomial in $t$, and expand the product on the left hand side. You get an equation of the form $\sum\limits_{u=0}^{\infty}\left(\text{some }K\text{-linear combination of }p_{u-m},p_{u-m+1},...,p_{u+n}\right)t^u=0$, where $m$ is $\max\left\lbrace\deg a_0,\deg a_1,...,\deg a_n\right\rbrace$. Now, equating coefficients, we get a recurrence equation for the $p_i$. Sometimes it may "degenerate", i. e. for some $i$ the coefficient before $p_i$ may be zero, but this shouldn't happen too often.
[Note that this recurrence equation has finitely many terms, since $a_k$ are polynomials in $t$. Had we allowed $a_k$ to be arbitrary power series in $t$, we would have obtained an infinite recurrence.]
Applications to the question:
The generating function for the Legendre polynomials is $\dfrac{1}{\sqrt{1-2xt+t^2}}$; this means that $\dfrac{1}{\sqrt{1-2xt+t^2}}=\sum\limits_{n=0}^{\infty}P_nt^n$ as a power series in the indeterminate $t$ over $K=\mathbb Q\left[x\right]$, where I write $P_n$ for $P_n\left(x\right)$.
Now you are interested in finding a recurrence relation for the $na_n=nP_n-\left(n-1\right)P_{n-2}$ (here I have multiplied by $n$ to get rid of the ugly fraction). So you are looking for a differential equation - with coefficients that are polynomial in $t$ and rational in $x$ - that the power series $\sum\limits_{n=0}^{\infty}na_nt^n$ satisfies.
Note that
$\sum\limits_{n=0}^{\infty}na_nt^n=\sum\limits_{n=0}^{\infty}\left(nP_n-\left(n-1\right)P_{n-2}\right)t^n=\sum\limits_{n=0}^{\infty}nP_nt^n-\sum\limits_{n=0}^{\infty}\left(n-2\right)P_{n-2}t^n-\sum\limits_{n=0}^{\infty}P_{n-2}t^n$
$=tU^{\prime}-t^3U^{\prime}-t^2U$,
where $U$ denotes the power series $\dfrac{1}{\sqrt{1-2xt+t^2}}=\sum\limits_{n=0}^{\infty}P_nt^n$.
Computations best left to a CAS now yield $\sum\limits_{n=0}^{\infty}na_nt^n=\dfrac{t\left(xt^2+x-2t\right)}{\sqrt{t^2-2tx+1}^3}$. This is the function we wish to find a differential equation for. Now there is a general way for it: If $P$ and $Q$ are two polynomials in $x$ and $t$, then the function $V:=\frac{P}{\sqrt Q}$ satisfies the differential equation $PQ\dfrac{d}{dt}V=\left(P^{\prime}Q - \dfrac{PQ^{\prime}}2\right)V$. This hopefully makes a "nice" recurrence. (In your case $P=t\left(xt^2+x-2t\right)$ and $Q=\left(t^2-2tx+1\right)^3$.)

A: Here's a negative result: I think I can show that there isn't a relation of the form:

$$a_n(x) =x C_n a_{n-1}+D_n a_{n-2}.$$

Through the properties of the Legendre polynomials, we find $D_n$ by proposing that the relation is true for $x=0$.  Then we find $C_n$ by proposing that the relation is true in an integral.  Then we show that the result isn't correct.

All the $a_i(x)$ are odd functions of $x$ for odd $i$, so $a_i(0)=0$, and for even $n$:

$$a_n(0)=P_n(0)-\frac{n-1}{n} P_{n-2}(0) =2(-1)^{n/2} \frac{(n-1)!!}{n!!}$$

using $P_n(0)=(-1)^{n/2} {(n-1)!!}/{n!!}$

So, if the relation is true for $x=0$, we know $D_n = -(n-1)/n$ for even $n$.

We know that

$$\int_{-1}^{1} \frac{P_n(x)}{\sqrt{1-x^2}} dx=\pi \left[ {\frac{(n-1)!!}{n!!}}\right] ^2$$

so after a bit of work I make it that
$$\int_{-1}^{1} \frac{a_n(x)}{\sqrt{1-x^2}} dx= \frac{-\pi}{n-1} \left[ {\frac{(n-1)!!}{n!!}}\right] ^2$$
$$\int_{-1}^{1} \frac{x \ a_{n-1}(x)}{\sqrt{1-x^2}} dx= \frac{-\pi (n^2-3n+3)}{n(n-1)(n-3)} \left[ {\frac{(n-3)!!}{(n-2)!!}}\right] ^2$$
$$C_n=\frac{(n-1)^2(2n-3)}{(n^2-3n+3)n}$$

(after applying the integral to the relation).  As far as I can tell, this does what it should -- I checked a specific example by typing into WolframAlpha: http://tinyurl.com/64pevxp , http://tinyurl.com/637ncou.  However, it doesn't generate the correct $a_n$ (for example, http://tinyurl.com/6gthkyg is not http://tinyurl.com/6afuttz).

You could check my working (I've been working on paper with the odd bit of WolframAlpha, because that's all I've got), but then perhaps you never expected the recurrence relation to be that simple.


text:
Q: Fb SDK Sample HelloFacebookSampleActivity is not working? I am working on Fb Sdk in android. I am doing import fb sdk and sample following here and i also get keyhash like this
 C:\Program Files (x86)\Java\jre7\bin> keytool -exportcert -alias androiddebugkey
 -keystore C:\Users\Duygu\.android\debug.keystore |C:\Users\Duygu\openssl-0.9.8k
_X64\bin\openssl.exe sha1 -binary | C:\Users\Duygu\openssl-0.9.8k_X64\bin\openss
l.exe base64

this is my app register

When i run HelloFacebookSampleActivity i am getting this error  and changed with my  app id from default id after error  i am getting same error.
I have some question:
1) When i try HelloFacebookSampleActivity i must change default app id from my id or not?
2)I am using my key hash but i also see reliase key. I must use reliase key now or my keyhash.I am doing just sample now.
3)I dont understand RELEASE_KEY_ALIAS and path.Where is there in my computer?
keytool -exportcert -alias **<RELEASE_KEY_ALIAS>** -keystore **<RELEASE_KEY_PATH**> | openssl sha1 -binary | openssl base64

Can anybody help me? I see all post but i couldnt.

A: There is some problem in the way you obtain your hash, I get it like this, and it never fails:
try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.josh.myapp",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("joshtag", "KeyHash:"+Base64.encodeToString(md.digest(), Base64.DEFAULT));
                }
            }
        catch (NameNotFoundException e) { }
        catch (NoSuchAlgorithmException e) { }

A: In order to run the sample apps that ship with the SDK, you need to add your key hash(es) to your developer settings:
https://developers.facebook.com/settings/developer/sample-app/