text:
Q: Updating MYSQL from daily CSV file - Skip already imported I am using the following script to copy data from a CSV file that is updated daily into a Mysql Database.
csv_data = csv.reader(open('test.csv'))
next(csv_data, None)
for row in csv_data:
    with connection.cursor() as cursor:
         cursor.execute(("INSERT INTO test(`1` ,`2`,`3` .......) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"), (row[0]........))

The CSV currently has over 40,000 rows and will continue to grow meaning it will take hours to do.
I know I can add a unique identifier onto the database the will stop duplicated and do  INSERT IGNORE to skip over it but is there anything else I can do to speed the process?

A: "INSERT IGNORE "  will resolve your issue.


text:
Q: Identify in QGIS by dragging polygon? In ArcMap it is possible to drag a polygon with the identify tool and thereby get information on multiple features without clicking on them with high precission.
So far I have not been able to find the same functionality in QGIS (checked all versons from 2.12 to 2.18.4).
Do you know a way to identify by dragging a polygon in QGIS?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Suggestion for either a pin or a hooked arrow to label an angle in a `TikZ` diagram The following code renders a circle circumscribing a triangle. One angle is marked $\theta$. I would like the other angle to be marked $90 - \theta$. There is not room it where it belongs. I am looking for suggestions on "pins" or hooked arrows. In either case, the end of the "pin" or hooked arrow should be at the green dot.
\documentclass{amsart}
\usepackage{amsmath}

\usepackage{tikz}
\usetikzlibrary{calc,intersections}

\begin{document}

\begin{tikzpicture}

%The circle circumscribing \triangle{ABC} is drawn. O is the center of the circle.
%\angle{ABO} and \angle{ACB} are complimentary angles.
\coordinate (O) at (0,0);
\draw (O) circle (1.75);
\draw[fill] (O) circle (1.5pt);
%
\path (190:1.75) coordinate (A) (120:1.75) coordinate (B) (70:1.75) coordinate (C);
\draw (A) -- (B) -- (C) -- cycle;
%
\draw[dashed] (O) -- (A);
\draw[dashed] (O) -- (B);
%

%The mark indicating the measure of \angle{ABO} is drawn. It is labeled \theta.
\draw[draw=blue] let \p1=($(A)-(B)$), \n1={atan(\y1/\x1)} in ($(B)!2.5mm!(O)$) arc (-60:{\n1-180}:0.25);
\draw[draw=blue] let \p1=($(A)-(B)$), \n1={atan(\y1/\x1)} in node[anchor={0.5*((\n1-180)-60)+180}, inner sep=0, font=\tiny] at ($(B) +({0.5*((\n1-180)-60)}:0.3)$){$\theta$};

%The mark indicating the measure of \angle{ABO} is drawn. It is labeled \theta.
\draw[draw=blue] let \p1=($(A)-(C)$), \n1={atan(\y1/\x1)}, \p2=($(B)-(C)$), \n2={atan(\y2/\x2)} in ($(C)!3.5mm!(B)$) arc ({\n2-180}:{\n1-180}:0.35);
\draw[fill=green] let \p1=($(A)-(C)$), \n1={atan(\y1/\x1)}, \p2=($(B)-(C)$), \n2={atan(\y2/\x2)} in ($(C) +({0.5*(\n1+\n2)-180}:0.45)$) circle (1pt);

\end{tikzpicture}

\end{document}

A: An option using tkz-euclide
RESULT:

MWE:
\documentclass[border=2mm]{standalone}
\usepackage{xcolor}
\usepackage{amsmath}
\usepackage{tkz-euclide}
\usetikzlibrary{arrows.meta}
\usetkzobj{all}
\begin{document}
    \begin{tikzpicture}
        % Set limits.
        \tkzInit[xmin=-4,xmax=11,ymax=5, ymin=-5]
        \tkzGrid[sub,color=blue!10!,subxstep=.5,subystep=.5]
        \tkzClip
        %Define principal points.
        \tkzDefPoint(0,0){O}
        \tkzDefShiftPoint[O](70:3){A}
        \tkzDefShiftPoint[O](120:3){B}
        \tkzDefShiftPoint[O](190:3){C}

        %Define principal points.
        \tkzDefPoint(7,0){O'}
        \tkzDefShiftPoint[O'](50:3){A'}
        \tkzDefShiftPoint[O'](120:3){B'}
        \tkzDefShiftPoint[O'](190:3){C'}

        %Draw the circle
        \tkzDrawCircle[R,blue](O,3cm)
        \tkzDrawCircle[R,blue](O',3cm)

        % Draw angles
        \tkzMarkAngle[fill=blue!25,mkpos=.2, size=0.5](C,B,O)
        \tkzMarkAngle[fill=green!25,mkpos=.2, size=0.5](B,A,C)

        \tkzMarkAngle[fill=blue!25,mkpos=.2, size=0.5](C',B',O')
        \tkzMarkAngle[fill=green!25,mkpos=.2, size=0.5](B',A',C')

        % Draw all segments.
        \tkzDrawSegments[thick,dashed](O,C O,B)
        \tkzDrawSegments[thick](C,A B,A B,C)

        \tkzDrawSegments[thick,dashed](O',C' O',B')
        \tkzDrawSegments[thick](C',A' B',A' B',C')

        % Draw specific points.
        \tkzDrawPoints[fill=white,size=7pt](A,B,C)
        \tkzDrawPoints[fill=black,size=12pt](O)

%       \tkzDrawPoints[fill=red,size=10pt](A',B',C')
        \tkzDrawPoints[fill=black,size=12pt](O')

        % Label points
        \tkzLabelPoints[color=blue,opacity=.7,above](A,B)
        \tkzLabelPoints[color=blue,opacity=.7,left](C)
        \tkzLabelPoints[color=blue,opacity=.7,below =5pt](O)

        % Label angles.
        \tkzLabelAngle[pos = .7](C,B,O){$\theta$}
        \tkzLabelAngle[pos =-1.2, rotate=25](B,A,C){$90-\theta$}

        \tkzLabelAngle[pos = .8](C',B',O'){$\theta$}
%           \tkzLabelAngle[pos =-1.2, rotate=25](B',A',C'){$\theta-90$}

        \draw[thick, Stealth-] (A')++(190:14.pt) to [in=-90,out=190] ++(-1,1.2) node[anchor=south] {$90-\theta$};
        % You can mark the segments
        \tkzMarkSegments[mark=||,pos=0.6](B,O C,O)
    \end{tikzpicture}
\end{document}

A: Here is a proposal. EDIT: I added your own proposal with some tiny modification (made it compile and added looseness).
\documentclass{amsart}
\usepackage{amsmath}

\usepackage{tikz}
\usetikzlibrary{calc,intersections}

\begin{document}

\begin{tikzpicture}

%The circle circumscribing \triangle{ABC} is drawn. O is the center of the circle.
%\angle{ABO} and \angle{ACB} are complimentary angles.
\coordinate (O) at (0,0);
\draw (O) circle (1.75);
\draw[fill] (O) circle (1.5pt);
%
\path (190:1.75) coordinate (A) (120:1.75) coordinate (B) (70:1.75) coordinate (C);
\draw (A) -- (B) -- (C) -- cycle;
%
\draw[dashed] (O) -- (A);
\draw[dashed] (O) -- (B);
%

%The mark indicating the measure of \angle{ABO} is drawn. It is labeled \theta.
\draw[draw=blue] let \p1=($(A)-(B)$), \n1={atan(\y1/\x1)} in ($(B)!2.5mm!(O)$) arc (-60:{\n1-180}:0.25);
\draw[draw=blue] let \p1=($(A)-(B)$), \n1={atan(\y1/\x1)} in node[anchor={0.5*((\n1-180)-60)+180}, inner sep=0, font=\tiny] at ($(B) +({0.5*((\n1-180)-60)}:0.3)$){$\theta$};

%The mark indicating the measure of \angle{ABO} is drawn. It is labeled \theta.
\draw[draw=blue] let \p1=($(A)-(C)$), \n1={atan(\y1/\x1)}, \p2=($(B)-(C)$), \n2={atan(\y2/\x2)} in ($(C)!3.5mm!(B)$) arc ({\n2-180}:{\n1-180}:0.35);
\draw[fill=green] let \p1=($(A)-(C)$), \n1={atan(\y1/\x1)}, \p2=($(B)-(C)$), \n2={atan(\y2/\x2)} in ($(C) +({0.5*(\n1+\n2)-180}:0.45)$)
coordinate(X) circle (1pt);

\draw[latex-,shorten <=1pt] let \p1=($(A)-(C)$), \n1={atan(\y1/\x1)},
\p2=($(B)-(C)$), \n2={\n1+atan(\y2/\x2)} in (X)
to[out={0.5*\n2-180},in=-90,looseness=2]
++ (-12pt,18pt) node[above]{$90^\circ-\theta$};
\end{tikzpicture}
\end{document}

If you really want a hook, you may want to load the arrows.meta library.
\documentclass{amsart}
\usepackage{amsmath}

\usepackage{tikz}
\usetikzlibrary{calc,intersections,arrows.meta}

\begin{document}

\begin{tikzpicture}

%The circle circumscribing \triangle{ABC} is drawn. O is the center of the circle.
%\angle{ABO} and \angle{ACB} are complimentary angles.
\coordinate (O) at (0,0);
\draw (O) circle (1.75);
\draw[fill] (O) circle (1.5pt);
%
\path (190:1.75) coordinate (A) (120:1.75) coordinate (B) (70:1.75) coordinate (C);
\draw (A) -- (B) -- (C) -- cycle;
%
\draw[dashed] (O) -- (A);
\draw[dashed] (O) -- (B);
%

%The mark indicating the measure of \angle{ABO} is drawn. It is labeled \theta.
\draw[draw=blue] let \p1=($(A)-(B)$), \n1={atan(\y1/\x1)} in ($(B)!2.5mm!(O)$) arc (-60:{\n1-180}:0.25);
\draw[draw=blue] let \p1=($(A)-(B)$), \n1={atan(\y1/\x1)} in node[anchor={0.5*((\n1-180)-60)+180}, inner sep=0, font=\tiny] at ($(B) +({0.5*((\n1-180)-60)}:0.3)$){$\theta$};

%The mark indicating the measure of \angle{ABO} is drawn. It is labeled \theta.
\draw[draw=blue] let \p1=($(A)-(C)$), \n1={atan(\y1/\x1)}, \p2=($(B)-(C)$), \n2={atan(\y2/\x2)} in ($(C)!3.5mm!(B)$) arc ({\n2-180}:{\n1-180}:0.35);
\draw[fill=green] let \p1=($(A)-(C)$), \n1={atan(\y1/\x1)}, \p2=($(B)-(C)$), \n2={atan(\y2/\x2)} in ($(C) +({0.5*(\n1+\n2)-180}:0.45)$)
coordinate(X) circle (1pt);
\draw[{Hooks[]}-,shorten <=1pt] (X) to[out=90,in=-90] ++ (3pt,18pt)
node[above]{$90^\circ-\theta$};

\end{tikzpicture}

\end{document}

And for completeness: there is an arguably simpler way to draw the angle arcs, namely with the angles library.
\documentclass{amsart}
\usepackage{amsmath}

\usepackage{tikz}
\usetikzlibrary{angles,quotes,plotmarks}

\begin{document}

\begin{tikzpicture}

%The circle circumscribing \triangle{ABC} is drawn. O is the center of the circle.
%\angle{ABO} and \angle{ACB} are complimentary angles.
\coordinate (O) at (0,0);
\draw (O) circle (1.75);
\draw[fill] (O) circle (1.5pt);
%
\path (190:1.75) coordinate (A) (120:1.75) coordinate (B) (70:1.75) coordinate (C);
\draw (A) -- (B) -- (C) -- cycle;
%
\draw[dashed] (O) -- (A);
\draw[dashed] (O) -- (B);
%

\path (A) -- (B) -- (O)
pic [angle radius=2.5mm,font=\tiny,draw,
angle eccentricity=2,"$\theta$"] {angle = A--B--O};

\path (B) -- (C) -- (A)
pic [angle radius=2.5mm,draw=black,
angle eccentricity=2,"{\pgfuseplotmark{*}}"
{green,name=X,pin=100:{\tiny$90^\circ-\theta$}}] {angle = B--C--A};

\end{tikzpicture}
\end{document}


text:
Q: Convert Json Array into CSV I would like to convert an array of JSON into a CSV format. I would like the first line of the CSV to be the label of the data.
There is a sample of my array:
objArray = [
    {"idMachine": 195, "LabelStop": "No more piece", "LabelNC": "Default"},
    {"idMachine": 214, "LabelStop": "No more box", "LabelNC": "Default"}
]

And the result I want :
idMachine;LabelStop;LabelNC
195;No more piece;Default
214;No more box;Default

For the moment, my code looks like that :
convertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';

        for (var index in array[i]) {
            if (i == 0) {
                if (line != '') line += ';'

                line += index;

            } else {
                if (line != '') line += ';'

                line += array[i][index];
            }
        }
        str += line + '\r\n';
    }
    return str;
}

The problem is that the first line is the data labels but the first values are skipped. My CSV looks like that :
idMachine;LabelStop;LabelNC
214;No more box;Default

A: Try this.
let objArray = [
    { "idMachine": 195, "LabelStop": "No more piece", "LabelNC": "Default" },
    { "idMachine": 214, "LabelStop": "No more box", "LabelNC": "Default" }
]

const header = Object.keys(objArray[0])
let csv = objArray.map(row => header.map(fieldName => JSON.stringify(row[fieldName])).join(';'))
csv.unshift(header.join(','))
csv = csv.join('\r\n')

console.log(csv);

A: You are currently looping over the items in your array, and then the individual properties of each item - so you won't be able to do it this exact way with line +=, because the data is not coming in the correct order for that.
Easiest if you just use an additional helper variable for the header line, and then prepend that to the rest of the output at the very end. The else simply gets removed, and the code you had in there executed in any case, not just when i!=0 (so that you get the data from the first item as well, your if/else construct is what made that get "skipped" in the first place.)
function convertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '', header = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';

        for (var index in array[i]) {
            if (i == 0) {
                if (header != '') {
                   header += ';'
                }
                header += index;
            }
            if (line != '') {
              line += ';'
            }
            line += array[i][index];
        }
        str += line + '\r\n';
    }
    return (header + '\r\n' + str);
}


text:
Q: How to convert the 'http:////someurl/' into http://someurl/' in Internet Explorer only-js I'm trying to load certain files for my application using the require.js. everything works fine in chrome and FF, but when i checked the Network tab in IE, it shows status as "Aborted" for some files, reason is the incorrect path.
Ex:
  http:////someurl/index/main.js
  http:////someurl/index/index2.js
  http:////someurl/index/test.js

IE is not able to convert the 4 slash after the 'http' automatically into 2, like the chrome and FF and hence results into "aborted" or file not found.
here is my main.js base url:
require.config({
baseUrl: "http://" + context, // where context = "//someurl/index/"
path: {
    path1: /someurl/index/path1,
    path2: /someurl/index/path2,
    path3: /someurl/index/path3,
 }
});

How to convert the http:////someurl/index/main.js into http://someurl/index/main.js in IE so that it renders the correct path. I also tried taking this url and pasting it in the browser and it works fine. Only on page load the IE fails to identify these files and throws errors.
Any ideas how to solve this issue??
Thanks!!

A: From your code:
 baseUrl: "http://" + context, // where context = "//someurl/index/"

This isn't an IE problem, it's that your URL is invalid with four slashes in it. Okay, so maybe Chrome and Firefox manage to cope with it and work out what you mean... that doesn't mean it's right, and it doesn't mean you should be doing anything special for IE to fix it.
The answer is obvious really. You just need to have fewer slashes.
You say that context starts with //, so why not just drop the // from the http:// part. Problem solved; valid URL. Should work in all browsers.
I guess it's possible that context might not always start with a //, in which case maybe you're adding the // on http: as well just in case. If that's what's happening here, then the solution is to check when building the string so you can decide whether to add the // or not.


text:
Q: inlineformset_factory minimal required Using inlineformset_factory I am able to add / remove phone numbers related to a single customer. Only problem is, I want to require at least 1 valid phone number for each customer.
Here is some demo code:
Models:
class Customer( models.Model ):
    name = models.CharField( max_length=255 )

class PhoneNumber( models.Model ):
    customer = models.ForeignKey( Customer )
    number = models.CharField( max_length=10 )

Forms:
class CustomerForm( ModelForm ):
    class Meta:
        model = Customer
        fields = ['name']

class PhoneNumberForm( ModelForm ):
    class Meta:
        model = PhoneNumber
        fields = ['number']

Ok, so that's pretty straight forward.
Then in my view:
class Create( View ):
    template_name = 'path_to_template'
    CustomerForm = forms.CustomerForm
    PhoneNumberFormSet = inlineformset_factory (
        parent_model = Customer,
        model = PhoneNumber,
        form = PhoneNumberForm,
        extra = 1,
    )

    def get(self, request):
        # Return empty forms
        context = {
            'customer_form': self.CustomerForm,
            'phone_number_formset': self.PhoneNumberFormSet
        }
        render( request, self.template_name, context)

    def post(self, request):
        this_customer_form = self.CustomerForm( request.POST )

        if this_customer_form.is_valid():
            new_customer.save(commit=False)
            this_phone_number_formset = self.PhoneNumberFormSet(request.POST, instance=new_customer)

            if this_phone_number_formset.is_valid():
                new_customer.save()
                this_phone_number_formset.save()
                return HttpResponseRedirect(reverse_lazy('customer-detail', kwargs={'pk': new_customer.pk}))

        # Something is not right, show the forms again
        this_phone_number_formset = self.PhoneNumberFormSet(request.POST)
        context = {
            'customer_form': this_customer_form,
            'phone_number_formset': this_phone_number_formset
        }
        render( request, self.template_name, context)

You get the point I think. Same thing for the Edit/Update view of the customer. Only then the forms are prepopulated.
At this point all I need is a way to require at least 1 valid PhoneNumber per Customer.
I found something like:
class RequiredFormSet(BaseFormSet):
    def __init__(self, *args, **kwargs):
        super(RequiredFormSet, self).__init__(*args, **kwargs)
        for form in self.forms:
            form.empty_permitted = False

from https://stackoverflow.com/questions/2406537/django-formsets-make-first-required
but it doesnt seem to work when I apply this on a BaseInlineFormSet class.
Django 1.7 seems to answer my wishes, but not for a InlineModelFormSet so far..
Any ideas?

A: If you just want to set the minimum or maximum, you can set them directly in inlineformset_factory, here's my code for minimum of one entry
from django.forms import inlineformset_factory

SubUnitFormSet = inlineformset_factory(
    Unit, SubUnit, form=SubUnitForm, min_num=1, validate_min=True, extra=0)

You need to properly handle this in your view. I'm using CBV and this is my code for your reference
class UnitCreateView(PermissionRequiredMixin, SuccessMessageMixin, CreateView):
    permission_required = "core.add_unit"

    model = Unit
    form_class = UnitForm
    template_name = 'core/basic-info/unit_form.html'
    success_url = reverse_lazy('core:units')
    success_message = _("%(code)s was added successfully")

    def get_context_data(self, **kwargs):
        data = super(UnitCreateView, self).get_context_data(**kwargs)
        if self.request.POST:
            data['subunits'] = SubUnitFormSet(self.request.POST, )
        else:
            data['subunits'] = SubUnitFormSet()
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        subunits = context['subunits']
        with transaction.atomic():
            if subunits.is_valid():
                self.object = form.save()
                subunits.instance = self.object
                subunits.save()
            else:
                return self.render_to_response(self.get_context_data(form=form))
        return super(UnitCreateView, self).form_valid(form)

A: Thank you kezabella ( django irc ).
Seems I found a solution by subclassing BaseInlineFormset:
class RequiredFormSet(BaseInlineFormSet):
    def clean(self):
        for form in self.initial_forms:
            if not form.is_valid() or not (self.can_delete and form.cleaned_data.get('DELETE')):
                return
        for form in self.extra_forms:
            if form.has_changed():
                return
        raise ValidationError("No initial or changed extra forms")

Btw, these validation errors do not show up in {{ formset.error }} but in:
{{ formset.non_form_errors }}


text:
Q: Handling OnItemTouch For a Navigation Drawer I'm trying to add OnItemTouch in this tutorial:
http://www.android4devs.com/2015/01/recycler-view-handling-onitemtouch-for.html
final code:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private static final int TYPE_HEADER = 0;  // Declaring Variable to Understand which View is being worked on
    // IF the viaew under inflation and population is header or Item
    private static final int TYPE_ITEM = 1;

    private String mNavTitles[]; // String Array to store the passed titles Value from MainActivity.java
    private int mIcons[];       // Int Array to store the passed icons resource value from MainActivity.java

    private String name;        //String Resource for header View Name
    private int profile;        //int Resource for header view profile picture
    private String email;       //String Resource for header view email
    Context context;

    // Creating a ViewHolder which extends the RecyclerView View Holder
    // ViewHolder are used to to store the inflated views in order to recycle them

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        int Holderid;

        TextView textView;
        ImageView imageView;
        ImageView profile;
        TextView Name;
        Context contxt;

        public ViewHolder(View itemView,int ViewType,Context c) {                 // Creating ViewHolder Constructor with View and viewType As a parameter
            super(itemView);
            contxt = c;
            itemView.setClickable(true);
            itemView.setOnClickListener(this);
            // Here we set the appropriate view in accordance with the the view type as passed when the holder object is created

            if(ViewType == TYPE_ITEM) {
                textView = (TextView) itemView.findViewById(R.id.rowText); // Creating TextView object with the id of textView from item_row.xml
                imageView = (ImageView) itemView.findViewById(R.id.rowIcon);// Creating ImageView object with the id of ImageView from item_row.xml
                Holderid = 1;                                               // setting holder id as 1 as the object being populated are of type item row
            }
            else{

                Name = (TextView) itemView.findViewById(R.id.name);         // Creating Text View object from header.xml for name
                       // Creating Text View object from header.xml for email
                profile = (ImageView) itemView.findViewById(R.id.circleView);// Creating Image view object from header.xml for profile pic
                Holderid = 0;                                                // Setting holder id = 0 as the object being populated are of type header view
            }
        }

        @Override
        public void onClick(View v) {

            Toast.makeText(contxt,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();

        }
    }

    MyAdapter(String Titles[], int Icons[], String Name, int Profile, Context passedContext){ // MyAdapter Constructor with titles and icons parameter
        // titles, icons, name, email, profile pic are passed from the main activity as we
        mNavTitles = Titles;                //have seen earlier
        mIcons = Icons;
        name = Name;
        profile = Profile;                     //here we assign those passed values to the values we declared here
        this.context = passedContext;

        //in adapter
    }

    //Below first we ovverride the method onCreateViewHolder which is called when the ViewHolder is
    //Created, In this method we inflate the item_row.xml layout if the viewType is Type_ITEM or else we inflate header.xml
    // if the viewType is TYPE_HEADER
    // and pass it to the view holder

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

        if (viewType == TYPE_ITEM) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row,parent,false); //Inflating the layout

            ViewHolder vhItem = new ViewHolder(v,viewType,context); //Creating ViewHolder and passing the object of type view

            return vhItem; // Returning the created object

            //inflate your layout and pass it to view holder

        } else if (viewType == TYPE_HEADER) {

            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header,parent,false); //Inflating the layout

            ViewHolder vhHeader = new ViewHolder(v,viewType,context); //Creating ViewHolder and passing the object of type view

            return vhHeader; //returning the object created

        }
        return null;

    }

    //Next we override a method which is called when the item in a row is needed to be displayed, here the int position
    // Tells us item at which position is being constructed to be displayed and the holder id of the holder object tell us
    // which view type is being created 1 for item row
    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
        if(holder.Holderid ==1) {                              // as the list view is going to be called after the header view so we decrement the
            // position by 1 and pass it to the holder while setting the text and image
            holder.textView.setText(mNavTitles[position - 1]); // Setting the Text with the array of our Titles
            holder.imageView.setImageResource(mIcons[position -1]);// Settimg the image with array of our icons
        }
        else{

            holder.profile.setImageResource(profile);           // Similarly we set the resources for header view
            holder.Name.setText(name);

        }
    }

    // This method returns the number of items present in the list
    @Override
    public int getItemCount() {
        return mNavTitles.length+1; // the number of items in the list will be +1 the titles including the header view.
    }

    // Witht the following method we check what type of view is being passed
    @Override
    public int getItemViewType(int position) {
        if (isPositionHeader(position))
            return TYPE_HEADER;

        return TYPE_ITEM;
    }

    private boolean isPositionHeader(int position) {
        return position == 0;
    }

}

but there is a problem with this code. I need, when user clicked on Items(in drawer), user to go to another activity. And here is my method:
Button b = (Button) findViewById(R.id.button1);
                b.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(MainActivity.this, Activity2.class));
                    }
                });

I can do this with Switch for each item.
But, how to achieve this?
(where can I put this method on My Adaptor?)

A: This behavior would happen in your MyAdapter.ViewHolder class. Make the ViewHolder implement View.OnClickListener and then you can add on click behavior for the entire item. It looks like in your code you already have this method defined, so you just have to add your startActivity line inside the onClick method.


text:
Q: Problem with updating running_mean and running_var in a custom Batchnorm built in Pytorch? I have been trying to implement a custom batch normalization function such that it can be extended to the Multi GPU version, in particular, the DataParallel module in Pytorch.The custom batchnorm works alright when using 1 GPU, but, when extended to 2 or more, the running mean and variance work in the forward function, but when it returns back from the network, the mean and variance are reinitialized to 0 and 1.
The torch.nn.DataParallel mentions in the warning section that " In each forward, module is replicated on each device, so any updates to the running module in forward will be lost. For example, if module has a counter attribute that is incremented in each forward, it will always stay at the initial value because the update is done on the replicas which are destroyed after forward." But I am not really sure how to retain the mean and variance from the default device.
I have provided code with the result obtained during multi GPU training. This code utilizes the Batchnorm provided here.
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
from torch.nn.parameter import Parameter

class ptrblck_BatchNorm2d(nn.BatchNorm2d):
    def __init__(self, num_features, eps=1e-5, momentum=0.1,
                 affine=True, track_running_stats=True):
        super(ptrblck_BatchNorm2d, self).__init__(
            num_features, eps, momentum, affine, track_running_stats)

    def forward(self, input):
        self._check_input_dim(input)

        exponential_average_factor = 0.0

        if self.training and self.track_running_stats:
            if self.num_batches_tracked is not None:
                self.num_batches_tracked += 1
                if self.momentum is None:  # use cumulative moving average
                    exponential_average_factor = 1.0 / float(self.num_batches_tracked)
                else:  # use exponential moving average
                    exponential_average_factor = self.momentum

        # calculate running estimates
        if self.training:
            mean = input.mean([0, 2, 3])
            # use biased var in train
            var = input.var([0, 2, 3], unbiased=False)
            n = input.numel() / input.size(1)
            with torch.no_grad():
                self.running_mean = exponential_average_factor * mean\
                    + (1 - exponential_average_factor) * self.running_mean
                # update running_var with unbiased var
                self.running_var = exponential_average_factor * var * n / (n - 1)\
                    + (1 - exponential_average_factor) * self.running_var
        else:
            mean = self.running_mean
            var = self.running_var

        input = (input - mean[None, :, None, None]) / (torch.sqrt(var[None, :, None, None] + self.eps))
        if self.affine:
            input = input * self.weight[None, :, None, None] + self.bias[None, :, None, None]

        return input

class net(nn.Module):
    def __init__(self):
        super(net, self).__init__()
        self.conv1 = nn.Conv2d(3, 64, kernel_size=3, padding=1)
        self.bn1 = ptrblck_BatchNorm2d(64)
        print("==> printing bn1 mean when init")
        print(self.bn1.running_mean)
        print("==> printing bn1 when init")
        print(self.bn1.running_mean)
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
        self.classifier = nn.Linear(64, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = F.relu(x)
        x = self.pool(x)
        x = self.avgpool(x)

        x = x.view(x.size(0), -1)
        x = self.classifier(x)
        print("======================================================")
        print("==> printing bn1 running mean from NET during forward")
        print(net.module.bn1.running_mean)
        print("==> printing bn1 running mean from SELF. during forward")
        print(self.bn1.running_mean)
        print("==> printing bn1 running var from NET during forward")
        print(net.module.bn1.running_var)
        print("==> printing bn1 running mean from SELF. during forward")
        print(self.bn1.running_var)
        return x

# Data
print('==> Preparing data..')
transform_train = transforms.Compose([
    transforms.RandomCrop(32, padding=4),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
    transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))])

transform_test = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))])

trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

# Model
print('==> Building model..')
net = net()
net = torch.nn.DataParallel(net).cuda()
print('Number of GPU {}'.format(torch.cuda.device_count()))

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4)

# Training
def train(epoch):
    print('\nEpoch: %d' % epoch)
    net.train()
    train_loss = 0
    correct = 0
    total = 0

    for batch_idx, (inputs, targets) in enumerate(trainloader):
        inputs, targets = inputs.cuda(), targets.cuda()
        outputs = net(inputs)
        loss = criterion(outputs, targets)
        print("====================================================")
        print("==> printing bn1 running mean FROM net after forward")
        print(net.module.bn1.running_mean)
        print("==> printing bn1 running var FROM net after forward")
        print(net.module.bn1.running_var)

        break
        # optimizer.zero_grad()
        # loss.backward()
        # optimizer.step()

        # train_loss += loss.item()
        # _, predicted = outputs.max(1)
        # total += targets.size(0)
        # correct += predicted.eq(targets).sum().item()

        # break

for epoch in range(0, 1):
    train(epoch)

Result:
==> Preparing data..
Files already downloaded and verified
Files already downloaded and verified
==> Building model..
==> printing bn1 mean when init
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
==> printing bn1 when init
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
Number of GPU 2

Epoch: 0
======================================================
==> printing bn1 running mean from NET during forward
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       device='cuda:0')
==> printing bn1 running mean from SELF. during forward
tensor([ 0.0053,  0.0010, -0.0077, -0.0290,  0.0241,  0.0258, -0.0048,  0.0151,
        -0.0133,  0.0080,  0.0197, -0.0042, -0.0188,  0.0233,  0.0310, -0.0230,
        -0.0133,  0.0222,  0.0119, -0.0042, -0.0220, -0.0169, -0.0342, -0.0025,
         0.0338, -0.0070,  0.0202,  0.0050,  0.0108,  0.0008,  0.0363,  0.0347,
        -0.0106,  0.0082,  0.0128,  0.0074,  0.0111, -0.0030, -0.0089,  0.0070,
        -0.0262, -0.0029,  0.0053, -0.0136, -0.0183,  0.0045, -0.0014, -0.0221,
         0.0132,  0.0064,  0.0388, -0.0220, -0.0008,  0.0400, -0.0187,  0.0397,
        -0.0131, -0.0176,  0.0035,  0.0055, -0.0270,  0.0066, -0.0149,  0.0135],
       device='cuda:0')
==> printing bn1 running var from NET during forward
tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], device='cuda:0')
==> printing bn1 running mean from SELF. during forward
tensor([0.9665, 0.9073, 0.9220, 1.0947, 1.0687, 0.9624, 0.9252, 0.9131, 0.9066,
        0.9536, 0.9258, 0.9203, 1.0359, 0.9690, 1.1066, 1.0636, 0.9135, 0.9644,
        0.9373, 0.9846, 0.9696, 0.9454, 1.0459, 0.9245, 0.9778, 0.9709, 0.9352,
        0.9995, 0.9657, 0.9510, 1.0943, 1.0171, 0.9298, 1.0747, 0.9341, 0.9635,
        0.9978, 0.9303, 0.9261, 0.9137, 0.9569, 1.0066, 1.0463, 0.9955, 0.9621,
        0.9172, 0.9836, 0.9817, 0.9086, 0.9576, 1.0905, 0.9861, 0.9661, 1.1773,
        0.9345, 1.0904, 0.9133, 1.0660, 0.9164, 0.9058, 0.9446, 0.9225, 1.0914,
        0.9292], device='cuda:0')
======================================================
==> printing bn1 running mean from NET during forward
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       device='cuda:0')
==> printing bn1 running mean from SELF. during forward
tensor([-0.0020,  0.0002, -0.0103, -0.0426,  0.0386,  0.0311, -0.0059,  0.0151,
        -0.0140,  0.0145,  0.0218, -0.0029, -0.0281,  0.0284,  0.0449, -0.0329,
        -0.0107,  0.0278,  0.0135, -0.0123, -0.0260, -0.0214, -0.0423, -0.0035,
         0.0410, -0.0097,  0.0276,  0.0102,  0.0197, -0.0001,  0.0483,  0.0451,
        -0.0078,  0.0190,  0.0135, -0.0004,  0.0196, -0.0028, -0.0140,  0.0070,
        -0.0332, -0.0110,  0.0151, -0.0210, -0.0226,  0.0074, -0.0088, -0.0314,
         0.0125, -0.0003,  0.0505, -0.0312,  0.0086,  0.0544, -0.0245,  0.0528,
        -0.0086, -0.0290,  0.0063,  0.0042, -0.0339,  0.0061, -0.0277,  0.0092],
       device='cuda:1')
==> printing bn1 running var from NET during forward
tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], device='cuda:0')
==> printing bn1 running mean from SELF. during forward
tensor([0.9665, 0.9072, 0.9211, 1.0999, 1.0714, 0.9610, 0.9209, 0.9125, 0.9063,
        0.9553, 0.9260, 0.9189, 1.0386, 0.9706, 1.1139, 1.0610, 0.9121, 0.9660,
        0.9366, 0.9886, 0.9683, 0.9454, 1.0511, 0.9227, 0.9792, 0.9704, 0.9330,
        0.9989, 0.9657, 0.9476, 1.1008, 1.0191, 0.9294, 1.0814, 0.9320, 0.9642,
        1.0006, 0.9287, 0.9254, 0.9128, 0.9559, 1.0100, 1.0521, 0.9972, 0.9621,
        0.9168, 0.9849, 0.9803, 0.9083, 0.9556, 1.0946, 0.9865, 0.9651, 1.1880,
        0.9330, 1.0959, 0.9116, 1.0706, 0.9149, 0.9057, 0.9450, 0.9215, 1.0972,
        0.9261], device='cuda:1')
====================================================
==> printing bn1 running mean FROM net after forward
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       device='cuda:0')
==> printing bn1 running var FROM net after forward
tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], device='cuda:0')

How can I make sure that the running estimates of the default device be used? Currently, I am not working towards synchronized Batchnorm.

A: Replacing
self.running_mean = (...)
with
self.running_mean.copy_(...)
did the job.
Reference


text:
Q: Set asp:CustomValidator text from codebehind I have User ID and Password fields, both of which work well with the RequiredFieldValidator. Just below that, I have placed a CustomValidator, and I'm attempting to have a similar validation from the codebehind when the passwords don't match.
<asp:RequiredFieldValidator runat="server" ID="PWRequired"
    ControlToValidate="PasswordTextbox"
    Display="None"
    ErrorMessage="Required Field Missing
A password is required." />
<asp:CustomValidator runat="server" ID="PWMatch"
    ControlToValidate="PasswordTextbox"
    Display="None"
    ErrorMessage="Password is Invalid
Please enter a valid password." />
<AjaxControl:ValidatorCalloutExtender
    runat="Server"
    ID="PWValidationExtender"
    TargetControlID="PWRequired"
    Width="185px"
    WarningIconImageUrl="/Images/warning.gif" />
<asp:TextBox ID="PasswordTextbox" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox>

(Hopefully that formatted correctly. I've never gotten the "4 space" thing to work.
Then in the codebehind, when the PWs don't match, I'm trying this:
CustomValidator myValidator = (CustomValidator)this.FindControl("PWMatch");
myValidator.Text = "Password is Invalid
Please enter a valid password.";
ValidatorCalloutExtender myValExtender = (ValidatorCalloutExtender)this.FindControl("PWValidationExtender");
myValExtender.ID = "PWValidationExtender";
myValExtender.TargetControlID="PWMatch";
myValExtender.WarningIconImageUrl = "/Images/warning.gif";
myValExtender.Width = new Unit(250);

I hope it is something simple and silly that I'm missing. I've burned a whole day trying to figure this out.
Thanks in advance for your help.
=========================================================================
Thanks freefaller.  I've tried that and get "no joy."  So, I'm coming at it from a little different direction.
I've changed to a CompareValidator, like this: (again, hope the markup works)
<asp:CompareValidator runat="server" ID="PWCompareValidator"
    ControlToValidate="PasswordTextbox"
    Operator="Equal"
    ValueToCompare="<%# GetPassword() %>"
    Text="Password is Invalid
Please enter a valid password."
    Type="String" />

It's giving me a message, but always evaluating to "false" because the GetPassword method is not being called.  If I keep hammering at this, I think I can get it to work, but if you see a quick solution, I'm all ears.  Thanks again!!

A: Instead of .Text use .ErrorMessage
So change...
myValidator.Text = "Password is Invalid
Please enter a valid password.";

To...
myValidator.ErrorMessage = "Password is Invalid
Please enter a valid password.";

Update (due to update in question)
The CompareValidator is designed to compare two values on the actual website... the ValueToCompare is supposed to be a static value, and by placing the password into it, you are opening up a security hole (because you'll be potentially sending the password to the browser - although I have doubts that ValueToCompare="<%# GetPassword() %>" will actually work in the first place.)
The CustomValidator requires you to provide at least one handler... definitely one on the server (using the OnServerValidate attribute), and if necessary one on the browser (using the ClientValidationFunction attribute).  It is within the handlers that you must set the IsValid attribute of the args parameter according the result of your checks.
(I say "definitely one on the server" because client-side script is easy to get around, so you always want to have something on the server to catch anybody trying.)
It isn't 100% clear exactly what you're trying to do, or indeed exactly what you've currently got in place, so it's difficult to give you any direct advice other than what I have above.

Final Update
As you are trying to check a password, here is an example of what I think you need...
Password: <asp:TextBox runat="server" id="txtPassword"/>
<asp:RequiredFieldValidator runat="server" id="reqPassword"
   ControlToValidate="txtPassword" ErrorMessage="Provide Password" />
<asp:CustomValidator runat="server" id="cusPassword"
   ControlToValidator="txtPassword" ErrorMessage="Incorrect Password"
   OnServerValidate="cusPassword_ServerValidate"/>

Then in your code-behind, you need to have the handler
protected void cusPassword_ServerValidate(object sender, ServerValidateEventArgs args)
{
  args.IsValid = (txtPassword.Text == GetPassword());
}


text:
Q: Google play throws a message (see below) when I try to upload signed app release .apk file I am trying to upload an app to Google play from the Google play developer console, and it throws the following message when I try to upload an apk file: "You need to use a different package name because "com.example" is restricted." The package that my app's classes belong to is called com.example.myname.converter. What is the best way to fix the problem without messing things up?

A: In Android studio build gradle  file change the package name.
The defaultConfig  like this
applicationId "com.example.android.applicationname"

change that com.example package name
applicationId "com.yourcustomname.yourcustomname.applicationname"

then clean and rebuild project

A: You need to specify a valid appId. An appId like com.example is, for sure, not the correct one.
For instance, if you app is from Facebook an app id like com.facebook.app is the correct choice.
Se more information about the appId here.
For updating your app id, just go to your app build.gradle and change the field applicationId.


text:
Q: Why wont MySQL query use index? I have tried several different ways but I can not figure out why my query would not be using the index.
EXPLAIN SELECT
    allocationdate,
    SUM(linepersonal) as recpts
FROM
    c1.recpt #force index (rbadateptype) #force index (rbADate)
WHERE
    allocationdate BETWEEN 20120101 AND 20140630
        AND ptype = 3
GROUP BY YEAR(allocationdate);

Without forcing indexes:
+----+-------------+--------+------+----------------------+------+---------+------+----------+----------------------------------------------+
| id | select_type | table  | type | possible_keys        | key  | key_len | ref  | rows     | extra                                        |
+----+-------------+--------+------+----------------------+------+---------+------+----------+----------------------------------------------+
| 1  | SIMPLE      | recptb | ALL  | rbADate,rbADatePtype | NULL | NULL    | NULL | 23186904 | Using where; Using temporary; Using filesort |
+----+-------------+--------+------+----------------------+------+---------+------+----------+----------------------------------------------+

Forcing rbadateptype:
+----+-------------+--------+------+----------------------+----------------+---------+------+----------+----------------------------------------------+
| id | select_type | table  | type | possible_keys        | key            | key_len | ref  | rows     | extra                                        |
+----+-------------+--------+------+----------------------+----------------+---------+------+----------+----------------------------------------------+
| 1  | SIMPLE      | recptb | ALL  | rbADate,rbADatePtype | rbAdatePtype | 9       | NULL | 8199594| Using where; Using temporary; Using filesort |
+----+-------------+--------+------+----------------------+----------------+---------+------+----------+----------------------------------------------+

`allocationDate` date DEFAULT NULL,
`pType` int(10) DEFAULT NULL,
KEY `rbADate` (`allocationDate`),
KEY `rbAdatePtype` (`allocationDate`,`patType`),

One of the interesting things things that I cannot explain is how the index on just the date says that it needs to look through 7,784,810 records but a composite index on the date and ptype needs to look at 8,199,594.
An even more interesting thing that I just noticed is that using the rbAdate index it says that it needs to look through 23,186,904 records when a select count(1) returns 21,610,791.


text:
Q: Vaadin @JavaScript for different builds I use Vaadin @JavaScript annotation to load JavaScript files for my application. It works great but I would need different JavaScript loaded for differents builds.
The idea is to have something like these:
@JavaScript("url.from.properties.or.pom")

So for DEV I would get @JavaScript("https://example.com/test/js/embed.js") and for PROD @JavaScript("https://example.com/production/js/embed.js"). The script url value should be taken from application.properties or pom.xml.
I cannot figure out how to do it. I use Vaadin 8 with Maven and Spring Boot. Thank you in advance.

A: There's no direct support for what you want to do, but I can come up with three different solutions that you could consider.

*

*Register a DependencyFilter that dynamically rewrites the dependency URL from the annotation depending on the situation.

*Create separate Java classes for each case (with all the actual functionality in a shared super class). You can then have either runtime logic or use e.g. different Spring configurations to choose exactly which class to use.

*Remove the @JavaScript annotation and instead call JavaScript.eval from onAttach to somehow dynamically inject the script you want.


text:
Q: How to statically link boost_filesystem using command line Hi a am learning boostfilesystem.I have a testcode and i have build it using command -
g++ -std=c++11 -I//Boost_Test/boost_1_63_0/installation/include  -L/Boost_Test/boost_1_63_0/installation/lib/ test.cpp -Bstatic  -lboost_filesystem -lboost_system
But when i run it using command
./a.out
i get the error as -  dyld: Library not loaded: libboost_filesystem.dylib
  Referenced from: /Users/Abc/Obj/./a.out
  Reason: image not found
But when i run it like -
DYLD_LIBRARY_PATH=/Boost_Test/boost_1_63_0/installation/lib ./a.out
it is working.
My Question is if i have linked it statically using -Bstatic option why it is not linked statically.Why i have to give shared library path to run it.


text:
Q: How to get the sub UL length

        Healthy Measures

What We Do

Our Team

Contact Us

        Healthy Measures

What We Do

Our Team

Contact Us

        Healthy Measures

What We Do

Our Team

Contact Us

        Healthy Measures

What We Do

Our Team

Contact Us

I would like to know the size of the inner UL inside the parent LI.
I am using the following code:
var vFirst = "3";
vULSubSize = $("#uSPStyle li:not(li li):eq(" + vFirst + ")").find("a").closest("li").children("ul").length; //{DONE}get the size of the sub UL inside the above LI
alert(vULSubSize); // keep displaying 1 [2 items] and not 2 [3 items]

How can I resolve the issue?

A: If you want to get the number of li descendants based on the fourth li child element, then you could use the direct child combinator, > in order to select direct children li elements:
$('#uSPStyle > li:eq(' + vFirst + ') ul li').length;

A: $('#uSPStyle li').eq(vFirst).find('li').length;

Demo
This would get the length of the list items inside the top-level list item having the index from your URL parameter. I prefer the eq() method for simpler syntax.

A: var vFirst = "3";
console.log( $('#uSPStyle > li:eq(' + vFirst + ') ul li').length )

jsFiddle example


text:
Q: How can I annotate the number as type in parametric type Im newbie to julia.
I was curious about value type in julia so I test them few.
using StaticArrays
struct MT{N,Np1}
    x::SVector{N,Int}
    y::SVector{Np1,Int}
    function MT(x::SVector{T,Int},y::SVector{V,Int}) where {T, V}
        Val{T}() == Val{V}() || throw(ArgumentError("mismatched lengths; y must be one element longer than x"))
        new{T, V}(x,y)
    end
end

MT(SVector{3,Int}(1,2,3),SVector{3,Int}(1,2,3))

My question is this:

*

*Can I annotate type of T and V in where clause?
(Like "where {T=Int, V=Int}" or something?)

*Can we restrict the type of T as Integer by using type annotation?
(Allow MT{1,1} but not MT{1.0, 1.0})

I want working code with type annotation.

A: The answer to your question about restricting the type of parameters T and V is that you cannot do that for non-type/value parameters. It would be nice, but you can't.
Only subtype relationships can be enforced on type paramaters, and value-parameters cannot be in a subtype relationship:
julia> 3 isa Integer  # this is a valid relationship
true

julia> 3 <: Integer  # this is not
ERROR: TypeError: in <:, expected Type, got a value of type Int64

A hypothetical syntax could instead be where {T::Int, V::Int}, or where {T isa Int, V isa Int}. I don't know why this is not possible, but it is a well-known limitation.
BTW: You can just write T == V. No need for Val{T}() == Val{V}(). The computation happens at compile time, since both are type parameters.

A: struct MT{N,Np1}
    x::SVector{N,Int}
    y::SVector{Np1,Int}
    function MT(x::SVector{T,Int},y::SVector{V,Int}) where T <: Integer where V <: Int
        Val{T}() == Val{V}() || throw(ArgumentError("mismatched lengths; y must be one element longer than x"))
        new{T, V}(x,y)
    end
end

does what you ask (it just replaces where {T, V} in your code with where T <: Integer where V <: Int. See the documentation for where for more.
There are some questions I considered about your question. A SVector{S, T} can have the type of T vary in type, but S is a count of elements and must be an Int as far as I know. So the SVector package should enforce the type of S for you. So the where would usually be used to vary the second type in the SVector, which you always set to Int here.


text:
Q: Using VARCHAR(Max) (That is really a string []) in an Inner Join using IN What I am trying to do is connect two tables.
Table 1 will have this setup
CREATE TABLE Table1
(
   PkId INT Identity(1,1) NOT NULL,
   ListOfProducts VARCHAR(MAX) NULL,
   ProductWareHouse VARCHAR(Max) NULL,
   CONSTRAINT PkId PRIMARY KEY (PkId)
)

Table 2 is set up like so
CREATE TABLE Table2
(
   PkId INT Identity(1,1) NOT NULL,
   Product VARCHAR(MAX) NULL,
   ProductCost DECIMAL(38,2) NOT NULL,
   CONSTRAINT PkId PRIMARY KEY (PkId)
)

Table 1's ListOfProducts is really a string[] and Table 2's Product links to Table 1's ListOfProducts.
What I really want to accomplish is an inner join of the two tables that would look in the ListOfProducts to actually accomplish the inner join so something like this
SELECT *
FROM TABLE1
INNER JOIN TABLE 2 ON Product IN(ListOfProducts)
WHERE ProductWareHouse = 'Warehouse1'

ListOfProducts values would look something like this: [Oranges, Apples].

A: Method 1:
JOIN ... ON ListOfProducts like '%' + Product + '%'

Method 2:
Get rid of the left and right bracket first, then:
JOIN ... ON Product in (select value from string_split(ListOfProducts,', '))

Both are terribly inefficient.


text:
Q: Add Google sheet with data using Google API v4 I am using Python. I need to add sheet in spreadsheets using Google API v4. I can create a sheet using batchUpdate with spreadsheet id and addSheet request (it returns shetId and creates empty sheet). But how can I add data in it?
data = {'requests': [
    {
        'addSheet':{
            'properties':{'title': 'New sheet'}
        }
    }
]}

res = service.spreadsheets().batchUpdate(spreadsheetId=s_id, body=data).execute()
SHEET_ID = res['replies'][0]['addSheet']['properties']['sheetId']

A: You can add this code to write data in Google Sheet. In the document - Reading & Writing Cell Values

Spreadsheets can have multiple sheets, with each sheet having any number of rows or columns. A cell is a location at the intersection of a particular row and column, and may contain a data value. The Google Sheets API provides the spreadsheets.values collection to enable the simple reading and writing of values.

Writing to a single range

To write data to a single range, use a spreadsheets.values.update request:

values = [
    [
        # Cell values ...
    ],
    # Additional rows ...
]
body = {
  'values': values
}
result = service.spreadsheets().values().update(
    spreadsheetId=spreadsheet_id, range=range_name,
    valueInputOption=value_input_option, body=body).execute()

The body of the update request must be a ValueRange object, though the only required field is values. If range is specified, it must match the range in the URL. In the ValueRange, you can optionally specify its majorDimension. By default, ROWS is used. If COLUMNS is specified, each inner array is written to a column instead of a row.

Writing multiple ranges

If you want to write multiple discontinuous ranges, you can use a spreadsheets.values.batchUpdate request:

values = [
    [
        # Cell values
    ],
    # Additional rows
]
data = [
    {
        'range': range_name,
        'values': values
    },
    # Additional ranges to update ...
]
body = {
  'valueInputOption': value_input_option,
  'data': data
}
result = service.spreadsheets().values().batchUpdate(
    spreadsheetId=spreadsheet_id, body=body).execute()

The body of the batchUpdate request must be a BatchUpdateValuesRequest object, which contains a ValueInputOption and a list of ValueRange objects (one for each written range). Each ValueRange object specifies its own range, majorDimension, and the data to input.

Hope this helps.

A: Figured out that after creating sheet inside spreadsheet you can access range 'nameofsheet!A1' i.e.
service.spreadsheets().values().update(spreadsheetId=s_id, range='New sheet!A1', body=data_i, valueInputOption='RAW').execute()

This request will post the data into new created sheet with name 'New sheet'

A: You could also try a 'more intuitive' library i wrote for google sheets api v4 , pygsheets as i found the default client bit cumbersome.
import pygsheets
gc = pygsheets.authorize()

# Open spreadsheet
sh = gc.open('my new ssheet')

# create a worksheet
sh.add_worksheet("new sheet",rows=50,cols=60)

# update data with 2d vector
sh.update_cells('A1:B10', values)

# or skip let it infer range from size of values
sh.update_cells('A1', values)


text:
Q: Factor graph vs Factor graphical model In inference we use the terms undirected graphical models and directed graphical models. Why do we say factor graph instead of factor graphical models?

A: You say factor graph when referring to the graph.  When referring to the model, you could indeed say factor graphical model.  That Wikipedia page contradicts itself by saying that a factor graph is both a graph and a model.

A: First you need to know the definition of probability graphical model (PGM).

Given a graph G, a distribution p.
a PGM is a pair (G,p), where p factorizes over G.[^1]

The keypoint is where G is a graph , not a factor graph.
Well ,I think there is nothing wrong to say factor graphical model (factor graph G, a distribution p), though there's no such use in literature, because factor graph has redundant information for this definition.
The graph's main advantage to representation is I-map property (i.e. conditional independence ). Even so, it is not very fined-grained representation. That's why factor graph or other representations comes in. (e.g. many factor graphs may represent the same Markov Network [^2] )
In UGM case, we usually have three representation : Markov Network, Factor Graph, Log-linear Model. The latter is finer-grained than previous one.[^3]

Why inference use factor graph? My opinion is

*

*it can represent directed and undirected graphical model. Many inferences are agnostic to both models.

*it can reveal more finer structure than Markov Network that help the message passing algorithm. [^4] Though I am not very familiar to Belief propagation ,I guess it may like reveal tree structure that is ambiguity (to a clique) in Markov Network.

[^1]: Kollar & Friedman 2009 (definition 3.5)
[^2]: Murphy 2012 (Figure 22.2)
[^3]: Kollar & Friedman 2009 (4.4)
[^4]: Murphy 2012 (22.2.3.1)
reference:
Kollar & Friedman 2009. Probabilistic Graphical Model.
Murphy 2012. Machine Learning, a probabilistic perspective.


text:
Q: Discord Python - Multiple Prefixes Is it possible to have multiple prefixes at once?
Example:
@discordbot help
;help (custom prefixes)
and in dms
\help
(I Got a working prefix changer and loader)
If there is, please show me a example or fix my broken code
the code:
import discord
import json

from discord import Embed
from discord.ext import commands
from discord.ext.commands import when_mentioned

def get_prefix(client, message):

    guild = message.guild

    if guild:

        with open('prefixes.json', 'r') as f:
            prefixes = json.load(f)

        return prefixes[str(int(message.guild.id))]

    elif not guild:
        return ','

    else:
        return when_mentioned(client, message)

client = commands.client(command_prefix=get_prefix)

@client.event
async def on_guild_join(guild):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes[str(int(guild.id))] = '//'

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

@client.event
async def on_guild_remove(guild):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes.pop(str(int(guild.id)))

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

@client.command()
async def prefix(ctx, *, prefix):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes[str(int(ctx.guild.id))] = prefix

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

@client.command()
async def ping(ctx):
    await ctx.send('pong')

@client.event
async def on_ready():
    print('ready')

client.run(token)

if not, please show me an example, Thanks

A: You can just make it like
prefixes = ";", "/"
bot = commands.Bot(command_prefix=prefixes)


text:
Q: general solution for Linear Programming problem Given a generic LP with a single constraint:
maximize $c_1x_1 + c_2x_2 +.... c_nx_n$
such that: $a_1x_1 + a_2x_2 + .... + a_nx_n \le b$
Is there an obvious solution?
I had originally thought this was a simple matter of choosing the largest coefficient (call it $c_i$) in the objective, and setting it to ($b/a_i$) so the constraint is met, but this only guaranteed to work if all the $a$ coefficients in the constraint are equal.
Next approach was to do the simplex algorithm by hand with all the parameters, but the result is ugly, and requires (unwarranted) assumptions along the way about whether some values are greater than others.
Is the answer some obvious ratio that I'm missing?

A: In the following, I will use the dual linear program and the strong duality theorem.
The dual of
\begin{align*}
\mbox{maximize } & c_1x_1 + c_2x_2 + \dots + c_nx_m\\
\mbox{subject to } & a_1x_1 + a_2x_2 + \dots + a_nx_m \leq b
\end{align*}
is
\begin{align*}
\mbox{minimize } & b\lambda \\
\mbox{subject to }  & a_1\lambda = c_1\\
& a_2\lambda = c_2\\
&\vdots\\
& a_n\lambda = c_n\\
&\lambda \geq 0\mbox.
\end{align*}
Let us look at the solutions of the dual system:
i) In the first step, we check whether there is any row with $a_i=0$ and $c_i\neq 0$. Such a row has no valid solution and, hence, the dual system is infeasible.
ii) Otherwise, we proceed with the second step, where we delete all rows that do not constrain the choice of $\lambda$. Theses are all rows for which $a_i=0$ and $c_i=0$.
iii) If after ii) no rows remain, we have found an optimal solution $\lambda=0$ of the dual system and the optimal value is $b\lambda = 0$. Otherwise, in the remaining rows none of the $a_i$ is equal to $0$. Then the system has a solution if and only if $\frac{c_i}{a_i}=\frac{c_j}{a_j} \geq 0$ holds for all $i,j=1,\dots,n$. In this case the optimal value of the dual system is $b\frac{c_i}{a_i}$. Otherwise the dual system is infeasible.
Now, the primal system has an optimal solution if and only if the dual system has an optimal solution, and the optimal values agree.
If the dual system is infeasible, then the primal system is feasible, but unbounded. I.e. there exist solutions, but none of them is optimal.
Note, that we can excluded the case that the dual system is unbounded (due to the constraint $\lambda\geq0$). Hence, it follows that the primal system cannot be infeasible, i.e. it always has a (not necessarily optimal) solution.


text:
Q: Flutter Lazy loading on Listview inside another Listview How to apply Lazy Loading or other better option to load more than 5000 of topping list in the Listview.builder inside another Listview.builder?
Below is post.json which will be loaded from local assets
{
    "Food": [
      {
        "name": "Cake",
        "id": "0001",
        "description": [
          {
            "category": "AAA",
            "Size": "Regular",
            "topping": []
          },
          {
            "category": "BBB",
            "Size": "Small",
            "topping": []
          },
          {
            "category": "CCC",
            "Size": "Medium",
            "topping": [
                {
                    "ingredient": "Chocolate with Sprinkles",
                    "price": "$70"
                },
                {
                    "ingredient": "Maple",
                    "price": "$99"
                },
                {
                    "ingredient": "Blueberry",
                    "price": "$123"
                }, ... // more than 5000 of topping list
            ]
          }
        ]
      },
      {
        "name": "Raised",
        "id": "0002",
        "description": ... // same structure as above
      }
    ]
}

Below is the Main file to display List of foods
void main() {
  runApp(const MyApp());
}

// Load local Json file
Future<Post> getFoodList() => Future.delayed(Duration(seconds: 1), ()  async {
  final getResponse = await rootBundle.loadString('assets/post.json');
  var data = jsonDecode(getResponse);
  return Post.fromJson(data);
});

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            child: FutureBuilder<Post>(
              future: getFoodList(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  var getFoodName = snapshot.data!.food;
                  return SingleChildScrollView(
                    child: Wrap(
                      children: [
                        for (final food in getFoodName!)
                          GestureDetector(
                            child: Text(foodName.name.toString()),
                            onTap: () {
                              Navigator.push(context, MaterialPageRoute(builder: (context) => foodDetail(food: food)));
                            },
                          ),
                      ],
                    ),
                  );
                } else {
                  return Text('Loading');
                }
              },
            ),
          ),
        ],
      ),
    );
  }
}

Food Detail page - display more than 5000 of topping list
class FoodDetail extends StatefulWidget {
  final Food food;
  const FoodDetail({super.key, required this.food});

  @override
  State<FoodDetail> createState() => _FoodDetailState();
}

class _FoodDetailState extends State<FoodDetail> {
  late ScrollController controller;
  // This example is taken from Flutter ListView lazy loading
  List<String> items = List.generate(100, (position) => 'Hello $position');

  @override
  void initState() {
    super.initState();
    controller = ScrollController()..addListener(_scrollListener);
  }

  @override
  void dispose() {
    controller.removeListener(_scrollListener);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Padding(
            padding: const EdgeInsets.all(8.0),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  // This is the first ListView.build to display category and size under description
                  ListView.builder(
                      itemCount: widget.food.description!.length,
                      itemBuilder: (context, index) {
                        // IF category is AAA || BBB, display the size
                        if (widget.food.description![index].category == "AAA" || widget.food.description![index].category == "BBB") {
                          return Text(widget.food.description![index].size.toString());
                        }
                        // IF category is CCC display the List of Topping (Note: this topping list is more than 5000)
                        else {
                          // This is the second ListView.build to display the topping information
                          // How do I apply ScollController or Lazy Loading to load 5000 list of topping?
                          return ListView.builder(
                              controller: controller,
                              itemCount: widget.food.description![index].topping!.length,
                              itemBuilder: (context, position) {
                                return Column(
                                  children: [
                                   Text(widget.food.description![index].topping![position].ingredient.toString())
                                   Text(widget.food.description![index].topping![position].price.toString())
                                  ],
                                );
                              });
                            }
                          }),
                    ],
                  ),
            )));
  }
  // This example is taken from Flutter ListView lazy loading
  void _scrollListener() {
    if (controller.position.extentAfter < 500) {
      setState(() {
        items.addAll(List.generate(42, (index) => 'Inserted $index'));
      });
    }
  }
}

Output of the workflow:

A: I think your best bet is to try to try to refactor it in a way to use only a single ListView.builder. To do this you need to flatten the data you are working with in some way. Here is an example that also uses nested data that transforms it in a way so a single ListView displays it. I'm not sure if it's the best way to do it but I think you could do something similar for your code maybe. This might give you an idea of how to do it:
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  final data = const [
    {
      "name": "A",
      "subnames": ["A1", "A2", "A3", "A4", "A5"]
    },
    {
      "name": "B",
      "subnames": ["B1", "B2", "B3", "B4", "B5"]
    },
    {
      "name": "C",
      "subnames": ["C1", "C2", "C3", "C4", "C5"]
    },
  ];

  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final newData = data
        .map((e) => [
              {"type": 1, "name": e["name"]},
              for (final name in (e["subnames"] as List))
                {"type": 2, "name": name}
            ])
        .expand((e) => e.toList())
        .toList();

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
          body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: ListView.builder(
            itemCount: newData.length,
            itemBuilder: (context, index) {
              if (newData[index]['type'] == 1) {
                return Text(
                  newData[index]['name'],
                  style: const TextStyle(color: Colors.red),
                );
              } else {
                return Text(
                  newData[index]['name'],
                  style: const TextStyle(color: Colors.blue),
                );
              }
            }),
      )),
    );
  }
}

Output:


text:
Q: Animate an skewed div without undesired effects I was thinking to make a menu with parallelogram containers and animate them on CSS. The idea is when you hover an item, the parrallelogram change it's height to make a visual scaling effect.
So far, so good, but the problem is that when I change the parallelogram's height on hover, it also change it's position a little bit to the right and I don't know why.
So the cuestion would be: Is it any way to change the parallelogram's height preserving it's position?
Here's the undesired effect I've got:

.container {
    float: left;
    padding: 0 0.5rem;
}

.parallelogram {
 position: relative;
 width: 125px;
 height: 50px;
 -webkit-transform: skew(-30deg);
 -moz-transform: skew(-30deg);
 -o-transform: skew(-30deg);
 transform: skew(-30deg);
    transition: all .4s linear;
}

.parallelogram:hover {
 height: 100px;
}

    1

    2

    3

A: From what I understand, you just need to change the transform-origin for .parallelogram.
Here's the updated demo.

.container {
  float: left;
  padding: 0 0.5rem;
}
.parallelogram {
  position: relative;
  width: 125px;
  height: 50px;
  -webkit-transform: skew(-30deg);
  -moz-transform: skew(-30deg);
  -o-transform: skew(-30deg);
  transform: skew(-30deg);
  transition: all .4s linear;
  transform-origin: top right;
}
.parallelogram:hover {
  height: 100px;
}

    1

    2

    3


text:
Q: How to create integration tests for auth0 private scoped endpoints in ASP.Net Core I have an ASP Net Core Web API which uses auth0 for authorization and authentication. Moreover, every endpoint is protected with different scopes. For example, to access the endpoint to read all reservations, one would need to have the read:reservations scope.
In auth0, I have roles that contain multiple permissions. Currently, I have an admin role that has access to all endpoints and a receptionist who can only view and edit reservations.
I want to create some integration tests to verify that the authorization works. I am using the Client Credentials Flow as explained here. The problem is that the access tokens I get have no scopes and, therefore, cannot access the endpoints.
At the end of the linked article, it is mentioned that the tokens can be customized using actions. However, I am confused because, as far as I understood, I would have to add every permission manually.
My question therefore is, how could I create multiple access tokens for the different roles that I have to test the endpoints as if I were a person with a said role?


text:
Q: uiautomation iOS uilabel value I am trying to get the value from a UILabel by doing a target.logElementTree() but I am unable to see the value that the Label is actually set with.
It only shows the string that we set based on the accessibilityLabel
self.settlementDate.isAccessibilityElement = YES;
self.settlementDate.accessibilityLabel = @"DetailViewInCode_SettlementDate";

And in the target.logElementTree() this is the value that I see i the log of Instruments-Automation
UIAStaticText: name:DetailViewInCode_SettlementDate value:DetailViewInCode_SettlementDate rect:{{260, 345}, {304, 21}}

UIALogger.logMessage("Target static:"+target.frontMostApp().mainWindow().staticTexts()["Activity_DetailedView_SettlementDate"].value());

And I can see the screenshot when I click on that entry

iOS 5.1 Simulator

A: It seems that the value is set by default with the value of accessibilityLabel property. Try to set the accessibilityValue property in the code in the same manner you set the accessibilityLabel property.
self.settlementDate.accessibilityValue = <ActualVale>;

A: The value is shown in the log. The value of that label is DetailViewInCode_SettlementDate.
The fact that the value and the name are identical might have been confusing you. This is not something uncommon.


text:
Q: Saving radio button options to access them later in wordpress plugin This is my code for the radio buttons. I would like them to be displayed in the settings page and save it for future use.
<form method="post" action="options.php">
<?php
    wp_nonce_field('update-options');
    $rsp_position = get_option('rsp_position');
    if(empty($rsp_position)){
        $rsp_position = "true";
    } else {
        $rsp_position = get_option('rsp_position');
    }
?>

Ad Placing:

<input type="radio" id="1" name="rsp_position" <?php if($rsp_position == 'true') echo 'checked="checked"'; ?> value="true" />yes

<input type="radio" id="2" name="rsp_position" <?php if($rsp_position == 'false') echo 'checked="checked"'; ?> value="flase" />no

<input type="text" name="publisher-id" size="45" value="<?php echo get_option('publisher-id'); ?>" />

<input type="submit" name="Submit" value="Save" />

<input type="hidden" name="action" value="update" />
<input type="hidden" name="page_options" value="publisher-id" />
<?php
    settings_fields( 'save_position' );
    register_setting( 'save_position', 'rsp_position');
?>

A: You're going along the right lines, but your calls to settings_fields and register_setting aren't in the right place.
Read Otto's tutorial on this, it's a good introduction to the settings API.
Basically, add an admin_init action and in the callback register the setting and use add_settings_field to create the form items.
Then in your add_options_page callback you make the call to settings_fields to display the entries created with add_settings_field.
If you're still struggling having worked through Otto's tutorial, post back again.
EDIT: Following pastebin entry.
The failure to save is a result of your validation function not returning the expected value. The preg_match is not finding the right value and turning the string to '' (nothing) before saving - so it looks like it's not saving, when in fact it's saving nothing.
You could also check out the following functions which may be useful.

*

*submit_button

*settings_errors


text:
Q: Newbie, for GIS (need wander path, trail data) I need Greek wander paths of places like mountains and forests as shapefiles, but I don't know how to start to extract them from specific sites or getting them ready as shapefiles. I need these data to store them in a Postgres DB and execute some PostGIS queries to find people who have been lost in a region. Can you give me some instructions how to extract these data or sites where I can find them ready?
I have found some sites where you can place your route like these here:
wandermap or this OSM specific, but I don't know how to extract the data as shapefiles. More specific, if it is possible I want to make a selection by dropping a rectangle over a region or country and extract these content as shapefiles. Is this possible?. And if yes, how can I achieve this?.
The data are needed to build something like this here: Introduction to web programming for GIS applications

A: Data from OSM can be extracted in a defined area from www.bbbike.org. here is the link


text:
Q: How to determine smallest $M>0$ such that $(Au,v)≤M\Vert u \Vert \Vert v \Vert?$ Let $V=\mathbb R^2$ provided with the euclidean inner product and norm. Given a linear, bounded and strong positive operator
$$A=\begin{bmatrix}
1 & 1 \\
\frac{1}{2} & 3
\end{bmatrix}
$$ is it true that the greatest $\mu>0 $ such that $$(Au,u) ≥ \mu\Vert u\Vert^2$$ is the greatest eigenvalue of A as I assume?
Furthermore, how can I determine the smallest $M>0$ such that $$(Au,v)≤M\Vert u \Vert \Vert v \Vert?$$
I have the assumption to somehow involve the symmetric part $\frac{1}{2}(A+A^T)$ to show is as I have seen something similar before. Some help or hints would be much appreciated.

A: As indicated in the comments below the answer, the $\mu$ in question will be the smallest eigenvalue of $B = (A + A^T)/2$.  One explanation is as follows:

*

*For all $u$, we have $(Au,u) = (Bu,u)$

*By the Rayleigh-Ritz theorem (described briefly in the opening blurb here), the minimum value of $(Bu,u)/\|u\|^2$ is the lowest eigenvalue of $B$.

As for $M$: we begin by noting that the largest singular value of $A$ can be described as
$$
\sigma_1(A) = \|A\| = \max_{\|x\| = 1} \|Ax\|
$$
With that and the Cauchy-Schwarz inequality, we note that
$$
(Au,v) \leq \|Au\| \cdot \|v\| \leq \sigma_1(A)\cdot \|u\| \cdot \|v\|
$$
To see that this upper bound is attained (i.e. that there exist $u,v$ such that $(Au,v) = \sigma_1(A)\|u\| \|v\|$), it suffices to take a $u$ such that $\|Au\| = \sigma_1(A)$ and take $v = Au$.


text:
Q: add row to the DB:: result in Laravel I have a table BirthDeath like below:
id birthmonth deathmonth
1  1            3
2  4            4
3  2            5

The query is for getting either birth or death month,
$events = DB::table('BirthDeath')->where('birthmonth',4)->orWhere('deathmonth',4)->paginate(10);

This query results in 1 row, however, I need this row to be duplicated (because the birth and death month are the same) and in the view, I am intending to show them separately. My current solution is to duplicate the results if the birth and death month are the same but it does not work. Here is the code
events2 = $events;
    foreach ($events as $event) {
            if ($event->birthmonth == $CurrentMonth || $event->deathmonth == $CurrentMonth) {
                $events2->appends($event); <-------- this is the cause of the error
            }
        }

A: If you want to add items to a Collection you can use the add or push method. add takes a single item and push can take many (variable amount of arguments):
$events->add($event);
// or
$events->push($event);


text:
Q: Only Some Filename Extension Needed When Compiling -- Why? Consider the following file named test.tex:
\documentclass{article}
\begin{document}
A
\end{document}

If I want to compile using latex --> dvips --> ps2pdf, I can use
latex test
dvips test

for the first two steps.
Now to my question: why I have to use
ps2pdf test.ps

instead of just
ps2pdf test

to get the last step in the compiling process?

A: The support for a default extension is a feature. Some programs support this, some not. ps2pdf of ghostscript is quite old and comes in different flavors, a shell script for Unix, batch for DOS/Windows, ...; my guess is, that the intention was to keep is short and simple.
There is also a downside to default extensions. It raises the ambiguity issue. Which file is loaded, if there is a file with the default extension and the file without extension? Should the specified file tried first, because it is the specified file after all, or should the file with the default extension be used, which is more appropriate for the application? Thus, not using a default extension provides a more robust and clear interface.


text:
Q: How can I send Broadcast message in c++ builder 6 What I want is to know how to bind two computers for my online game.
I made it using Server Socket and Client Socket and it works. But how can I do the same if it's unknown where this program is running. So I can't connect because I don't know who is the server. I was told that I can send broadcast message but now it's the third day of my endless attempts to do it...
I tried to write it like this (c++ builder 6):
ClientSocket->Socket->SendText("Message");

The address and host is 192.168.0.255;
And I run it twice in one computer at the same time but it does not work (because I don't know what to do then)).
Please, help me to find the server that I don't know beforehand.

A:
I was told that I can send broadcast message

That is one way to do it, yes (it is not the only way).  However, that only works if the client PC and server PC are connected to the same network.
The server app can open two listening sockets, one for TCP and one for UDP (IPv4 only) or Multicast (IPv4 or IPv6).  IPv6 does not support UDP broadcasts, so you have to use Multicast instead.
The client app can then:

*

*for UDP, send a message to the UDP port using the broadcast IPv4 address of the subnet that it is connected to.  The message will be delivered to every device connected to that subnet.  If the server PC is connected to the same subnet and the server app receives the broadcast message, it can send a reply back to the IPv4 address that sent the broadcast.  When the client app receives the reply, it will know the IPv4 address that sent the reply.

*for Multicast, subscribe to the server PC's Multicast group address.  The server can periodically send its current IP address to the group, and any clients that are subscribed to the same group will receive it.  When the client receives the message, it will know the IP address that sent the message.
Once the client has discovered the server's IP address, it can connect its TCP client socket to that IP address using the TCP port.
If the two PCs are not on the same network (ie, they are connecting over the Internet), then the above does not apply.  The server will have to publish its current IP address somewhere that the client can find it, such as on a public website, or a Dynamic DNS service.
Of course, the simplest solution is to just ask the server admin for the server's current TCP IP/port, and then you can enter that into your client app's configuration as needed.

I tried to write it like this (c++ builder 6):
  ClientSocket->Socket->SendText("Message");

TClientSocket uses TCP/IP.  To send a subnet broadcast using UDP, you need to use UDP component instead.  C++Builder 6 ships with FastNet, which has a TNMUDP component, as well as Indy, which has TIdUDPClient and TIdUDPServer components.  Or, you can write your own UDP socket code using the WinSock API directly.
Indy also provides Multicast

The address and host is 192.168.0.255

That is the broadcast IP address for an IPv4 192.168.0.x subnet that has a 255.255.255.0 subnet mask.  If that is your actual subnet configuration, and your client and server PCs are both connected to the 192.168.0.x subnet, then yes, you can send a UDP broadcast message to that IP address.
To obtain the subnet broadcast IP address, you can either:

*

*calculate it manually.  Use GetAdaptersInfo() or GetAdaptersAddresses() to get the local PC's current IPv4 address and subnet mask, then mask the bits of the IP address with the bits of the subnet mask using an AND operator, and then OR the result with the inverse bits of the network mask.

*ask Windows.  Create a socket and bind() it to the desired local network adapter. and then use WSAIoctl(SIO_GET_BROADCAST_ADDRESS) to query the broadcast IP address associated with that network.


text:
Q: CKEditor - How to use the Advanced Content Filter and widgets together in 2 editors I've got 2 CKEditor instances. One editor (A) supporting a number of widgets, another editor B has an Advanced Content Filter with these settings to make sure only <p>, <br>, <em> and <strong> tags are allowed in the second editor:
config.allowedContent = 'p br em strong';

My widget contains an image and some other tags and this filter setting:
config.allowedContent = 'img div figure figcaption';

When text containing this kind of widget from editor A is pasted into editor B, I would like the editor to strip out the widget but it doesn't.  This makes sense because the allowedContent setting of the widget makes sure that the image is not removed.
However, my second editor does not know anything about this widget and I would like to configure the filter to strip out all widgets pasted in.
I've tried adding the Disallowed Content setting to editor B:
config.disallowedContent = 'img div span figure figcaption';

But without succes, I keep getting the widget div's in editor B.
Same goes for pasting the widget into editor 4 of the sample editors provided by CKEditor. The widget is inserted even if the ACF does not allow it.
Is there another filter option to prevent widgets from sneaking into the body?

A: Unfortunately there's no easy way to filter pasted events with the ACF at the moment - see http://dev.ckeditor.com/ticket/11115. It has the 4.5.0 milestone assigned, but I don't feel that we'll manage to make this change in this version. There are architectural limitations which make this ticket very complex.
What you could try to do is to intercept pasted content on the editor#paste, parse the content and filter pasted widgets manually. The hard thing (the actual #11115 blocker) is that in the pasted content you'll find upcasted versions of widgets, with all wrappers, all internal attributes etc. ACF cannot be applied to this content directly because ACF is supposed to filter downcasted versions of widgets. Therefore you need to filter this more manually or with a special CKEDITOR.filter instance.
You can find this question useful - Apply CKEditor Advanced Content Filter to a string.


text:
Q: How to stop resizing elements at diferent devices I have a problem with the button that changes the size of the mobile.
Can I somehow prevent that? I want to get the same look at mobile as on pc.
Button size change example.
The code that I use is:

.container8 {
  position: relative;
  width: 100%;
  max-width: 100%;
}

.container8 img2 {
  width: 100%;
  height: 100%;
}

.container8 .xxx8 {
  position: absolute;
  top: 73%;
  left: 72%;
  background-color: #e20612;
  color: black;
  font-size: 18px;
  padding: 1% 3.5%;
  border: none;
  cursor: pointer;
  border-radius: 10%;
  text-align: center;
}

.xxx8:hover {
  background-color: #b3ecff
}

.container8 .btn:hover {
  background-color: black;
}
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">

    <button class="xxx8">FORM</button>

A: if you set a px size for your button, it will be the same size for each device and screens
.xxx8 {
    height: 50px;
    width:  100px;
}

A: I see in your code that the size of FORM button depends on this button text size. So if you want to have the same font size (and also the same responsive button) on each device set the vw or vh in font size ex. font-size: 2vw;
.container8 .xxx8 {
   position: absolute;
   top: 73%;
   left: 72%;
   background-color: #e20612;
   color: black;
   font-size: 2vw;
   padding: 1% 3.5%;
   border: none;
   cursor: pointer;
   border-radius: 10%;
   text-align: center;
}

Look in JSFiddle if it is what you want.
vw is device width (responsive)
vh is device height (responsive)

A: Give a fixed width and height to your button, also you should take a look at what Responsive is.
.xxx8{
    display: inline-block;
    height: 50px;
    width: 100px;
}

A: <meta name="viewport" content="width=device-width, initial-scale=1">

remove this meta from HTML file

A: You could try adding !important at the end of the css which has the size of the button.
Or you can do CSS media queries like this.
@media (max-width: 600px (you need to know on which width your are getting the trouble)) {
  .class_of_button{
     width: your width;
     height: your height;

}


text:
Q: Sample size estimation for difference-indifference design with continuous outcome I have spent some time looking for a package in R to estimate the required sample size for a difference-in-difference design with continuous outcome. However, I could not find any package. Is there a package available that I have overlooked? Or is there a procedure in Stata 15? Thanks a lot for your guidance on this matter in advance.
Best
Michael


text:
Q: What to do when my scope does not fit into any master scope? I have created my own unity scope following this tutorial which works very well.
For now I have added it to the Info master scope, however it does not really fit there or in any other master scope. Do I need to create my own master scope? If yes how do I go about this?

A: After a discussion I had on IRC Freenode #ubuntu-unity I have now a solution which I wanted to share.
It is fairly easy to turn an ordinary scope into a master scope. To start just create a normal scope e.g. by following the scope tutorial.
The only thing which needs to be different is the scope file. Instead of copying it into a specific scope your directly copy it into /usr/share/unity/scopes/. Additionally in the scope file add IsMaster in the scope section
[Scope]
...
IsMaster=true

As a master scope can define its own filters and categories add those as needed to your scope file as well. Here an example I copied from the files.scope file:
[Category recent]
Name=Recent
Icon=/usr/share/icons/unity-icon-theme/places/svg/group-recent.svg
DedupField=uri

[Filter type]
Name=Type
Type=filter-checkoption
SortType=display-name
OptionIDs=documents;folders;images;audio;videos;presentations;other;
OptionNames=Documents;Folders;Images;Audio;Videos;Presentations;Other;

Per default won't your new master scope show up as an icon on the dash. If you want to do so you will need to change gsettings which you can do with the following command:
gsettings set com.canonical.Unity.Dash scopes "['home.scope', 'applications.scope', 'files.scope', 'video.scope', 'music.scope', 'photos.scope', 'social.scope', 'mynewmaster.scope']"

Replace mynewmaster.scope with the name of your scope. Done.


text:
Q: Поменять template.php после Ajax запроса (Битрикс) Есть компонент, который отрисовывает содержимое в несколько столбцов, количество столбцов хранится в $arResult["COLS"], моя задача состоит в том, чтобы при размере окна <= 768px принудительно задать $arResult["COLS"] = 1.
Я решил пойти через Ajax(Может это и не правильный путь): Отправляю Ajax запрос, в компоненте его обрабатываю:
if ($_POST["123"]) {
$APPLICATION->RestartBuffer();
$arResult["COLS"] = 1;
exit();
}

Запрос отправляется и обрабатывается, но переменная остается прежней, как обновить эту переменную чтобы шаблон отрисовался в один столбец?


text:
Q: How do I do initial data configuration setup with CoreData? I've got an app using CoreData as a data storage mechanism and the app needs some initial data to be configured. Are there any recommendations / what/how are you doing in order to set up the initial data?
Currently I am doing it in the following way (when the app starts for the 1st time):
SomeEntity *newEntity=[NSEntityDescription insertNewObjectForEntityForName:@"SomeEntity" inManagedObjectContext:context];
[newEntity setCode:@"a-code"];
[newEntity setName:@"a-name"];
...
[context save:nil];

I do not like this approach for 2 reasons:
1) it's so boring and error-prone if you need more than 10 entity instances for more than  one entity type
2) it may take up some time for the initial start-up
In previous apps using SQLite I just linked my initial SQLite database into the app and, if needed to modify any data, moved the database to the Documents directory. Is there any similar approach for CoreData?

A: That's exactly what you'd do with Core Data, too. Use your app to create the data the way you want, and then download the data from the device. You'll find a SQLite file in the Documents directory (which is the default location). Add the SQLite file to your project as a resource. It'll get copied along with your app.
Then, all you need to do is write some code to determine if a file already exists in the Documents directory on startup. If not, you can copy the file from your application's bundle to the Documents directory and Core Data will open that. You just want to make sure to do this before the NSPersistentStoreCoordinator is set up.


text:
Q: Wix - ComPlusAssembly - Could not install type library I'm new to Wix and I have ran into a problem that I'm obviously not able to solve on my own, so any help will be very much appreciated.
Quick background:
I'm representing a software vendor building a comprehensive suite of SOA based applications for deployment in large enterprises. Our architecture consists of many layers which may be installed/upgraded independently, so I'm building several installers, composing from the ground up (like: platform, core framework components, service layer, business layer, application layer, etc.).
Software versions:
-Wix 3.5.1309.0 (wix.dll)
- Visual Studio 2008, .Net 3.5
- Build OS: Windows 2008 R2 Standard 64 bit
- Deploy OS: Windows 2008 Standard 32 bit
My problem is in regards to installing .Net assemblies in COM+ applications. I keep on getting the error "Could not install type library". I have been reading all the documentation that I can find, and I have been google'ing for several days now. I find quite a few posts on the topic, but I'm still not able to resolve the issue.
To isolate the problem I have extracted the issue into a separate installer. First I run the main installer:
1. Installs all assemblies into GAC, including the one to be installed in COM+.
2. Create local users and groups.
3. Create the target COM+ application, including roles etc.
4. Installs the target assembly, and the companion typelib, in a folder (to remove any GAC lookup issues)
This installer I can install/repair/uninstall, everything works fine.
Then I run the minimum installer containing only the issue, which tries to:
1. Install the assembly in an existing COM+ application (server), referencing the pre-installed .dll and .tlb.
The install fails, and the log is showing:
MSI (s) (AC:64) [19:16:01:127]: Invoking remote custom action. DLL: C:\Windows\Installer\MSI1BAB.tmp, Entrypoint: ComPlusInstallExecute
ComPlusInstallExecute:  ExceptionInfo: Code='0', Source='System.EnterpriseServices', Description='Could not install type library 'c:\Program Files\MyManufacturer\ComPlus\WDA.ServiceProviders.Update.11.tlb' into application 'WDA.ServiceProviders.Update.11'.', HelpFile='', HelpContext='0'
ComPlusInstallExecute:  Error 0x80020009: Failed to invoke RegistrationHelper.InstallAssembly() method
ComPlusInstallExecute:  Error 0x80020009: Failed to register .NET assembly
ComPlusInstallExecute:  Error 0x80020009: Failed to register assembly, key: MyAssembly
ComPlusInstallExecute:  Error 0x80020009: Failed to register assemblies
Action ended 19:16:02: InstallFinalize. Return value 3.

I also notice that the rollback removes the COM+ application, even though it was not created by this installer.
I can install the assembly manually, using the Server Manager, from the same physical file that the installer is referencing. After manually removing the component from the COM+ application, then the installer works!
Also, why do I have to supply a typelib in the first place? The EnterpriseServices.RegistrationHelper is generating the typelib on the fly anyway.
This is the minimum test installer that is failing:
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
     xmlns:complus="http://schemas.microsoft.com/wix/ComPlusExtension"
>
  <Product Id="48EDB258-BD84-47EF-94A2-B4950EE48139"
             UpgradeCode="F29B8EBD-DFD1-4B7E-96FF-86842CAAE4A4"
             Name="ComPlusInstalls"
             Language="1033"
             Version="1.0.0"
             Manufacturer="MyManufacturer">
    <Package Id="ABA41719-BC28-4A57-BA9A-58F4F3B2194F" InstallerVersion="200" Compressed="yes" />
    <Media Id="1" Cabinet="WixTest.cab" EmbedCab="yes" />
    <complus:ComPlusApplication Id="MyApplication" ApplicationId="1FCF220A-A1FE-44FE-BE91-B37341BA6D4A" />
    <Directory Id="TARGETDIR" Name="SourceDir">
      <Directory Id="ProgramFilesFolder">
        <Directory Id="MyManufacturer" Name="MyManufacturer">
          <Directory Id="INSTALLLOCATION" Name="ComPlus">
            <Component Id="MyComponent" Guid="6D46A007-6669-487B-BAA0-DFA7314C141D" KeyPath="yes">
              <complus:ComPlusAssembly Id="MyAssembly" Type=".net" Application="MyApplication"
                                       RegisterInCommit="no" DllPathFromGAC="no"
                                       DllPath="[INSTALLLOCATION]WDA.ServiceProviders.Update.11.dll"
                                       TlbPath="[INSTALLLOCATION]WDA.ServiceProviders.Update.11.tlb"/>
            </Component>
          </Directory>
        </Directory>
      </Directory>
    </Directory>
    <Feature Id="MainFeature" Title="WixTest" Level="1" Absent="disallow" InstallDefault="local">
      <ComponentRef Id="MyComponent" />
    </Feature>
  </Product>
</Wix>

Cheers,
-Nils

A: I have the same problem. Ive tried Wix 3.5 and 3.6.2012.0 and it hasnt worked with either. It works if

*

*I use regsvcs first

*Delete the component

*Run the msi and click on Ignore when a message comes up about the application already existing

Did you manage to find a solution?

A: First, you might try upgrading to the latest version of WiX v3.5. There were some bug fixes in COM+ at the end. If that doesn't work, take a look at the open bugs around COM+. There are a couple known issues with the installation code due to complexities in COM+.
If any of those bugs sound applicable maybe you can help fix them with the community?