text:
Q: How to draw random sample from an empirical joint distribution? I want to draw a random sample from a known joint distribution. what I have now is the number of people in each age and income bracket (as shown in the example below):0.12 0.42 0.06
16 0.08 0.28 0.04
                   income $1-10,000    income $10,001-20,000
15-20 years old      0.12                      0.08
21-25 years old      0.42                      0.28
26-30 years old      0.06                      0.04

Using this I will get the joint distribution of income and age. But I am not sure where to go from here in terms of drawing samples.
Any thoughts are appreciated. My knowledge in statistics is quite limited...

A: If you want to sample (Age,Income) pairs, use any old sampling method directly on your joint distribution. Using numpy:
dist = [(("15-20 yr", "$1-10000"), 0.12), (("15-20 yr", "$10000-20000"), 0.08), ...]
num_of_samples = 10 # choose any size you want here
samples_i = numpy.random.choice(len(dist), size=num_of_samples, p=[x[1] for x in dist])
samples = [dist[x][0] for x in samples_i]


text:
Q: How to return a generic Collection in java I would like to do something like this, but it doesn't work clearly, any suggestions?
public HashSet<?> insert(String word, int val, HashSet<?> set) {

    if (val > 30) set.add(word);
    else set.add(val);

    return set;
}

A: The only thing you can do, since you're adding values to the Set, and you have both Integer and String as possible types (which have only Object as a common super class), is:
public HashSet<Object> insert(String word, int val, HashSet<Object> set) {
    if (val > 30) {
        set.add(word);
    } else {
        set.add(val);
    }
    return set;
}

The problem here is that when you return the Set you will be forced to cast its element to some specific type (Integer or String). Possibly you'd need to investigate some time in re-designing your model and then try to work efficiently with the Generic types.

A: Try this (but it won't work):
public <T> Set<T> insert(String word, int val, Set<T> set)
{
    if(val > 30)
    {
        set.add(word);
    }
    else
    {
        set.add(val);
    }

    return set;
}

By the way, this code here that is inside the method only works with Set<Object> which kinda ruins the point of generics.
EDIT: Indeed, it didn't work because T would need to be bound to extend both String and Integer, which is not possible.
The way generic is meant to be used is the following:
public <T> Set<T> insert(T t, Set<T> set)
{
    set.add(t);
    return set;
}

This way, you can only put a particular type of elements into the Set, so that you don't need to cast when you retrieve them. For example,
public static void main(String[] args)
{
    Set<String> set = new HashSet<String>();
    insert("Hello", set);
    insert("World!", set);
    for(String string : set)
    {
        System.out.println(string);
    }
    insert(562, set); //won't compile because it allows only strings
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to parse an xml to java class with recycler view or in adapter of recyclerview I have an xml file which name it is Bookmark and it is into the xml folder.
I want to parse xml to recycler view which I can show the list of the Bookmark in recycler view.
The bookmark xml it is not in assets it is in res then xml folder.
This is my code.
Bookmark.xml in the xml folder
<Bookmarks>
    <Bookmark id="1" icon="google.png" name="Google" searchUrl="https://www.google.com" hidden="true" />
    <Bookmark id="2" icon="youtube_new.png" name="Youtube" searchUrl="http://m.youtube.com" />
    <Bookmark id="3" icon="facebook.png" name="Facebook" nativeUrl="facebook://" searchUrl="https://m.facebook.com" />
    <Bookmark id="4" icon="twitter.png" name="Twitter" searchUrl="https://mobile.twitte.com" />
    <Bookmark id="5" icon="instagram.png" name="Instagram" nativeUrl="instagram://" searchUrl="https:instagram.com" />
    <Bookmark id="6" icon="gmail.png" name="Gmail" nativeUrl="googlemail://" searchUrl="https://gmail.com" />
    <Bookmark id="7" icon="google_translate.png" name="Translate" searchUrl="https://" />

</Bookmarks>

This is the java class for recycler view
 public class FragmentBookmark extends Fragment {
    ArrayList<Bookmark> arrayList = new ArrayList<>();
    XmlPullParserFactory pullParserFactory;
    RecyclerView myRecyclerView;
    MyAdapter myAdapter;

    public void onCreateView(@Nullable Bundle savedInstanceState) {
        myRecyclerView = getActivity().findViewById(R.id.myRecyclerView);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 1);
        myRecyclerView.setHasFixedSize(true);
        try {
            pullParserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = pullParserFactory.newPullParser();

            InputStream in_s = getActivity().getApplicationContext().getAssets().open("bookmarks.xml");
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(in_s, null);

            parseXML(parser);

        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < arrayList.size(); i++) {
            Log.e("OUTPUT", arrayList.get(i).toString());
        }

        myAdapter = new MyAdapter(getActivity(), arrayList);
        myRecyclerView.setAdapter(myAdapter);
    }

    private void parseXML(XmlPullParser parser) throws XmlPullParserException, IOException {
        ArrayList<Bookmark> countries = null;
        int eventType = parser.getEventType();
        Bookmark country = null;

        while (eventType != XmlPullParser.END_DOCUMENT) {
            String name;
            name = parser.getName();
            switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    countries = new ArrayList();
                    break;
                case XmlPullParser.START_TAG:
                    break;

                case XmlPullParser.END_TAG:
                    if (name.equals("Bookmark")) {

                        Bookmark bookmark = new Bookmark();
                        bookmark.setName(parser.getAttributeValue(null, "name"));
                        bookmark.setIcon(parser.getAttributeValue(null, "icon"));
                        bookmark.setId(parser.getAttributeValue(null, "id"));
                        bookmark.setSearchUrl(parser.getAttributeValue(null, "searchUrl"));
                        bookmark.setNativeUrl(parser.getAttributeValue(null, "nativeUrl"));
                        arrayList.add(bookmark);
                    }
                    break;
            }
            eventType = parser.next();
        }

    }

    private void processParsing(XmlPullParser parser) throws IOException, XmlPullParserException {
        int eventType = parser.getEventType();
        Bookmark bookmark = null;

    }
    }

This is the recycler view xml
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/listRecyclerView"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    android:fillViewport="false">

    </android.support.v7.widget.RecyclerView>

This is the adapter for recyclerview
public class MyAdapter extends RecyclerView.Adapter {
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.grid_item, viewGroup, false);
        return new ListViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
        ((ListViewHolder) viewHolder).bindView(i);
    }

    @Override
    public int getItemCount() {
        return OurData.title.length;
    }

    private class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView mItemText;
        private ImageView mItemImage;

        public ListViewHolder(View itemView) {
            super(itemView);
            mItemText = itemView.findViewById(R.id.textView);
            mItemImage =  itemView.findViewById(R.id.image_view);
            itemView.setOnClickListener(this);
        }

        public void bindView(int position) {
            mItemText.setText(OurData.title[position]);
            mItemImage.setImageResource(OurData.picture[position]);

        }

        @Override
        public void onClick(View v) {

        }
    }
}

This is a java class which I have added manually and works in the recycler view but I need the Bookmark xml to show in recycler view
public class OurData {
    public static String[] title = new String[] {
            "Bing",
            "Facebook",
            "Gmail",
            "Translate",
            "Bing",
            "Facebook",
            "Gmail",
            "Translate"
    };

    public static int[] picture = new int[] {
            R.drawable.instagram,
            R.drawable.instagram,
            R.drawable.instagram,
            R.drawable.instagram,
            R.drawable.instagram,
            R.drawable.instagram,
            R.drawable.instagram,
            R.drawable.instagram

    };
}

This is the xml to show an Image and a TextView for recycler view
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:id="@+id/recyclerView">

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="28dp"
        android:layout_height="27dp"
        android:layout_alignParentTop="true"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.129"
        app:layout_constraintStart_toStartOf="parent"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteY="16dp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="80dp"
        android:layout_height="23dp"
        android:layout_below="@+id/image_view"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintHorizontal_bias="0.069"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/image_view" />

</android.support.constraint.ConstraintLayout>

A: UPDATE 2

FragmentBookmark

public class FragmentBookmark extends Fragment {

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

    private Context mContext;
    ArrayList<Bookmark> arrayList = new ArrayList<>();
    XmlPullParserFactory pullParserFactory;

    RecyclerView myRecyclerView;
    DataAdapter dataAdapter;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_bookmark, container, false);

        myRecyclerView = rootView.findViewById(R.id.myRecyclerView);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        myRecyclerView.setHasFixedSize(true);

        dataAdapter = new DataAdapter(mContext, arrayList);
        myRecyclerView.setAdapter(dataAdapter);

        try {

            XmlPullParser xpp = getResources().getXml(R.xml.bookmarks);

            while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
                if (xpp.getEventType() == XmlPullParser.START_TAG) {
                    if (xpp.getName().equals("Bookmark")) {

                        Log.e("MY_VALUE", " * " + xpp.getAttributeValue(0) + " * ");
                        Log.e("MY_VALUE", " * " + xpp.getAttributeValue(1) + " * ");
                        Log.e("MY_VALUE", " * " + xpp.getAttributeValue(5) + " * ");
                        Log.e("MY_VALUE", " * " + xpp.getAttributeValue(2) + " * ");
                        Log.e("MY_VALUE", " * " + xpp.getAttributeValue(3) + " * ");
                        Log.e("MY_VALUE", " * " + xpp.getAttributeValue(4) + " * ");

                        Bookmark bookmark = new Bookmark();
                        bookmark.setName(xpp.getAttributeValue(0));

                        int drawableResourceId = this.getResources().getIdentifier(xpp.getAttributeValue(1), "drawable", mContext.getPackageName());
                        bookmark.setIcon(drawableResourceId);

                        bookmark.setId(xpp.getAttributeValue(2));

                        bookmark.setSearchUrl(xpp.getAttributeValue(3));
                        bookmark.setNativeUrl(xpp.getAttributeValue(4));
                        arrayList.add(bookmark);

                    }
                }

                xpp.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        dataAdapter.notifyDataSetChanged();
        return rootView;
    }

}

layout.fragment_bookmark

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/myRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

DataAdapter

public class DataAdapter  extends RecyclerView.Adapter<DataAdapter.ViewHolder> {

    private Context context;
    ArrayList<Bookmark> arrayList = new ArrayList<>();

    public DataAdapter(Context context, ArrayList<Bookmark> arrayList) {
        this.context = context;
        this.arrayList = arrayList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {

        View view=LayoutInflater.from(context).inflate(R.layout.custom_layout,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        holder.tvName.setText(arrayList.get(position).getName());

        holder.tvIcon.setImageResource(arrayList.get(position).getIcon());

        holder.tvId.setText(arrayList.get(position).getId());
        holder.tvSearchUrl.setText(arrayList.get(position).getSearchUrl());
        holder.tvNativeUrl.setText(arrayList.get(position).getNativeUrl());
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvName,tvId,tvSearchUrl,tvNativeUrl;

        ImageView tvIcon;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            tvName=itemView.findViewById(R.id.tvName);
            tvIcon=itemView.findViewById(R.id.tvIcon);
            tvId=itemView.findViewById(R.id.tvId);
            tvSearchUrl=itemView.findViewById(R.id.tvSearchUrl);
            tvNativeUrl=itemView.findViewById(R.id.tvNativeUrl);
        }
    }
}

layout.custom_layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:cardCornerRadius="15dp"
    app:cardElevation="5dp"
    app:cardUseCompatPadding="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="Name  : " />

            <TextView
                android:id="@+id/tvName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="Icon  : " />

            <ImageView
                android:id="@+id/tvIcon"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:padding="10dp"
                android:text="" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="Id  : " />

            <TextView
                android:id="@+id/tvId"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="SearchUrl  : " />

            <TextView
                android:id="@+id/tvSearchUrl"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="NativeUrl  : " />

            <TextView
                android:id="@+id/tvNativeUrl"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="" />

        </LinearLayout>

    </LinearLayout>

</android.support.v7.widget.CardView>

Bookmark model class

public class Bookmark
{
    String name,id,nativeUrl,searchUrl;
    int icon;

    public String getName() {
        return name;
    }

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

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getIcon() {
        return icon;
    }

    public void setIcon(int icon) {
        this.icon = icon;
    }

    public String getNativeUrl() {
        return nativeUrl;
    }

    public void setNativeUrl(String nativeUrl) {
        this.nativeUrl = nativeUrl;
    }

    public String getSearchUrl() {
        return searchUrl;
    }

    public void setSearchUrl(String searchUrl) {
        this.searchUrl = searchUrl;
    }

    @Override
    public String toString() {
        return "Bookmark{" +
                "name='" + name + '\'' +
                ", icon='" + icon + '\'' +
                ", id='" + id + '\'' +
                ", nativeUrl='" + nativeUrl + '\'' +
                ", searchUrl='" + searchUrl + '\'' +
                '}';
    }
}

UPDATE
XML FILE
<Bookmarks>
    <Bookmark
        name="Google"
        hidden="true"
        icon="google.png"
        id="1"
        nativeUrl=""
        searchUrl="https://www.google.com" />
    <Bookmark
        name="Youtube"
        hidden=""
        icon="youtube_new.png"
        id="2"
        nativeUrl=""
        searchUrl="http://m.youtube.com" />
    <Bookmark
        name="Facebook"
        hidden=""
        icon="facebook.png"
        id="3"
        nativeUrl="facebook://"
        searchUrl="https://m.facebook.com" />
    <Bookmark
        name="Twitter"
        hidden=""
        icon="twitter.png"
        id="4"
        nativeUrl=""
        searchUrl="https://mobile.twitte.com" />
    <Bookmark
        name="Instagram"
        hidden=""
        icon="instagram.png"
        id="5"
        nativeUrl="instagram://"
        searchUrl="https:instagram.com" />
    <Bookmark
        name="Gmail"
        hidden=""
        icon="gmail.png"
        id="6"
        nativeUrl="googlemail://"
        searchUrl="https://gmail.com" />
    <Bookmark
        name="Translate"
        hidden=""
        icon="google_translate.png"
        id="7"
        nativeUrl=""
        searchUrl="https://" />

</Bookmarks>

Here is the code to parse XML from res/XML folder
    try {

        XmlPullParser xpp = getResources().getXml(R.xml.bookmarks);

        while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
            if (xpp.getEventType() == XmlPullParser.START_TAG) {
                if (xpp.getName().equals("Bookmark")) {

                    Log.e("MY_VALUE", " * " + xpp.getAttributeValue(0) + " * ");
                    Log.e("MY_VALUE", " * " + xpp.getAttributeValue(1) + " * ");
                    Log.e("MY_VALUE", " * " + xpp.getAttributeValue(5) + " * ");
                    Log.e("MY_VALUE", " * " + xpp.getAttributeValue(2) + " * ");
                    Log.e("MY_VALUE", " * " + xpp.getAttributeValue(3) + " * ");
                    Log.e("MY_VALUE", " * " + xpp.getAttributeValue(4) + " * ");

                    Bookmark bookmark = new Bookmark();
                    bookmark.setName(xpp.getAttributeValue(0));
                    bookmark.setIcon(xpp.getAttributeValue(1));
                    bookmark.setId(xpp.getAttributeValue(2));
                    bookmark.setSearchUrl(xpp.getAttributeValue(3));
                    bookmark.setNativeUrl(xpp.getAttributeValue(4));
                    arrayList.add(bookmark);

                }
            }

            xpp.next();
        }
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

There are three types of android XML parser that we can use.

*

*SAX Parsers

*DOM Parsers

*XMLPullParser
You can use XmlPullParserFactory to parse your xml
Try this here is the working code

MainActivity

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<Bookmark> arrayList = new ArrayList<>();
    XmlPullParserFactory pullParserFactory;

    RecyclerView myRecyclerView;
    DataAdapter dataAdapter;

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

        myRecyclerView = findViewById(R.id.myRecyclerView);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        myRecyclerView.setHasFixedSize(true);
        try {
            pullParserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = pullParserFactory.newPullParser();

            InputStream in_s = getApplicationContext().getAssets().open("bookmark.xml");
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(in_s, null);

            parseXML(parser);

        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < arrayList.size(); i++) {
            Log.e("OUTPUT", arrayList.get(i).toString());
        }

        dataAdapter = new DataAdapter(this, arrayList);
        myRecyclerView.setAdapter(dataAdapter);
    }

    private void parseXML(XmlPullParser parser) throws XmlPullParserException, IOException {
        ArrayList<Bookmark> countries = null;
        int eventType = parser.getEventType();
        Bookmark country = null;

        while (eventType != XmlPullParser.END_DOCUMENT) {
            String name;
            name = parser.getName();
            switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    countries = new ArrayList();
                    break;
                case XmlPullParser.START_TAG:
                    break;

                case XmlPullParser.END_TAG:
                    if (name.equals("Bookmark")) {
                        Log.e("VALUE", parser.getAttributeValue(null, "name") + "");
                        Log.e("VALUE", parser.getAttributeValue(null, "icon") + "");
                        Log.e("VALUE", parser.getAttributeValue(null, "id") + "");
                        Log.e("VALUE", parser.getAttributeValue(null, "searchUrl") + "");
                        Log.e("VALUE", parser.getAttributeValue(null, "nativeUrl") + "");

                        Bookmark bookmark = new Bookmark();
                        bookmark.setName(parser.getAttributeValue(null, "name"));
                        bookmark.setIcon(parser.getAttributeValue(null, "icon"));
                        bookmark.setId(parser.getAttributeValue(null, "id"));
                        bookmark.setSearchUrl(parser.getAttributeValue(null, "searchUrl"));
                        bookmark.setNativeUrl(parser.getAttributeValue(null, "nativeUrl"));
                        arrayList.add(bookmark);
                    }
                    break;
            }
            eventType = parser.next();
        }

    }

    private void processParsing(XmlPullParser parser) throws IOException, XmlPullParserException {
        int eventType = parser.getEventType();
        Bookmark bookmark = null;

    }
}

layout.activity_main

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/myRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

DataAdapter

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

public class DataAdapter  extends RecyclerView.Adapter<DataAdapter.ViewHolder> {

    private Context context;
    ArrayList<Bookmark> arrayList = new ArrayList<>();

    public DataAdapter(Context context, ArrayList<Bookmark> arrayList) {
        this.context = context;
        this.arrayList = arrayList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {

        View view=LayoutInflater.from(context).inflate(R.layout.custom_layout,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        holder.tvName.setText(arrayList.get(position).getName());
        holder.tvIcon.setText(arrayList.get(position).getIcon());
        holder.tvId.setText(arrayList.get(position).getId());
        holder.tvSearchUrl.setText(arrayList.get(position).getSearchUrl());
        holder.tvNativeUrl.setText(arrayList.get(position).getNativeUrl());
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvName,tvIcon,tvId,tvSearchUrl,tvNativeUrl;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            tvName=itemView.findViewById(R.id.tvName);
            tvIcon=itemView.findViewById(R.id.tvIcon);
            tvId=itemView.findViewById(R.id.tvId);
            tvSearchUrl=itemView.findViewById(R.id.tvSearchUrl);
            tvNativeUrl=itemView.findViewById(R.id.tvNativeUrl);
        }
    }
}

layout.custom_layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:cardCornerRadius="15dp"
    app:cardElevation="5dp"
    app:cardUseCompatPadding="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="Name  : " />

            <TextView
                android:id="@+id/tvName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="Icon  : " />

            <TextView
                android:id="@+id/tvIcon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="Id  : " />

            <TextView
                android:id="@+id/tvId"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="SearchUrl  : " />

            <TextView
                android:id="@+id/tvSearchUrl"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="NativeUrl  : " />

            <TextView
                android:id="@+id/tvNativeUrl"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="" />

        </LinearLayout>

    </LinearLayout>

</android.support.v7.widget.CardView>

Bookmark model class

public class Bookmark
{
    String name,icon,id,nativeUrl,searchUrl;

    public String getName() {
        return name;
    }

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

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getNativeUrl() {
        return nativeUrl;
    }

    public void setNativeUrl(String nativeUrl) {
        this.nativeUrl = nativeUrl;
    }

    public String getSearchUrl() {
        return searchUrl;
    }

    public void setSearchUrl(String searchUrl) {
        this.searchUrl = searchUrl;
    }

    @Override
    public String toString() {
        return "Bookmark{" +
                "name='" + name + '\'' +
                ", icon='" + icon + '\'' +
                ", id='" + id + '\'' +
                ", nativeUrl='" + nativeUrl + '\'' +
                ", searchUrl='" + searchUrl + '\'' +
                '}';
    }
}

for more information please check below post

*

*Android - XML Parser

*Android XML Parser – XMLPullParser

*How to read XML File in Java (DOM Parser)

*Java SAX Parser Example

*Parsing XML data in Android Apps

*Android XML Parsing using DOM Parser

*Android XML Parsing Tutorial

*Learning to Parse XML Data in Your Android App
OUTPUT

A: You can use this library to parse XML into your POJO file. parsing can be done in your Fragment.


text:
Q: Can not use native code: Initialisation failed. Cannot create Excel Object I am trying to convert excel file to .csv file using ColdFusion code. I have written the following code. While I am trying to create excel COM object in server i am getting a java runtime exception like
"java.lang.RuntimeException: Can not use native code: Initialisation failed. Cannot create Excel Object"

I am using ColdFusion 8.0. Please help me to solve this exception.
Code:

<cfsetting enablecfoutputonly="Yes">

<cfparam name="sheetName" type="string" default="sheet1">
<cfparam name="showConfirmation" type="boolean" default="0">

<cftry>

  <cfobject
           action="CONNECT"
           class="Excel.Application"
           name="objExcel"
           type="COM">
  <cfcatch type="ANY">

    <cftry>
      <cfobject
               action="CREATE"
               class="Excel.Application"
               name="objExcel"
               type="COM">

      <cfcatch type="ANY">
        <cfoutput>
          <cfdump var="#cfcatch.Detail#">
          Cannot create Excel Object

Make sure Excel is installed on the ColdFusion Server.

Make sure that ColdFusion has permissions to
                                   use the Excel COM objects.

        </cfoutput>
        <cfabort>
      </cfcatch>
    </cftry>
  </cfcatch>
</cftry>
<cftry>
  <cfscript>
    // this code will open up the excel spread sheet and then save it as a CSV file.

    // Excel file path
    ExcelFilePath = "#path#csar_reports\Budgeting_Requests_as of_#date#.xls";

    // Destination path for new Excel spreadsheet
    // We leave off the extension since we'll declare the file type later on
    CSVFilePath = "#path#csar_reports\Budgeting_Requests_as of_#date#.csv";

    // Open Excel in the background
    objExcel.Visible = false;

    // Disable alerts such as: 'Save this document?'
    objExcel.DisplayAlerts = false;

    // Get the 'Documents' collection
    objBooks = objExcel.workbooks;

    // Open the Excel spreadsheet
    objBook = objBooks.Open(ExcelFilePath);

    // Get the sheets collection
    objSheets = objBook.WorkSheets;

    // Get the first sheet
    objSheet = objSheets.Item(Val(1));

    // Get a named sheet
    //objSheet = objSheets.Item("#sheetName#");

    /* Save it as a new document -- the extension will automatically
       be appended based on the file type we choose.
       Some of the file types to convert to:
       1 = .xls
       3 = .txt (tab delimetered)
       6 = .csv
    */
    objSheet.SaveAs(CSVFilePath, Val(6));

    // Close the spreadsheet
    objBook.Close();

    // Quit Excel
    objExcel.Quit();

    if (showConfirmation EQ 1) {
      writeOutput("File Created: ""#attributes.CSVFileOut#"" from file: ""#attributes.excelFileIn#""
");
    }
  </cfscript>

  <cfcatch>

    <cfoutput>
      there was an error creating your
                     new CSV filesfrom your Excel Spreadsheet

#cfcatch.message#

Caught an exception, type = #cfcatch.type#

The contents of the tag stack are:
 <cfloop index = i from = 1 to = #ArrayLen(cfcatch.tagContext)#> <cfset sCurrent = #cfcatch.tagContext[i]#>
#i# #sCurrent["ID"]# (#sCurrent["LINE"]#,#sCurrent["COLUMN"]#) #sCurrent["TEMPLATE"]# </cfloop>
    </cfoutput>
  </cfcatch>
</cftry>
<cfsetting enablecfoutputonly="no">


text:
Q: Home Network Setup and Advice I am wanting some ideas and advice for how to do my home network. I am an IT Technician and know the basics, however networking is not my strong suite and I want to improve.
[Current setup]
There are two family's in my house so I need to segregate the networks.
I have a TP-Link Arch c9 router(R1) connected to the internet box. Next I have my Asus RT68R (R2) connected to lan port of R1 and hosting the network for the reset of the house. The other family has their Linksys Router(R3) also connected to lan port on R1. All routers provide their own network with DHCP I understand that this is called triple nating and may cause some issue or latancy. R1 Has ip scheme of 10.0.20.x and R2 has IP scheme of 192.168.1.x R3 i dont know for sure but I believe it starts with 10.something. I belive all routers subnetmasks are set to 255.255.255.0 Not fully sure for R3 as I dont have access to their router.
Behind R2 is a file and domain server 2016 data center with 4-5 desktops and 2-3 wireless devices. R2 Also has a wireless ssid for the network and a guest ssid. R2 has a static ip from R1 and is on DMZ to allow for vpn access to R2 file server
[Problem]
The family that uses R3 has a problem every now and then were their router loses internet and the only thing that fixes it is rebooting R1 and some times even have to reboot all routers and internet box. To trouble shoot the issue I have tried scanning the network for R3 and pinging it from a device behind R2 But dose not find or see it how ever I can see R1 just fine. I talked with some co-workers and they believe the famly using R3 has configured something on their router that causes it to some times boot to a different setting like AP mode or bridge mode. Also discovered if I disable DHCP on R1 internet works fine for R2 and R3 but after a while R3 loses internet.
[What I would like to do]
I want to completely segregate R2 and R3 so they are not communicating at all to remove any type of conflict or issue that may be caused by the current setup. Behind R2 I would like to have a couple subnets for various devices to improve the security for more important devices. Example would be R2 main network With domain server and general home devices like media computer or roku or fire tv stick ect. Next would be a subnet for more personal device that may contain more important documents and files but I still want them to be able to communicate with the domain server and file server for network drive. Lastly I want two subnets one that is for testing purposes and fixing computers that may be infected so cant communicate with any other networks. The second would be for guests.
I understand some of what I want to do may cost more money and a firewall would be a good idea to help segragate R2 and R3 I just wonder if its at any way possible for me to do with type of setup with consumer grade routers and waps or if I really need business grade firewall/ managed switchs and waps
I have thought about buying some newer routers like netger xr500 or asus ac3100 and ubiquity waps.
Last question. is it possible to setup a guest ssid network on my asus router and assign devices on the lan ports to that network or is the guest network only accessible via wifi
I appreciate any help or advice any one has to offer.

A: 1) One possible reason for the "internet trouble" on R3 is that R3 seems to rely on DHCP for the connection to R1, and if this doesn't work for some reason, R3 looses the lease and therefore connection to R1. To debug this one would need access to R3.
One way to avoid that is to give both R2 and R3 static addresses, then you can disable DHCP on R1 (or reserve a static range). You'll need to set up the static address on R3, so talk to the other family ("it will help with your internet problems" is probably a good argument for "I'll need to do something on your router").
2) Ideally, only R1 should do NAT, but setting this up will require routing rules on R1 and correct setup of R2 and R3. Given the situation, this may not be so easy, so I guess you are stuck with double NAT (not triple NAT - on each path R2-R1 and R3-R1 both routers are doing NAT).
3) R2 and R3 "communicating" and causing trouble is very likely not the issue. You can set up a firewall on R1 if you are really worried about this. This will probably require a custom firmware like OpenWRT on R1 (Archer C9 should be supported), and will require some expertise, so maybe it's easier to just leave it as it is.
As R2 and R3 do both NAT, the networks behind R2 and R3 are effectively separated, anyway, even with additional firewall stuff.
4) If you want different subnets behind R2, you should be aware that this will require routing between subnets, which in turn will require routes on all members of a subnet. You can distribute routes via DHCP. For a similar question, see e.g. here.
This will require a very custom setup on R2, and again possibly open firmware on R2 if the provided firmware doesn't allow it. It's certainly possible to set something up like that, but it again requires some networking expertise.
5) A guest network on LAN isn't that different from a guest network on WLAN. But again, the firmware needs to support it. If the provided firmware doesn't, you need OpenWRT etc., and need to set it up yourself (which in addition needs a working understanding of firewall rules/iptables).
All of what you want to do is doable. Even without additional hardware (though you may need some LAN switches for all the devices if you don't have them yet). If you are doing it for the first time, don't underestimate the learning curve - you'll need to do quite a bit of reading up on networking fundamentals.

A: Segregation
This can be accomplished by using subnetting. Subnetting is the division of Network bits and host bits.  I don't know if you know this or not so I'll list it out.
For Private IP Addresses:
+-------+-------------------------+-------------+-------------------------------+
| Class |     Private Network     | Subnet Mask |             Range             |
+-------+-------------------------+-------------+-------------------------------+
| A     | 10.0.0.0                |   255.0.0.0 | 10.0.0.0 - 10.255.255.255     |
| B     | 172.16.0.0 - 172.32.0.0 | 255.240.0.0 | 172.16.0.0 - 172.31.255.255   |
| C     | 192.168.1.0             | 255.255.0.0 | 192.168.0.0 - 192.168.255.255 |
+-------+-------------------------+-------------+-------------------------------+

+-------+-------------------+-----------------+-------------+----------------+----------------------+-----------------------+
| Class | First Octet Range | High Order Bits | Notation ID | Default Subnet |   Num of Networks    |     Num of Hosts      |
+-------+-------------------+-----------------+-------------+----------------+----------------------+-----------------------+
| A     | 1 – 126           |               0 | N.H.H.H     |      255.0.0.0 | 126 (2^7 – 2)        | 16,777,214 (2^24 – 2) |
| B     | 128 – 191         |              10 | N.N.H.H     |    255.255.0.0 | 16,382 (2^14 – 2)    | 65,534 (2^16 – 2)     |
| C     | 192 – 223         |             110 | N.N.N.H     |  255.255.255.0 | 2,097,150 (2^21 – 2) | 254 (2^8 – 2)         |
|       |                   |                 |             |                |                      |                       |
+-------+-------------------+-----------------+-------------+----------------+----------------------+-----------------------+

See IP address classes, if you have tabs.
Using the above tables, and the data from your question:

*

*R1 is using a Class A address.

*R2 is using a Class C address.

*R3 is using a Class A address.

*

*Surely you don't need 16,777,214 LAN devices on your network.  Let's put them all in the Same Class, which should be Class C.

*Make sure all Routers are set to the same IP Protocol.  If your ISP and modem support IPv6, and it's currently set to IPv6, all devices in the line must support IPv6.  If one device only does IPv4 then you must set all devices to IPv4.

*Decide on a topology.  There are some options here:

*

*Remove all Routers except the one connected to the ISP:  Replace Both routers with one switch, with enough ports to support all family members.  Buying say three switches and bridging 2, also works.  Using a switch would alleviate subnetting all together, as each device is now all in one subnet, and share only the wireless password between the families.

*Let each router be its own subnet:  Use MAC Address filtering so that the DHCP service in R1 always gives the same IP addresses to R2 and R3, since you have them uplinked. @djkrt alluded to this in his suggestion regarding static IP addresses.

*After choosing a topology, read Subnetting Made Easy, and then use this Subnet calculator, to calculate the proper subnet for R2, and again for R3.

Note that R3, must be in a different subnet to divide the traffic, and will not communicate with R1 or R2 unless you enable routing rules, like port forwarding etc. Also note that if you want R1 and R2 to communicate together they must be in the same Class and subnet. NAT Translation only occurs once if this is fixed.  R3 may be losing connection because NAT has occurs twice.  Once from the original translation and again when R3 adds the information to it's own ARP table.


text:
Q: How to check if a character in a string is a digit or letter I have the user entering a single character into the program and it is stored as a string. I would like to know how I could check to see if the character that was entered is a letter or a digit. I have an if statement, so if its a letter its prints that it's a letter, and the same for a digit. The code I have so far doesn't work but I feel like I'm close. Any help you can offer is appreciated.
  System.out.println("Please enter a single character: ");
  String character = in.next();

  System.out.println(character);

  if (character.isLetter()){
    System.out.println("The character entered is a letter.");
  }
  else (character.isDigit()){
    Syste.out.println("The character entered is a digit.");

A: You could use:
    if (Character.isLetter(character.charAt(0))){
    ....

A: This is a little tricky, the value you enter at keyboard, is a String value, so you have to pitch the first character with method line.chartAt(0) where, 0 is the index of the first character, and store this value in a char variable as in char c= line.charAt(0)
now with the use of method isDigit() and isLetter() from class Character you can differentiate between a Digit and Letter.
here is a code for your program:
import java.util.Scanner;

class Practice
{
 public static void main(String[] args)
  {
   Scanner in = new Scanner(System.in);
   System.out.println("Input a letter");
   String line = in.nextLine();
   char c = line.charAt(0);
   if( Character.isDigit(c))
   System.out.println(c +" Is a digit");
   else if (Character.isLetter(c))
   System.out.println(c +" Is a Letter");
  }

}

A: By using regular expressions:
boolean isChar = character.matches("[a-zA-z]{1}");
boolean isDigit = character.matches("\\d{1}");

A: char charInt=character.charAt(0);
if(charInt>=48 && charInt<=57){
    System.out.println("not character");
}
else
    System.out.println("Character");

Look for ASCII table to see how the int value are hardcoded .

A: This is the way how to check whether a given  character is alphabet or not
public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    char c = sc.next().charAt(0);
    if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
         System.out.println(c + " is an alphabet.");
    else
        System.out.println(c + " is not an alphabet.");
}

A: You could use the existing methods from the Character class. Take a look at the docs:
http://download.java.net/jdk7/archive/b123/docs/api/java/lang/Character.html#isDigit(char)
So, you could do something like this...
String character = in.next();
char c = character.charAt(0);
...
if (Character.isDigit(c)) {
    ...
} else if (Character.isLetter(c)) {
    ...
}
...

If you ever want to know exactly how this is implemented, you could always look at the Java source code.

A:      char temp = yourString.charAt(0);
     if(Character.isDigit(temp))
     {
         ..........
     }else if (Character.isLetter(temp))
     {
          ......
      }else
     {
      ....
     }

A: import java.util.*;

public class String_char
{

    public static void main(String arg[]){

        Scanner in = new Scanner(System.in);
        System.out.println("Enter the value");
        String data;
        data = in.next();

        int len = data.length();
        for (int i = 0 ; i < len ; i++){
            char ch = data.charAt(i);

            if ((ch >= '0' && ch <= '9')){
                System.out.println("Number ");
            }
            else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
            System.out.println("Character");
            }
            else{
                System.out.println("Symbol");
             }
        }
    }
}

A: Ummm, you guys are forgetting the Character.isLetterOrDigit method:
boolean x;
String character = in.next();
char c = character.charAt(0);
if(Character.isLetterOrDigit(charAt(c)))
{
  x = true;
}

A: You need to convert your string into character..
String character = in.next();
char myChar = character.charAt(0);

if (Character.isDigit(myChar)) {
   // print true
}

Check Character for other methods..

A: You could do this by Regular Expression as follows
you could use this code
EditText et = (EditText) findViewById(R.id.editText);
String NumberPattern = "[0-9]+";
String Number = et.getText().toString();

if (Number.matches(NumberPattern) && s.length() > 0)
{
    //code for number
}
else
{
    //code for incorrect number pattern
}

A: I have coded a sample program that checks if a string contains a number in it! I guess it will serve for this purpose as well.
public class test {
    public static void main(String[] args) {
        String c;
        boolean b;

        System.out.println("Enter the value");
        Scanner s = new Scanner(System.in);
        c = s.next();
        b = containsNumber(c);
        try {
            if (b == true) {
                throw new CharacterFormatException();
            } else {
                System.out.println("Valid String \t" + c);
            }
        } catch (CharacterFormatException ex) {
            System.out.println("Exception Raised-Contains Number");

        }
    }

    static boolean containsNumber(String c) {
        char[] ch = new char[10];
        ch = c.toCharArray();

        for (int i = 0; i < ch.length; i++) {
            if ((ch[i] >= 48) && (ch[i] <= 57)) {
                return true;
            }
        }
        return false;
    }
}

CharacterFormatException is a user defined Exception. Suggest me if any changes can be made.


text:
Q: Merge git commit history After merge all commits into one (for rewrite git log history) on local machine (this operation was succesfull) I have a notice after command git status
Your branch and 'origin/master' have diverged,
# and have 1 and 8 different commits each, respectively.

These 8 commits are those commits that I have been merged into one.
I tried to do git push --force origin master and the result is
Compressing objects: 100% (9924/9924), done.
Writing objects: 100% (21454/21454), 24.68 MiB | 2.95 MiB/s, done.
Total 21454 (delta 8595), reused 20826 (delta 8591)
remote: error: denying non-fast-forward refs/heads/master (you should pull first)
To http://somesite.com/gitproject.git
! [remote rejected] master -> master (non-fast-forward)
error: failed to push some refs to 'http://somesite.com/gitproject.git'

And branches remained diverged.
And I think if I'll do git pull then all git commits history that have been merged appear again on local machine.
To cut a long story short how can I push local git commits history into origin branch?

A: Looks like the problem here is like some commits have been pushed to origin from someone while you made your own commits locally.
So your history in git looks like something like this.
*   d993799 Commit 1
*   caa12d6 Commit 2
|\
| * e38fecc Your Commit
|
*   29158f8 Commit 3

Now, you have two options, do a Merge or a Rebase
git merge origin/master

or
git rebase origin/master

Pro Tip after you do commits locally when you are ready to push into origin do a git pull --rebase doing that is going to pull the latest version of origin and then it is going to try to update your changes
Some Awesome url:
http://git-scm.com/book/en/Git-Branching-Rebasing


text:
Q: Nox player isn't showing in android studio I have an AMD A10 processor that doesn't support VT-x. I installed Nox player and enabled USB debugging but still Android studio cannot find the emulator. Any helpful and clear steps to install USB driver adb(Android Debug Bridge)

A: Connect a NOX device to Android Studio: By Abhijeet Pal

On CMD:

*

*Route: cd C:\Program Files (x86)\Nox\bin

*Connection: nox_adb.exe connect 127.0.0.1:62001

Not Connecting Fix
You need to find the correct port and use it. I faced the same problem so here is what I did.

*

*Kill the server:

nox_adb.exe kill-server

*Now try to connect on any port number, say, 62001:

C:\Program Files (x86)\Nox\bin>nox_adb.exe connect 127.0.0.1:62001

*

*daemon not running. starting it now on port 5037

*daemon started successfully

*unable to connect to 127.0.0.1:62001:62001

*Now try to use port 5037 as mentioned in the output above:

C:\Program Files (x86)\Nox\bin>nox_adb.exe kill-server
C:\Program Files (x86)\Nox\bin>nox_adb.exe connect 127.0.0.1:5037

*

*daemon not running. starting it now on port 5037

*daemon started successfully

*connected to 127.0.0.1:5037

It should work fine then.
127.0.0.1:5037 Disconnected on Android Studio Solution

It should appear without any further customizations. I have used Nox Emulator for a while and you have to do a little trick to make it work for debugging:

*

*Click the debug or run button on Android Studio2. Wait for the popup to open (the one where it lists the connected devices)3. Run Nox Emulator4. After Nox is ready and running, it should appear on your connected devices list.
    This isn't of my authorship, that's why I attached all sources of problems that I've faced.

A: I made the mistake of starting the adb server before and then opening android studio. It didn't work.
Subsequently did this:
D:\Program Files\Nox\bin>nox_adb.exe connect 127.0.0.1:62001
adb server version (41) doesn't match this client (36); killing...
* daemon started successfully *
connected to 127.0.0.1:62001

Android studio immediately updated and showed the following:


text:
Q: Why Babel 7 uses require() function for browser which knows nothing about it? I try to use d3.js in my module. I use Babel 7 for  transpiling my code sources.
This is my package.json:
{
  "name": "d3_learning",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "build": "babel src --out-dir dist --source-maps --minified --no-comments",
    "build:watch": "npm run build -- -w"
  },
  "babel": {
    "presets": [
      [
        "@babel/preset-env",
        {
          "useBuiltIns": "entry",
          "targets": {
            "firefox": "64",
            "opera": "57",
            "chrome": "71",
            "edge": "44",
            "ie": "11"
          }
        }
      ]
    ]
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.2.3",
    "@babel/core": "^7.2.2",
    "@babel/node": "^7.2.2",
    "@babel/polyfill": "^7.2.5",
    "@babel/preset-env": "^7.2.3",
    "@babel/register": "^7.0.0"
  },
  "dependencies": {
    "d3": "^5.7.0"
  }
}

Pay attention in the targets section I pointed the versions of web browsers are interest for me. Browsers know nothing about require function. Only Node.js knows about it.
This is my source code:
import * as d3 from 'd3';

function draw(data) {
    // ...
}

d3.json('../data/some-data.json', draw);

But I see Babel 7 code generation result contains require function:
"use strict";var d3=_interopRequireWildcard(require("d3"));...
Therefore I get runtime error in the browser:

Uncaught ReferenceError: require is not defined

Why does it happen and how can I solve the problem?

A: Yes require() is not built into the browser.
Babel converts import and export declaration to CommonJS (require/module.exports) by default.
Babel doesn't do anything,It basically acts like const babel = code => code;
by parsing the code and then generating the same code back out again.
If you want to run modern JavaScript in the browser, Babel on its own is not enough, you also need a build system or bundler that supports CommonJS modules statements:

*

*Babelify + Browserify

*Babel + WebPack
These two tools will transform your require calls to work within the browser.

*

*Compile to AMD format (transform-es2015-modules-amd) and include Require.js in your application  [I am using this since my existing app relays on grunt, require]

Hope it helps  and created a simple webpack , babel setup check it out if you need. webpack-babel setup


text:
Q: Integrating single variable out of marginal I have just seen that
$$
P(w|x, y) = \int P(w|x, y, z) P(z|x, y) dz
$$
I thought it would be
$$
P(w|x, y) = P(x,y)\int P(w|x, y, z) P(z|x, y) dz
$$
Can someone explain to me why it isn't?

A: For simplicity we will denote
$$P(\cdot|x,y):=P(\cdot)$$
as the dependence is always present in the example.
Now, first think about it in terms of events. Let $C$ be the certain event, ie. $P(C)=1$. Than we have $W\cap C = W$. Than, let $C=\cup_i Z_i$, and $\cap_i Z_i = \emptyset$ (meaning that $Z_i$ are a perfect set of events).
$$P(W)=P(W\cap C)=P(W\cap\cup_i Z_i)=P(\cup_i W\cap E_i)=\sum_i P(W\cap Z_i)$$
which is the law of total probability. Now, in the continuous case
$$P(W\cap Z_i)=\int_{a_i}^{b_i} p(W|z)p(z)dz$$
Thus
$$P(W\cap Z)=\sum_i P(W\cap Z_i)=\int p(W|z)p(z)dz$$


text:
Q: In Brightcove, can I retrieve a video's thumbnail WITHOUT a media API token? I would like to use Javascript to retrieve thumbnail URLs from Brightcove-hosted videos.
I can't see a way to do that without exposing my Media API token to the client browser.  (The with-token method is documented here.)
I don't need a token to show the whole video, so it seems insane and unnecessary that I need a token to get the thumbnail url, which obviously I would want to show to the user anyway.
The only workaround I can devise is to create a middleman interface on the server.  (The client JS makes a request to my server, which uses the token to request the thumbnail from BC, then returns it back to the JS.)  That's just annoying.
Am I missing something?  Is there an alternate way to retrieve video thumbnails in the client without exposing the Media API key?

A: According to Brightcove's support, they tell me that the answer is "NO".
They do recommend a server-side relay, which is what I ended up writing, and it works fine.
Disappointing, though.


text:
Q: Swift dynamic properties in initialization I am working in Xcode 7 beta 5 with Swift 2.0.  I think I am having an issue with initialization of a struct.
enum Resource {
    case gold
    case elixer
    case darkElixer
}

class Avatar {
    let cost, health, damage, space: Int
    let lifeSpan: Double
    let costType: Resource

    init(damage: Int, health: Int, cost: Int, costType: Resource, space: Int){
        self.damage = damage
        self.health = health
        self.cost = cost
        self.costType = costType
        self.space = space
        self.lifeSpan = Double(damage / health)
}

I am having trouble with the line.
self.lifeSpan = Double(damage / health)

I'm just trying to figure out how to dynamically set properties during initialization.

A: After doing some research I found the answer to be.
var lifeSpan: Double {
    get {
        return  Double(health) / Double(damage)
    }

}


text:
Q: Windows => Webdav folders are empty, when it contains an HTML file I'm experiencing a very weird behavior on Windows 7. I've included a WebDav server (Apache) into my Windows Explorer (Map Network Drive).
Every folder works fine and Windows displays all contents correctly... until I add an HTML file to that folder, then Windows is not able to display the contents of the folder anymore. First it shows an empty folder and then it tells me that the "disc might be corrupt". As soon as I remove the html file on the server, everything is working fine again.
So for some reason WebDav tries to interpret the HTML files (As it does when I visit that folder from a browser). I've already created an .htaccess file that contains the following, but that didn't help.
RemoveHandler .html
RemoveType .html
Do you guys have any idea what might be causing this?
Thank you very much in advance,
Sascha

A: Found the fix:
I just added DirectoryIndex disabled to the VirtualHost! :)


text:
Q: pyqt5 QMessageBox not open from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(9576, 698)
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(9)
        MainWindow.setFont(font)
        MainWindow.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(20, 30, 221, 421))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.RButton = QtWidgets.QRadioButton(self.verticalLayoutWidget)
        font = QtGui.QFont()
        font.setPointSize(20)
        self.RButton.setFont(font)
        self.RButton.setObjectName("RButton")
        self.verticalLayout.addWidget(self.RButton)
        self.RButton2 = QtWidgets.QRadioButton(self.verticalLayoutWidget)
        font = QtGui.QFont()
        font.setPointSize(20)
        self.RButton2.setFont(font)
        self.RButton2.setObjectName("RButton2")
        self.verticalLayout.addWidget(self.RButton2)
        self.RButton3 = QtWidgets.QRadioButton(self.verticalLayoutWidget)
        font = QtGui.QFont()
        font.setPointSize(20)
        self.RButton3.setFont(font)
        self.RButton3.setObjectName("RButton3")
        self.verticalLayout.addWidget(self.RButton3)
        self.Button = QtWidgets.QPushButton(self.centralwidget)
        self.Button.setGeometry(QtCore.QRect(390, 150, 351, 221))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(24)
        self.Button.setFont(font)
        self.Button.setFocusPolicy(QtCore.Qt.NoFocus)
        self.Button.setAutoDefault(False)
        self.Button.setObjectName("Button")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 957, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.Button.clicked.connect(self.btn_clicked)
        self.RButton.clicked.connect(self.btn_clicked)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def btn_clicked(self):
        QMessageBox.about(self,"창","안녕")

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.RButton.setText(_translate("MainWindow", "버튼1"))
        self.RButton2.setText(_translate("MainWindow", "버튼2"))
        self.RButton3.setText(_translate("MainWindow", "버튼3"))
        self.Button.setText(_translate("MainWindow", "확인"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

when button clicked program is turn off...
I need help

A: The problem is caused because QMessageBox.about() requires as a first parameter a widget but self, that is Ui_MainWindow, is not a widget. Qt Designer does not generate a widget but creates a class that fills a widget. It is also not recommended to modify the class generated by Qt Designer, it is appropriate to create a class that inherits from the appropriate widget and use the design class
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
        self.setupUi(self)
        self.Button.clicked.connect(self.btn_clicked)
        self.RButton.clicked.connect(self.btn_clicked)

    def btn_clicked(self):
        QMessageBox.about(self,"창","안녕")

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())


text:
Q: Disable orange higlight on a Menu using Android A link(Menu) is highlighted by orange color after the user tap on it on android browser. I would like to remove this highlight.
I tried to search but and found some answers but when i tried it didn't work in my case. Is there anyone who can guide me?
ul {
  -webkit-tap-highlight-color: transparent;
  float: right;
  li {
    -webkit-tap-highlight-color: transparent;
    float: left;
    padding-left: 40px;
    font-size: 10px;
    font-weight: 900;
    letter-spacing: 0.04rem;
    text-transform: uppercase;
  }
}


text:
Q: How to extract substring starting from index of particular character upto the index of some other character from given string? Suppose, i have a string str = "lorem ipsum src="https://www.youtube.com/embed/HyvFqW7xE1c" lorem ipsum". i want to extract substring https://www.youtube.com/embed/HyvFqW7xE1c which is actually a url. I can extract index of "h" which is starting index of the required url by using indexOf() method. But how can i extract complete url where length is url is not fixed.

A: You can use RegExp() and Iterable<RegExpMatch> to get URL from string.
  var text = """lorem ipsum src="https://www.youtube.com/watch?v=dQw4w9WgXcQ" lorem
  ipsum""";
  RegExp exp = new RegExp(r'(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-?=%.]+');
  Iterable<RegExpMatch> matches = exp.allMatches(text);

  matches.forEach((match) {
    print(text.substring(match.start, match.end));
  });

Resource Here


text:
Q: Intersection Polygon-PolyLine with pyqgis I want to make intersection between polygon and polyline shapefile with pyqgis, but I get an empty output. Here the code that i use :
params = {'INPUT': polygone.shp, 'OVERLAY': line.shp, 'INPUT_FIELDS': [], 'OVERLAY_FIELDS': [], 'OUTPUT': 'memory'}
processing.run('native:intersection', params)

bellow the picture of polygon and polyline shapefile. The both shapefiles have the same crs : epsg:2154

A: Create a buffer of the line layer and use that as the overlay layer instead.


text:
Q: How to store data with large number (constant) of properties in SQL I am parsing the USDA's food database and storing it in SQLite for query purposes.  Each food has associated with it the quantities of the same 162 nutrients.  It appears that the list of nutrients (name and units) has not changed in quite a while, and since this is a hobby project I don't expect to follow any sudden changes anyway.  But each food does have a unique quantity associated with each nutrient.
So, how does one go about storing this kind of information sanely.  My priorities are multi-programming language friendly (Python and C++ having preference), sanity for me as coder, and ease of retrieving nutrient sets to sum or plot over time.
The two things that I had thought of so far were 162 columns (which I'm not particularly fond of, but it does make the queries simpler), or a food table that has a link to a nutrient_list table that then links to a static table with the nutrient name and units.  The second seems more flexible i ncase my expectations are wrong, but I wouldn't even know where to begin on writing the queries for sums and time series.
Thanks

A: You should read up a bit on database normalization. Most of the normalization stuff is quite intuitive, but really going through the definition of the steps and seeing an example helps understanding the concepts and will help you greatly if you want to design a database in the future.
As for this problem, I would suggest you use 3 tables: one for the foods (let's call it foods), one for the nutrients (nutrients), and one for the specific nutrients of each food (foods_nutrients).
The foods table should have a unique index for referencing and the food's name. If the food has other data associated to it (maybe a link to a picture or a description), this data should also go here. Each separate food will get a row in this table.
The nutrients table should also have a unique index for referencing and the nutrient's name. Each of your 162 nutrients will get a row in this table.
Then you have the crossover table containing the nutrient values for each food. This table has three columns: food_id, nutrient_id and value. Each food gets 162 rows inside this table, oe for each nutrient.
This way, you can add or delete nutrients and foods as you like and query everything independent of programming language (well, using SQL, but you'll have to use that anyway :) ).
Let's try an example. We have 2 foods in the foods table and 3 nutrients in the nutrients table:
+------------------+
| foods            |
+---------+--------+
| food_id | name   |
+---------+--------+
| 1       | Banana |
| 2       | Apple  |
+---------+--------+

+-------------------------+
| nutrients               |
+-------------+-----------+
| nutrient_id | name      |
+-------------+-----------+
| 1           | Potassium |
| 2           | Vitamin C |
| 3           | Sugar     |
+-------------+-----------+

+-------------------------------+
| foods_nutrients               |
+---------+-------------+-------+
| food_id | nutrient_id | value |
+---------+-------------+-------+
| 1       | 1           | 1000  |
| 1       | 2           | 12    |
| 1       | 3           | 1     |
| 2       | 1           | 3     |
| 2       | 2           | 7     |
| 2       | 3           | 98    |
+---------+-------------+-------+

Now, to get the potassium content of a banana, your'd query:
SELECT food_nutrients.value
  FROM food_nutrients, foods, nutrients
  WHERE foods_nutrients.food_id = foods.food_id
    AND foods_nutrients.nutrient_id = nutrients.nutrient_id
    AND foods.name = 'Banana'
    AND nutrients.name = 'Potassium';

A: Use the second (more normalized) approach.
You could even get away with fewer tables than you mentioned:

*

*tblNutrients
-- NutrientID
-- NutrientName
-- NutrientUOM (unit of measure)
-- Otherstuff

*tblFood
-- FoodId
-- FoodName
-- Otherstuff

*tblFoodNutrients
-- FoodID (FK)
-- NutrientID (FK)
-- UOMCount
It will be a nightmare to maintain a 160+ field database.
If there is a time element involved too (can measurements change?) then you could add a date field to the nutrient and/or the foodnutrient table depending on what could change.


text:
Q: Is it possible to install 2 different versions of an application at the same time Won't it have any conflicts? Because I am using an old version of virtual box and I want to try the newest version but I haven't still completed my download in the virtual ose.

A: It completely depends on how the software is written. Some do, some don't.

*

*If when you install the latest
version it implements a
library/file/registry entry in the
same location as the older version
and that library/file/registry entry
is incompatible it will break the
older version.

*If it doesn't, you should be fine.
Your best bet would be to ask the Virtual Box people themselves.

A: In general software you can often get away with it (depending on what operating system your running and how you configure things).
However, this is VirtualBox. DO NOT RUN TWO VERSIONS AT ONCE. They will almost certainly conflict. Especially if you are using hardware assisted virtualization (VTX).


text:
Q: Cant connect to selenium over Tor I am using selenium in Kali to connect to Tor, the path is correct for the TOR package (i double checked).
Keep getting this error, been driving me crazy. Any input would be highly appreciated.


text:
Q: Parsing excel string of numbers using vba I am trying parse a number string and create rows accordingly. On the left of the Example Data picture is an example of the input data with the right being my desired output. I am wanting to insert a unique row of data for each digit within the brackets for each number combination.

Here is an example of the code I used to try to solve the problem.
Option Explicit

Sub example()

Dim num As Variant
Dim x As Variant
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim m As Integer
Dim test As Variant
Dim test2 As Variant
Dim count As Integer

m = 0

For i = 1 To 3

num = Range("C" & 5 + i + m).Value

For j = 1 To Len(num)

    test = Mid(num, j)

    If Left(Mid(num, j), 1) = "[" Then

        For k = 1 To Len(num) - (j + 1)

            m = m + 1

            Range("C" & 5 + m + i - 1).EntireRow.Insert

            test2 = Left(Mid(num, j + k), 1)

            Range("C" & 5 + m + i - 1).Value = Left(num, j - 1) + test2

        Next k

    End If

Next j

Next i

End Sub

A: Please consider using the following script:
Sub splitcombinations()

Dim rngCell As Range
Set rngCell = ThisWorkbook.Sheets(1).Range("A2")

Dim strCombinationDigits As String, strBaseDigits As String
Dim intCombinationDigitsLen As Integer

Dim x As Integer

Do While rngCell.Value2 <> ""

    If InStr(rngCell.Value2, "[") > 0 Then

        strCombinationDigits = Mid(rngCell.Value2, InStr(rngCell.Value2, "[") + 1, InStr(rngCell.Value2, "]") - InStr(rngCell.Value2, "[") - 1)
        intCombinationDigitsLen = Len(strCombinationDigits)

        strBaseDigits = Left(rngCell.Value2, InStr(rngCell.Value2, "[") - 1)

        ActiveSheet.Range(rngCell.Offset(1, 0), rngCell.Offset(intCombinationDigitsLen - 1, 0)).EntireRow.Insert

        For x = 1 To intCombinationDigitsLen

            rngCell.Offset(x - 1, 0).Value2 = strBaseDigits & Mid(strCombinationDigits, x, 1)
            rngCell.Offset(x - 1, 1).Value2 = rngCell.Offset(0, 1).Value2
            rngCell.Offset(x - 1, 2).Value2 = rngCell.Offset(0, 2).Value2

        Next

    End If

    Set rngCell = rngCell.Offset(intCombinationDigitsLen , 0)

Loop

End Sub


text:
Q: MongoDB, How to get ObjectId that just created in Embedded document? I'm creating a Post & Comments, and I designed to post contains comments. "Comments" is embedded document(Object Array) field that contains comment information, and uses "_id" as unique identifier. This is the code(Note that I'm using Node.js with extra mongoDB library) :
db.update('posts', {
    _id: new ObjectID(postId)
}, {
    $push: {
        comments: {
            _id: new ObjectID(),
            author: comment.author,
            email: comment.email,
            text: comment.text
        }
    }
}) ...

Look at the $push, you can see that I created new ObjectId. It's working well, but I want to send back the _id that just created comment to the client, so make client can erase or edit without page refresh. How do I get the _id that just created embedded document?

A: How about setting them to variables when you create the ids:
const id1=new ObjectID(postId);
const id2=new ObjectID();

db.update('posts', { _id: id1 },
 { $push:
 { comments: { _id: id2,
    author: comment.author,
    email: comment.email,
    text:   comment.text } } }) ...


text:
Q: How to make a chef recipe to be idempotent in chef for SUSE os I've written a chef recipe for SUSE, to install a package, wherein it's installing it however it keeps running the enable command every time when the chef-client runs, even though there is no change in the configuration.
recipe sample example:
zypper_package 'apache2' do
action :install
end

service 'apache2' do
action  [:enable, :start]
end

Please advise, how to make it idempotent?

A: I've run into this situation with SuSE. At least with the version of chef i'm using (12.13, not sure about newer versions) seem to get the init determination wrong so the internal test to see if the service is already enabled does not work right.
The most interesting thing about it was that the provider i found to work on SLES 11 was Chef::Provider::Service::Redhat. I had to handle supporting both 11 and 12 so i ended up using an if block within the resource definition
service 'apache2' do
  action [:enable, :start]
  if node['init_package'] != 'systemd'
    provider Chef::Provider::Service::Redhat
  end
end

I just spent the better part of 30 minutes digging through all of my cookbooks trying to find the original, but couldn't, i did just confirm that SLES SP4 exhibits the behavior you described, and that the above fixed it
-----> Converging <default-sles-11-sp4>...
Recipe: apache_test::default
  * zypper_package[apache2] action install (up to date)
  * service[apache2] action enable (up to date)
  * service[apache2] action start (up to date)

A: Try using not_if. You can wrap the enable in some kind of condition based on the presence of a configuration file to not run the command.
e.g.
package 'Install Apache' do
   package_name 'apache2'
   action :enable
   not_if do ::File.exists?(/some/config/file.conf) end
end


text:
Q: How do I initialize cubejs library? I want to use this library to model and solve a cube from a string: https://github.com/ldez/cubejs but I have no clue how to include it on my website. I read the readme file and wrote this script:
Cube.initSolver();
var cube = new Cube();
cube = Cube.fromString(this.s); //s is a string from an external script in a format which should work
console.log('facelet: ' + cube.asString());
console.log('Solve: ' + cube.solve());
console.log('Is cube solved? ' + cube.isSolved());

I then included the js script in header of html:
<script src="js/solver.js"></script>

Is the script initialized or what?
console.log is there so that i could potentially see something happen but nope.
I really have no clue. all js files are in the same folder.


text:
Q: Show CCLabel for few seconds on touch I'm new to Cocos Sharp and have been struggling to implement behaviour from question title. I want to show message to user that will fade or disappear after some period of time, lats say 3 seconds, after user touches some sprite. But I can't figure it out how to do that.
I'm showing CCLabel like this:
var scoreLabel = new CCLabel("Touch Menu and Exit button together to exit!", "Arial", 50, CCLabelFormat.SystemFont);
scoreLabel.PositionX = button.PositionX;
scoreLabel.PositionY = button.PositionY + 300;
scoreLabel.AnchorPoint = CCPoint.AnchorMiddleRight;

Can someone help me?

A: After 3 seconds, fadeout in 1 second
scoreLabel.RunActions(new CCDelayTime(3), new CCFadeOut(1));


text:
Q: Is it possible to run certain layers of a network on different devices on Tensorflow? I have been trying to run inference on a custom Tensorflow model on Movidius Neural Compute Stick. The problem is, the final layer is unsupported by NCSDK. Since the final layer is computationally quite light, I would like to know if there is a possibility to run that layer on CPU?
My previous searches led me to these:
Distributed Tensorflow
Placing Variables on CPU??
I just need to be able to run inference up to a certain layer on the NCS, then process the last layer on CPU.

A: Using mvNCCompile and the -in and -on options of NCS might help. Compile a model with -in input and then use -on  to specify the output node as the last node that you need to run on NCS. This will create a graph file that takes input from the input node and give the output node. So instead of processing the data through the entire model, you can get the output of the intermediate results of whatever node you choose.
After getting the result from intermediate layer from NCS, you might have to give this as input to the last layer which has to run on CPU.
You could find a similar discussion in the link.


text:
Q: Cannot access a website, DNS fails I can't access my website, the DNS fails at a certain point.
I don't understand much of this stuff, so I hope someone can give a simple answer for this question:
Can I fix it even if it is a temporary solution? How?
I believe these questions are the exact thing that is happening to me

*

*Dns failing to propagate worldwide

*Why did this website dns change fail in some parts of the us
C:\> tracert ryuushin.net
1 192.168.1.1
2 201.67.130.254
3 201.10.252.173
4 201.10.235.89
5 201.10.241.18
6 66.110.68.33
7 66.110.68.6
8 64.86.9.77
9 64.86.9.14
10 209.58.44.2
11 68.86.86.81
12 68.86.85.153
13 68.86.86.94
14 75.149.228.2
15 70.87.253.50
16 74.55.252.146 ( 2-1.dsr01.hstntx.theplanet.com )
17 74.55.252.82 ( p01.car06.hstntx2.theplanet.com )
18 * * * Request timed out.
19 * * * Request timed out.
...
30 * * * Request timed out.

If I am missing any info let me know...
Update:
C:\>nslookup ryuushin.net
DNS request timed out.
    timeout was 2 seconds.
Server:  UnKnown
Address:  fe80::29d3:9dff:56ed:1b1d

DNS request timed out.
    timeout was 2 seconds.
DNS request timed out.
    timeout was 2 seconds.
DNS request timed out.
    timeout was 2 seconds.
DNS request timed out.
    timeout was 2 seconds.
*** Request to UnKnown timed-out

Update2:
C:\>ping ryuushin.net
Pinging ryuushin.net [174.123.210.242] with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.

Ping statistics for 174.123.210.242:
    Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),

Accessing the page
The connection has timed out
The server at ryuushin.net is taking too long to respond.

Of note: It was working just fine until Sunday morning, when it sundently started to behave like this.

A: dns lookup is resolving to: 174.123.210.242
what you're doing is not dns. you are tracing the server hops to get to wherever your site is hosted.
not all servers will respond to a ping, and not all ipaddresses will resolve to a domain name
to test dns resolution use on a windows box: nslookup ryuushin.net
if this is not working in all locations, be patient, dns can take a fair while to replicate around the world.
if after 48 hours it is still failing, get in contact with your domain name host or registar.
after your update:
check this url for lookup information:
http://www.dnswatch.info/dns/dnslookup?la=en&host=+ryuushin.net&type=A&submit=Resolve
it looks like your dns on your machine is a bit funky.
that you're able to do a tracert suggests that the dns is resolving to an IP address ok.
what do you get if you just do: ping ryuushin.net
also, what do you get when you open the page in a web browser.
i get an apache config page from here, so i would suggest the issue is somewhere on your LAN.

A: Based on your update it looks like there is indeed a DNS issue but your first problem is to determine at what point that error is, because it might just as easily be on your own machine. Start systematically eliminating links in the chain. Start at the DNS server, checking firstly that you do in fact have the correct entries, and work back to your machine until the lookup fails.

A: Your web site and the DNS servers are all on the same subnet (174.123.210.242 - 244).  This is a single point of failure.
That network had some connectivity issues (I can't reproduce them now) so not only did your site stop responding, but for some the domain would have stopped resolving too.   This would also cause inbound e-mail to bounce instead of queue.
Invest in some diverse DNS hosting, so that your DNS continues to work even if the main web hosting goes down.  A google search for "secondary DNS provider" should reveal plenty.


text:
Q: Spring Boot Microservices Fetching Config from Server Over Https We are switching over our microservice ecosystem from http to https.  I have been able to boot out Eureka Gateway Service in https and have our Config Service connect and register itself over https.
However, when I boot a third service that requires configurations, I cannot get the service to fetch the configs over https:
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.0.RELEASE)

2018-09-06 15:03:21.260  INFO 2800 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at: http://blah

I have researched several Spring Boot Https guides, and have tried many different combinations of configurations.  I will paste the bootstraps for the relevant services.  There may be some redundant info because I had tried so many different things.
bootstrap.yml for the Gateway Service:
server:
  port: 8761
  transport: https
  ssl:
    enabled: true
    key-store: serverkeystore.p12
    key-store-password: changeit
    key-store-type: PKCS12
    key-alias: serverkey
spring:
  application:
    name: gateway
  cloud:
    config:
      enabled: false
eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
    healthcheck:
      enabled: true
    service-url:
      defaultZone: https://localhost:8761/eureka
  server:
    enableSelfPreservation: false
  instance:
    hostname: localhost
    nonSecurePortEnabled: false
    securePortEnabled: true
    statusPageUrl: "https://${eureka.instance.hostname}:${server.port}/info"
    healthCheckUrl: "https://${eureka.instance.hostname}:${server.port}/health"
    homePageUrl: "https://${eureka.instance.hostname}:${server.port}/"

security:
  require-ssl: true

bootstrap.yml for Config Service:
server:
  port: 8085
  transport: https
  ssl:
    enabled: true
    key-store: serverkeystore.p12
    key-store-password: changeit
    key-store-type: PKCS12
    key-alias: serverkey

spring:
  application:
    name: config
eureka:
  client:
    serviceUrl:
      defaultZone: https://localhost:8761/eureka

security:
  require-ssl: true

bootstrap.yml for Third Service:
server:
  port: 1111
  transport: https
  ssl:
    enabled: true
    key-store: serverkeystore.p12
    key-store-password: changeit
    key-store-type: PKCS12
    key-alias: serverkey
spring:
  application:
    name: service
  cloud:
    config:
      failFast: true
      discovery:
        enabled: true
        serviceId: config
eureka:
  client:
    serviceUrl:
      defaultZone: https://localhost:8761/eureka

security:
  require-ssl: true

If anyone has had this same issue, please advise!

A: Based on configuration in the question you are running your Config Server in https, but you should also register it in Eureka to be discovered as https. Otherwise Third service after doing discovery by serviceId will receive http URL from Eureka, so you should force your Config Server to register as https by using:
eureka:
  instance:
    statusPageUrl: https://${eureka.hostname}/info
    healthCheckUrl: https://${eureka.hostname}/health
    homePageUrl: https://${eureka.hostname}/

See: http://cloud.spring.io/spring-cloud-static/spring-cloud.html#_registering_a_secure_application


text:
Q: jquery ajax call fails on facebook <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.min.js"></script>
<script type="text/javascript">
    function postolayi(){
        $.ajax({
            type: 'POST',
            url: 'yorum_gonder.php',
            data: $('#form1').serialize(),
            success: function(cevap){
                $("#sonuc").html(cevap)
            }
        })
    }
</script>
<form id="form1">
    <label for="textfield">Name</label>
    <input id="textfield" type="text" name="ad" />
    <input onclick="postolayi();" type="button" />
</form>

Why this code is not working on facebook apps? Please help

A: Must be over a ssl / https, try change the jquery-link:
http://code.jquery.com/jquery-1.7.min.js to https://code.jquery.com/jquery-1.7.min.js


text:
Q: Python function return problem, it returns None i want to calculate sum of every digit. For example, if we have number 134,we calculate 1+3+4 =8 and print it out. I did this in c, it works fine but when i try it in python it doesn't work. Here is my code: python code

A: the problem in your code is that it has no return statement; by default, Python will return None.
That being said, I would recommend you to add the code to the question in the next questions; just as skrrrt commented :).


text:
Q: Python lista arredondamento a = [1.2,2.3,3.4]
b = [4.1,5.2,6.3]
x = 3.4
y = a.index(x)
print (y)
y1 = b[y]
print (y1)

Como eu faria no código se x fosse 3. sendo que eu queria que fosse mostrado o valor mais próximo. no caso se x = 3, y iria receber a posição 2 ou seja 3.4

A: Vejo que tanto a lista ´a´ como ´b´ estão ordenadas.
Assumindo que todas as listas para o qual pertende testar estejam também ordenadas o que recomendo é fazer uma pesquisa binária por o valor mais proximo.
A minha sugestão é a seguinte:
def binary_search_closest(l, item):
    last = len(l) - 1
    mid = last // 2

    if l[mid] == item:
        return mid

    else:
        if last == 1:  # apenas 2 elementos
            if abs(l[0] - item) < abs(l[1] - item):
                return 0
            else:
                return 1
        elif item < l[mid]:
            return binary_search_closest(l[:mid + 1], item)  # incluir o l[mid] para o caso de arredondamento
        else:
            return mid + binary_search_closest(l[mid:], item)

Caso as listas não se encontrem ordenadas apenas surgiro percorrer a lista toda e ir guardando o indice do mais proximo, assim como a sua diferença em relação ao item.
A minha soluçao:
def find(l, item):
    closest = (0, abs(item - l[0]))  # tuplo com indice do valor mais proximo e a sua diferença em relação ao item
    for i in range(len(l)):
        dif = abs(item - l[i])
        if dif == 0:  # se encontrou o item na lista
            return i
        elif dif < closest[1]:
            closest = (i, dif)

    return closest[0]

Note que neste caso se existirem 2 elementos da lista com a mesma diferença apenas retornará o indice do primeiro que aparecer.
Por exemplo em: a=[1.0, 2.5, 3.5] se pesquisar pelo valor 3 ele irá retornar o indice 1, para o valor 2.5

A: Boa noite!
Tenta fazer desta forma:
* precisa importar a biblioteca numpy
import numpy as np

a = np.array([1.2,2.3,3.4])
b = np.array([4.1,5.2,6.3])

x = 3.0

idx = (np.abs(a-x)).argmin()
print(idx)


text:
Q: On my Pi, chmod +w doesn't behave as usual? $ ls -al file1
-r--r--r-- 1 pi pi 0 Feb 10 15:18 file1

$ chmod +w file1
$ ls -al file1
-rw-r--r-- 1 pi pi 0 Feb 10 15:18 file1  #only u is updated

$ chmod +x file1
$ ls -al file1
-rwxr-xr-x 1 pi pi 0 Feb 10 15:18 file1  #all updated

Is this how chmod +w works?

A: Depends on what your umask is. If your umask is 022, then the +w gets masked in the group and other permissions flags. +x is not masked. To mask any of the executable flags, add 1 to the umask in that position. eg do umask 033 and try your test again.

A: From the man page:
If no value is supplied for who, each permission bit spec-
ified in perm, for which the corresponding bit in the file mode
creation mask (see umask(2)) is clear, is set.  Otherwise, the mode
bits represented by the specified who and perm values are set.

So if you don't specify who you want to update the permissions on it falls back to what the umask says to do with the permission you're setting.  In this case your umask probably allows read and execute on files, so the execute bit gets set for everyone, but the umask probably only allows writing for the owner.

A: This is defined by umask. It sets the default for creating and change of permissions of files.
To see the umask by default in a easy way issue the command umask -S . For example the result:
u=rwx,g=rx,o=rx
means that for user applies all, for group only read and execute, and the same for others.
To change it issue umask on this way:
umask x@y
where:
x could be: u (user), g(group),o (other) or a (all)
@ could be + to add permissions, - to remove permissions
y could be r (read), w(write), x(execute)
For example: umask g+w enable write permissions by default to group when you do a chmod +w.
More information here or issuing man umaskon the command prompt.

A: The umask (by default 0022) is the reason the chmod +w change only the user attribute
$ chmod -v 444 a
mode of 'a' retained as 0444 (r--r--r--)
$ umask 000
$ chmod  -v +w a
mode of 'a' changed from 0444 (r--r--r--) to 0666 (rw-rw-rw-)
$ chmod -v +x a
mode of 'a' changed from 0666 (rw-rw-rw-) to 0777 (rwxrwxrwx)


text:
Q: How can I prove algorithm correctness? I have a problem with this exercise in Java, I don't understand how to prove this sum method in Java
This is what I made :
P(0) : If r=0 and i=0 => r=0+a[0]

p(i+1) : r'= r + a[i] and i'=i+1
       r'=r + a[i] + a[i+1]

public static int sum(int[] a) {
    int r = 0;
    int i = 0;
    while (i < a.length) {
        r = r + a[i];
        i = i + 1;
    }

    return r;
}

A: The loop invariant should express that r equals the sum of the elements of a from index 0 to index i, excluded. I.e. r = Sum(k<i: a[k]).
Then we can annotate
int r = 0;
int i = 0;
/* r = Sum(k<i: a[k]) */
while (i < a.length) {
    r = r + a[i];
    /* r = Sum(k<i: a[k]) + a[i] = Sum(k<i+1: a[k]) */
    i = i + 1;
    /* r = Sum(k<i: a[k]) */
}
/* r = Sum(k<=a.length: a[k]) */

The crux of the proof is
Sum(k<i: a[k]) + a[i] = Sum(k<i+1: a[k])

expressing that the sum is obtained incrementally.

A: The easiest method is to define a set of inputs along with their expected outputs.  If this is for an exercise, you may be given these values, or you may need to calculate a handful of them by hand.  Then I would write unit tests using those known inputs to see if each output matches the expected value.  If you find places where they don't match, double check both your algorithm and the expected values.  Work through the steps of each side-by-side and figure out which one is wrong (or if both are wrong).
Another option is to write the same algorithm in another language; ideally, one where you can't copy-paste the algorithm's implementation to prevent sharing common bugs.  Then run both with a ton of inputs.  If both implementations have matching results for every input, you can have a higher confidence that both are correct.
A third option is to find a set of invariants, i.e. things that are provably true at various stages of the algorithm.  Then write tests (or just throw in assert statements) at all of those points that show that the invariants hold.  Things like for every iteration of the "i" loop, r' >= r.  Then run it against a large range of inputs, and if any of those assertions fail, you can start digging in and figuring out what edge case you forgot to handle in your algorithm (e.g. What if the input is empty?  How do I handle negative numbers?  etc.)