text:
Q: Звездный рейтинг с шрифтом "Fontello" $('body').on('mousemove', '.blockElem', function(e) {
    var x = e.offsetX==undefined?e.layerX:e.offsetX;

if(x >= 1 && x < 20) {
    $('.elem1').html('✯');
  $('.elem2').html('✫');
  $('.elem3').html('✫');
  $('.elem4').html('✫');
  $('.elem5').html('✫');
  var result = 1;
}

if(x >= 21 && x < 40) {
    $('.elem1').html('✯');
  $('.elem2').html('✯');
  $('.elem3').html('✫');
  $('.elem4').html('✫');
  $('.elem5').html('✫');
  var result = 2;
}

if(x >= 41 && x < 60) {
    $('.elem1').html('✯');
  $('.elem2').html('✯');
  $('.elem3').html('✯');
  $('.elem4').html('✫');
  $('.elem5').html('✫');
  var result = 3;
}

if(x >= 61 && x < 80) {
    $('.elem1').html('✯');
  $('.elem2').html('✯');
  $('.elem3').html('✯');
  $('.elem4').html('✯');
  $('.elem5').html('✫');
  var result = 4;
}

if(x >= 81 && x < 100) {
    $('.elem1').html('✯');
  $('.elem2').html('✯');
  $('.elem3').html('✯');
  $('.elem4').html('✯');
  $('.elem5').html('✯');
  var result = 5;
}

$('.result').html(result);});$('body').on('mouseleave', '.blockElem', function() {
$('.result').html('OUT');});

https://jsfiddle.net/yfp09xt2/ - Набросал рейтинг с html символами
https://test.xn--80akhmlofgv.net/new_Real_Estate/test - с шрифтом "Fontello"
При использовании "Fontello" mouseleave не срабатывает. Помогите разобраться.

A: меняйте class а не html

$(document).ready(function() {
  $('body').on('mousemove', '#starRating', function(e) {
    var x = e.offsetX == undefined ? e.layerX : e.offsetX;

    var dataOldRating = $('#starRating').data('oldRating');
    if (dataOldRating === 'no') {
      var oldRating = $('#starRating').html();
      $('#starRating').data('oldRating', oldRating);
    }
    var rating = 0;

    if (x >= 1 && x < 11) {
      $('.starRating1 i').attr('class', "icon-star-half-alt");
      $('.starRating2 i').attr('class', "icon-star-empty-1");
      $('.starRating3 i').attr('class', "icon-star-empty-1");
      $('.starRating4 i').attr('class', "icon-star-empty-1");
      $('.starRating5 i').attr('class', "icon-star-empty-1");
      rating = 0.5;
    }

    if (x >= 11 && x < 23) {
      $('.starRating1 i').attr('class', "icon-star-3");
      $('.starRating2 i').attr('class', "icon-star-empty-1");
      $('.starRating3 i').attr('class', "icon-star-empty-1");
      $('.starRating4 i').attr('class', "icon-star-empty-1");
      $('.starRating5 i').attr('class', "icon-star-empty-1");
      rating = 1;
    }

    if (x >= 23 && x < 34) {
      $('.starRating1 i').attr('class', "icon-star-3");
      $('.starRating2 i').attr('class', "icon-star-half-alt");
      $('.starRating3 i').attr('class', "icon-star-empty-1");
      $('.starRating4 i').attr('class', "icon-star-empty-1");
      $('.starRating5 i').attr('class', "icon-star-empty-1");
      rating = 1.5;
    }

    if (x >= 34 && x < 45) {
      $('.starRating1 i').attr('class', "icon-star-3");
      $('.starRating2 i').attr('class', "icon-star-3");
      $('.starRating3 i').attr('class', "icon-star-empty-1");
      $('.starRating4 i').attr('class', "icon-star-empty-1");
      $('.starRating5 i').attr('class', "icon-star-empty-1");
      rating = 2;
    }

    if (x >= 45 && x < 56) {
      $('.starRating1 i').attr('class', "icon-star-3");
      $('.starRating2 i').attr('class', "icon-star-3");
      $('.starRating3 i').attr('class', "icon-star-half-alt");
      $('.starRating4 i').attr('class', "icon-star-empty-1");
      $('.starRating5 i').attr('class', "icon-star-empty-1");
      rating = 2.5;
    }

    if (x >= 56 && x < 67) {
      $('.starRating1 i').attr('class', "icon-star-3");
      $('.starRating2 i').attr('class', "icon-star-3");
      $('.starRating3 i').attr('class', "icon-star-3");
      $('.starRating4 i').attr('class', "icon-star-empty-1");
      $('.starRating5 i').attr('class', "icon-star-empty-1");
      rating = 3;
    }

    if (x >= 67 && x < 78) {
      $('.starRating1 i').attr('class', "icon-star-3");
      $('.starRating2 i').attr('class', "icon-star-3");
      $('.starRating3 i').attr('class', "icon-star-3");
      $('.starRating4 i').attr('class', "icon-star-half-alt");
      $('.starRating5 i').attr('class', "icon-star-empty-1");
      rating = 3.5;
    }

    if (x >= 78 && x < 89) {
      $('.starRating1 i').attr('class', "icon-star-3");
      $('.starRating2 i').attr('class', "icon-star-3");
      $('.starRating3 i').attr('class', "icon-star-3");
      $('.starRating4 i').attr('class', "icon-star-3");
      $('.starRating5 i').attr('class', "icon-star-empty-1");
      rating = 4;
    }

    if (x >= 89 && x < 100) {
      $('.starRating1 i').attr('class', "icon-star-3");
      $('.starRating2 i').attr('class', "icon-star-3");
      $('.starRating3 i').attr('class', "icon-star-3");
      $('.starRating4 i').attr('class', "icon-star-3");
      $('.starRating5 i').attr('class', "icon-star-half-alt");
      rating = 4.5;
    }

    if (x >= 100 && x <= 112) {
      $('.starRating1 i').attr('class', "icon-star-3");
      $('.starRating2 i').attr('class', "icon-star-3");
      $('.starRating3 i').attr('class', "icon-star-3");
      $('.starRating4 i').attr('class', "icon-star-3");
      $('.starRating5 i').attr('class', "icon-star-3");
      rating = 5;
    }

    $('#ColRating').html(rating);
  });

  $('body').on('mouseleave', '#starRating', function(e) {
    //var oldRating = $('#starRating').data('oldRating');
    //$('#starRating').html(oldRating);
    $('#ColRating').html("OUT");
  });
});

A: Звездочки закрывают общий блок от нормального события mouseleave. Поскольку вы их все равно не используйте (их события), просто отключите их от взаимодействия с мышью:
.starRating span {
    pointer-events: none;
}


text:
Q: Müller's Method I have these question and I cannot solve it.
Can somebody help me?

Use Müller's method to determine the roots of
  $$
 f(x)=2x^5−2x^4+6x^3−6x^2+8x−8
$$
  Choose $x_2=0.8 $, $x_0=0.808$ $x_1=0.792$.
Terminate your computation when the approximate relative error falls below  $E_s = 10^{-4}$

A: The essential formulas in https://en.wikipedia.org/wiki/Muller%27s_method are
$$
 w = f[x_{k-1},x_{k-2}] + f[x_{k-1},x_{k-3}] - f[x_{k-2},x_{k-3}]. \,
$$
and
$$
x_{k} = x_{k-1} - \frac{2f(x_{k-1})}{w \pm \sqrt{w^2 - 4f(x_{k-1})f[x_{k-1}, x_{k-2}, x_{k-3}]}}.
$$
The most difficult part is to find striking variable names... Set

*

*x1 for $x_{k-1}$, x2 for $x_{k-2}$ etc. and

*f1=f(x1) for f(x_{k-1}), f2=f(x2), etc. and

*for the divided differences set

*

*f12=(f1-f2)/(x1-x2) for $f[x_{k-1},x_{k-2}]$,

*f23=(f2-f3)/(x2-x3) and

*f13=(f1-f3)/(x1-x3) and finally

*f123=(f12-f23)/(x1-x3) for $f[x_{k-1},x_{k-2},x_{k-3}]$

#include<stdio.h>
#include<math.h>
#include<complex.h>

complex double f(complex double x) {
    complex double x2 = x*x;
    return (x-1)*((x2+2)*(x2+2)-x2);
}

complex double Muller(complex double (*f)(complex double), double a, double b, double c) {
    // initialize
    unsigned int k=0;
    complex double x1 = c, f1 = f(x1);
    complex double x2 = b, f2 = f(x2), f12 = (f1-f2)/(x1-x2);
    complex double x3 = a, f3 = f(x3), f13 = (f1-f3)/(x1-x3), f23 = (f2-f3)/(x2-x3);
    complex double f123 = (f12-f23)/(x1-x3);
    double scale = fmax(cabs(f1),fmax(cabs(f2),cabs(f3)));

    printf("x[%2u]=%-15.12f%+15.12fi,\tf(x[%2u])=%-15.12f%+15.12fi,\n",
           k,creal(x3),cimag(x3),k,creal(f3),cimag(f3));
    k++;
    printf("x[%2u]=%-15.12f%+15.12fi,\tf(x[%2u])=%-15.12f%+15.12fi,\n",
           k,creal(x2),cimag(x2),k,creal(f2),cimag(f2));
    k++;
    printf("x[%2u]=%-15.12f%+15.12fi,\tf(x[%2u])=%-15.12f%+15.12fi,\n",
           k,creal(x1),cimag(x1),k,creal(f1),cimag(f1));
    k++;
    // loop
    double err = 1;
    while ( err > 1e-4 )
    {
        // iteration formulas, variables are type complex double, controls real
        complex double w = f12 - f23 + f13;
        complex double root = csqrt(w*w-4*f1*f123);
        if( cabs(w+root) < cabs(w-root) ) root = -root;
        complex double x0 = x1 - 2*f1/(w+root);
        complex double f0 = f(x0);
        printf("x[%2u]=%-15.12f%+15.12fi,\tf(x[%2u])=%-15.12f%+15.12fi,\n",
               k,creal(x0),cimag(x0),k,creal(f0),cimag(f0));
        k++;

        // shift the index for the next step, (1,2,3) <- (0,1,2)
        x3=x2; x2=x1; x1=x0;
        f3=f2; f2=f1; f1=f0;
        f23 = f12;

        // recompute remaining divided differences
        f12 = (f1-f2)/(x1-x2); f13 = (f1-f3)/(x1-x3);
        f123 = (f12-f23)/(x1-x3);

        // finish by computing control variables
        err = fmin( cabs(f1)/scale, cabs(x2-x1)/fabs(b-a) );
    }
    return x1;
}

int main() {
    Muller(*f, 0.808, 0.792, 0.8);
    printf("\n\nRestart\n\n");
    Muller(*f, -0.808, -0.792, -0.8);
    printf("\n\nRestart\n\n");
    Muller(*f, -1.808, -1.792, -1.8);
    return 0;
}

Log of the computation
x[ 0]=0.808000000000 +0.000000000000i,  f(x[ 0])=-1.225886093279+0.000000000000i,
x[ 1]=0.792000000000 +0.000000000000i,  f(x[ 1])=-1.305252442145+0.000000000000i,
x[ 2]=0.800000000000 +0.000000000000i,  f(x[ 2])=-1.265920000000+0.000000000000i,
x[ 3]=1.007594143502 +0.000000000000i,  f(x[ 3])=0.061333813157 +0.000000000000i,
x[ 4]=0.999691840144 +0.000000000000i,  f(x[ 4])=-0.002464329484+0.000000000000i,
x[ 5]=0.999999517022 +0.000000000000i,  f(x[ 5])=-0.000003863821+0.000000000000i,

Restart

x[ 0]=-0.808000000000+0.000000000000i,  f(x[ 0])=-11.543760711713+0.000000000000i,
x[ 1]=-0.792000000000+0.000000000000i,  f(x[ 1])=-11.245251809247+0.000000000000i,
x[ 2]=-0.800000000000+0.000000000000i,  f(x[ 2])=-11.393280000000+0.000000000000i,
x[ 3]=-0.313139488169-0.597993095065i,  f(x[ 3])=-3.578785212716-3.102850582564i,
x[ 4]=-0.152423434021-0.896568995507i,  f(x[ 4])=-2.174496945609-2.419209170588i,
x[ 5]=-0.113762245198-1.283180404737i,  f(x[ 5])=-1.974140842175-2.072205685530i,
x[ 6]=-0.590242127121-1.562744397202i,  f(x[ 6])=-1.355281768619+5.516580476110i,
x[ 7]=-0.451736511236-1.277417823451i,  f(x[ 7])=-0.401351555157-0.782834069193i,
x[ 8]=-0.493961290160-1.317349685898i,  f(x[ 8])=-0.054707398842-0.107598547954i,
x[ 9]=-0.499942023498-1.322680432217i,  f(x[ 9])=0.000220582660 -0.003039079565i,
x[10]=-0.500000033538-1.322875803330i,  f(x[10])=-0.000000312546+0.000002246640i,

Restart

x[ 0]=-1.808000000000+0.000000000000i,  f(x[ 0])=-68.773715292193+0.000000000000i,
x[ 1]=-1.792000000000+0.000000000000i,  f(x[ 1])=-66.857255669727+0.000000000000i,
x[ 2]=-1.800000000000+0.000000000000i,  f(x[ 2])=-67.809280000000+0.000000000000i,
x[ 3]=-1.182333251904-0.563769729100i,  f(x[ 3])=-10.589662224283-18.750119777722i,
x[ 4]=-0.933263172300-0.753306592649i,  f(x[ 4])=-2.028773338306-12.084168632225i,
x[ 5]=-0.707684635587-0.951498316047i,  f(x[ 5])=0.866873722369 -6.119938934357i,
x[ 6]=-0.547056458429-1.156597078482i,  f(x[ 6])=0.791543009771 -2.225497123247i,
x[ 7]=-0.493379197649-1.278355700046i,  f(x[ 7])=0.097313082739 -0.629785563704i,
x[ 8]=-0.496959319137-1.320479889960i,  f(x[ 8])=-0.029703785932-0.049268561946i,
x[ 9]=-0.499969027836-1.322900955102i,  f(x[ 9])=-0.000567484947+0.000190261047i,

Check:
$$
2x^5−2x^4+6x^3−6x^2+8x−8=2(x-1)(x^4+3x^2+4)=2(x-1)((x^2+2)^2-x^2)\\
=2(x-1)(x^2-x+2)(x^2+x+2)
$$
with roots $1$ and $\pm\frac12\pm i·\frac{\sqrt{7}}2$, independent signs for 4 roots.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Debounce implementation I'm having difficulty implementing lodash :
I'm trying to make it so that my input field triggers my check if exist API call every second after keystrokes end rather than every second.
(Ill separate the updateInput function later so that first it sets the input value then it calls the debounced API call method that I should create.)
import React, { Component } from 'react';
import _ from 'lodash';
import { Input, Row, Col } from 'reactstrap';
import loading from '../../../../img/loading.gif';

class InputTypeComponent extends Component {

    constructor(props) {
        super(props);
        const initialValue = props.value;
        this.state = {
            ...initialValue,
        };
        this.updateInput = this.updateInput.bind(this);
        this.handleProviderChange = this.handleProviderChange.bind(this);
        this.updateInput = _.debounce(this.updateInput, 1000);
    }

componentWillMount() {
    this.setState({ inputIcon: this.props.icon.inputIcon });
}

componentWillReceiveProps(newProps) {
    const response = newProps.response;
    const old = this.props.response;
    const { id, onChange } = this.props;
    if (response !== old && response.objectIdentifier === id) {
        let number = 2;
        if (response.objectName === '') {
            number = 0;
        } else if (response.activ) {
            if (response.isthere) {
                number = 4;
            } else {
                number = 3;
            }
        }
        this.setState({ inputIcon: number });
        onChange({ icon: {
            ...this.props.icon,
            inputIcon: number,
        } }, this.props.id);
    }
}

onRemove = () => {
    this.props.onRemove(this.props.id);
};

onChange = () => {
    this.props.onChange(this.props.id);
};

updateInput(event) {
    const { onChange, exists } = this.props;
    const inputValue = event.target.value.toUpperCase();
    this.setState({ input: inputValue });
    onChange({ value: {
        ...this.state,
        input: inputValue,
    } }, this.props.id);
    const placeHolder = this.props.placeholder.toLowerCase();
    const objectIdentifier = this.props.id;
    const payload = {
        objectType: placeHolder,
        objectName: inputValue,
        objectIdentifier,
        objectFisrt: '',
    };
    exists(payload);
}

render() {
    const { placeholder, provider, size } = this.props;
    const { inputIcon } = this.state;
    this.type = placeholder;
    return (
        <Row>
            <Col xs="8">
                <Row>
                    <Col xs="11">
                        <Input
                            value={this.state.input}
                            onChange={this.updateInput}
                            placeholder={placeholder}
                        />
                    </Col>
                    <Col xs="1" className="margintop noPadding">
                        {{
                            0: (

                            ),
                            1: (

                            ),
                            2: (

                            ),
                            3: (

                            ),
                            4: (

                            ),
                            default: (

                            ),
                        }[inputIcon]}
                    </Col>
                </Row>
           </Col>
      </Row>
   );
}

this broke my code now the UpdateInput function never triggers.
docs and blogs on all this are sparce so I've nowhere else to go.

A: The error message is actually pointing you at the cause of the error:

Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property target on a released/nullified synthetic event. This is set to null ... See fb.me/react-event-pooling

React manages all the DOM events for you, and as part of its internal performance optimizations it maintains a pool of events and re-uses the objects for new events as they come in.  However, when React is done passing the event through the component tree it nulls out all the fields.
When you defer updateInput lodash only calls updateInputs after React has cleared out the shared event object.
The way to fix this is to divide your method into two parts - the first that grabs the information you need off of the synthetic event and the second which actually does the work you want debounced:
constructor() {
  this.onInput = this.onInput.bind(this);
  this.updateInput = _.debounce(this.updateInput.bind(this), 1000);
}
onInput(event) {
  const inputValue = event.target.value.toUpperCase();
  this.updateInput(inputValue);
}
updateInput(inputValue) {
  // Details omitted for brevity
}


text:
Q: Angular Material Styling I can seem to style the scrollbar on the mat-option field with css. I want to make the scrollbar a different size and color. Any help or direction would be appreciated.
I tried doing this below but it didn't work.
How to change the scrollbar styles in Angular Material select?
  <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
    <mat-option *ngFor="let product of filteredProducts | async" [value]="product">
      {{ product.name }}
    </mat-option>
  </mat-autocomplete>

A: To apply style to the autocomplete panel, you simply add a class to the autocomplete element. See the docs on the 'class' @Input: https://material.angular.io/components/autocomplete/api#MatAutocomplete.
For example:
<mat-autocomplete class="custom-scroll" #auto="matAutocomplete" [displayWith]="displayFn">

And then in your global scss:
.custom-scroll.mat-autocomplete-panel {

    &::-webkit-scrollbar {
        width: 8px;
    }

    &::-webkit-scrollbar-track {
        border-radius: 4px;
        background-color: green;
    }

    &::-webkit-scrollbar-thumb {
        border-radius: 4px;
        background-color: blue;
    }
}

A: Use this if you want to change it all for scroll bars in your Angular project:
::-webkit-scrollbar {
width: 6px !important;
}
::-webkit-scrollbar-track {
border-radius: 4px !important;
background-color: #EFEFEF!important;
}
::-webkit-scrollbar-thumb {
border-radius: 4px !important;
background-color: #DCB064 !important;
}


text:
Q: Automatically saving attachments of certain emails I'm trying to write a macro to automatically save certain reports we get via email at work. Another department has something very similar in place, so I can re-use a lot of their code. However, they couldn't really explain to me what certain parts of the code do and googling it wasn't particularly helpful.
If it helps, I'll post the whole code, I left it out because a) I'd have to edit some things (names etc) and b) I don't think it's relevant to my problem.
The point of the code is that on startup the macro starts; every new email gets then checked (by sender; subject line; attachments). I struggle understanding the startup-part of the code because I'm not that experienced with VBA in general and have never used VBA in Outlook.
Option Explicit

Private WithEvents olInboxItems As Items

Private Sub Application_Startup()
  Dim objNS As NameSpace
  Set objNS = Application.Session
  Set olInboxItems = objNS.GetDefaultFolder(olFolderInbox).Folders("reports").Items
  Set objNS = Nothing
End Sub

Private Sub olInboxItems_ItemAdd(ByVal Item As Object)

If Item.Attachments.Count > 0 Then

    ….

End Sub

Questions:
Private WithEvents olInboxItems As Items - What does Private WithEvents mean or do? I know about events in VBA, like opening a workbook, but I couldn't figure out what was meant with this line.
NameSpace: Simply put, what is a NameSpace? What I read was that in Outlook there's a different structure to the object model compared to say Excel, the NameSpace is just below the application level. If that's correct, then I guess that's good enough for me, but if anyone has a neat explanation, I'd appreciate it.
Why would you Set objNS = Nothing?

A:
Private WithEvents olInboxItems As Items - What does Private WithEvents mean or do?

WithEvents Specifies one or more declared member variables refer to an instance of a class that can raise events.
To create an event handler for Microsoft Outlook objects in Microsoft Visual Basic see
Using Events with Automation MSDN
Using Outlook Visual Basic for Applications to Respond to Outlook Events MSDN

NameSpace: Simply put, what is a NameSpace?

NameSpace object (Outlook) it represents an abstract root object for any data source and accessing storage objects directly.
NameSpace object (Outlook) MSDN
good code example
Option Explicit
Private WithEvents Items As Outlook.Items

Private Sub Application_Startup()
    Dim olNs As Outlook.NameSpace
    Set olNs = Application.GetNamespace("MAPI")

    Dim Inbox  As Outlook.MAPIFolder
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
    Set Items = Inbox.Items

End Sub

Private Sub Items_ItemAdd(ByVal Item As Object)
    If TypeOf Item Is Outlook.MailItem Then
        DoEvents
        '' call another sub
    End If
End Sub

Setting Object to Nothing - https://stackoverflow.com/a/517202/4539709


text:
Q: Convert Delphi Extended to C# How to correctly convert Delphi Extended type to C# decimal?
I have tried code from this post https://stackoverflow.com/a/34550718/2550543 ,with some values it works fine, but not with all.
Example :
000000000000A08C0B40 == 4500, correct
0050AA7D3A1E33D30140 == 6,59999, correct
00D0F753E3A59BC4F73F == 25769803,776, should be 0.006
00A0703D0AD7A3B0FD3F == 1481763717,12, should be 0.345

Yep, both incorrect values ends with 3F byte, if that means something ...
Can somebody help me with that? :)
Code i have used so far :
    var extendedSize = 10;
    var buf = new byte[extendedSize];

    // Populate buffer with something like: { 0x00, 0x68, 0x66, 0x66, 0x66, 0x66, 0x66, 0xA2, 0x02, 0x40 } = 10.15
    // Read(buf, extendedSize);

    var sign = (buf[extendedSize - 1] & 0x80) == 0x80 ? -1 : 1;
    buf[extendedSize - 1] = (byte)(buf[extendedSize - 1] & 0x7F);
    var exp = BitConverter.ToUInt16(buf, extendedSize - 2);
    var integral = (buf[extendedSize - 3] & 0x80) == 0x80 ? 1 : 0;

    // Calculate mantissa
    var mantissa = 0.0;
    var value = 1.0;
    var fractal = BitConverter.ToUInt64(buf, 0);

    while (fractal != 0)
    {
        value = value / 2;
        if ((fractal & 0x4000000000000000) == 0x4000000000000000) // Latest bit is sign, just skip it
        {
            mantissa += value;
        }
        fractal <<= 1;
    }

    return sign * (1 << (exp - 16383)) * (integral + mantissa);

A:   return sign * (1 << (exp - 16383)) * (integral + mantissa);

Here be careful of your optimizations.  Left shift works as a fast power of two if the right side argument is positive.  For negative numbers this does not work as you would expect since the result of the power operation must be a floating point number for negative exponents and bit shifts will only produce an integer result.  You can recover the correct answer by removing this "optimization" :
 return sign * (Math.Pow(2, exp - 16383)) * (integral + mantissa);

I've also corrected the code in the linked answer from your question.  Do note the caveats from that answer as well - this implementation does not correctly handle denormal numbers, NaN, INF, and other special cases.  It could (should) also catch cases of extended values which are normal but fall outside the representable range of double.  It would be up to you to decide whether that is important for your use case.


text:
Q: New boost::thread causes object destructor to be called many times more than expected? Strange behavior from the code posted below causes the objects destructor to be called more than once. While the code doesn't crash as a result I just want to find out why such behavior occurs. It's a very simple template of a normal program probably used by many people all around Boost land but I've never noticed this behavior till now.
#include <boost/thread.hpp>
#include <iostream>

class object
{
    private:

        int value;

    public:

    object();
    ~object();
    void pass( int value);
};

object::object()
{
    std::cout<<"constructing object: "<<this<<" with value: "<<this->object::value<<std::endl;
}
object::~object()
{
    std::cout<<"destructing  object: "<<this<<" with value: "<<this->object::value<<std::endl;
}
void object::pass( int value)
{
    this->object::value = value;
    std::cout<<"value passed is: "<<this->object::value<<std::endl;
}

class threaded
{
    private:

         object A;

    public:

    threaded();
    ~threaded();
    void init( int value);
};
threaded::threaded(){}
threaded::~threaded(){}
void threaded::init( int value)
{
    this->threaded::A.pass( value);
}

int main()
{
    threaded T;
    int unlucky_number = 13;

    boost::thread_group tg;

    tg.add_thread( new boost::thread( boost::bind( &threaded::init, T, unlucky_number)));

    tg.join_all();

    return 0;
}

Here's the code output.
constructing object: 0x7ffcb53157f0 with value: 0

destructing  object: 0x7ffcb53156d0 with value: 0 <----From here?
destructing  object: 0x7ffcb5315720 with value: 0
destructing  object: 0x7ffcb53157a0 with value: 0
destructing  object: 0x7ffcb5315780 with value: 0
destructing  object: 0x7ffcb5315710 with value: 0
destructing  object: 0x7ffcb53157c0 with value: 0
destructing  object: 0x7ffcb5315820 with value: 0
destructing  object: 0x7ffcb5315800 with value: 0 <----To here?

value passed is: 13
destructing  object: 0x1a5f2d8 with value: 13
destructing  object: 0x7ffcb53157f0 with value: 0

The objects destroyed after the first one constructed and the before the line value passed is: 13 must have somehow been created by a copy constructor inside the boost thread library but why were they never constructed and why no crash? Plus their values are always zero so it's not junk memory... any ideas?
So at the request of G.M. I tried to create copy constructors only to get boost related errors in the error_code.hpp.
Here's the new code plus the errors compiling it.
#include <boost/thread.hpp>
#include <iostream>

class object
{
    private:

        int value;

    public:

    object();
    object( object const &copy_this);
    ~object();
    void pass( int value);
};

object::object()
{
    std::cout<<"constructing object: "<<this<<" with value: "<<this->object::value<<std::endl;
}
object::object( object const &copy_this)
{
    std::cout<<"object copy constructor. "<<std::endl;
    this->object::value = copy_this.value;
}
object::~object()
{
    std::cout<<"destructing  object: "<<this<<" with value: "<<this->object::value<<std::endl;
}
void object::pass( int value)
{
    this->object::value = value;
    std::cout<<"value passed is: "<<this->object::value<<std::endl;
}

class threaded
{
    private:

         object A;

    public:

    threaded();
    threaded( threaded const &copy_this);
    ~threaded();
    void init( int value);
};
threaded::threaded(){}
threaded::threaded( threaded const &copy_this)
{
    std::cout<<"threaded copy constructor. "<<std::endl;
    this->threaded::A = copy_this.A;
}
threaded::~threaded(){}
void threaded::init( int value)
{
    this->threaded::A.pass( value);
}

int main()
{
    threaded T;
    int unlucky_number = 13;

    boost::thread_group tg;

    tg.add_thread( new boost::thread( boost::bind( &threaded::init, T, unlucky_number)));

    tg.join_all();
    //T.init(13);

    return 0;
}

||=== Build: Debug in boost_thread_destructor_problem (compiler: GNU GCC Compiler) ===|
obj/Debug/boost_thread_destructor_problem.o||In function `__static_initialization_and_destruction_0(int, int)':|
/usr/include/boost/system/error_code.hpp|221|undefined reference to `boost::system::generic_category()'|
/usr/include/boost/system/error_code.hpp|222|undefined reference to `boost::system::generic_category()'|
/usr/include/boost/system/error_code.hpp|223|undefined reference to `boost::system::system_category()'|
obj/Debug/boost_thread_destructor_problem.o||In function `boost::thread_exception::thread_exception(int, char const*)':|
/usr/include/boost/thread/exceptions.hpp|51|undefined reference to `boost::system::system_category()'|
obj/Debug/boost_thread_destructor_problem.o||In function `boost::condition_error::condition_error(int, char const*)':|
/usr/include/boost/thread/exceptions.hpp|84|undefined reference to `boost::system::system_category()'|
obj/Debug/boost_thread_destructor_problem.o||In function `boost::detail::thread_data_base::thread_data_base()':|
/usr/include/boost/thread/pthread/thread_data.hpp|152|undefined reference to `vtable for boost::detail::thread_data_base'|
obj/Debug/boost_thread_destructor_problem.o||In function `boost::detail::interruption_checker::interruption_checker(pthread_mutex_t*, pthread_cond_t*)':|
/usr/include/boost/thread/pthread/thread_data.hpp|195|undefined reference to `boost::detail::get_current_thread_data()'|
obj/Debug/boost_thread_destructor_problem.o||In function `boost::thread::start_thread()':|
/usr/include/boost/thread/detail/thread.hpp|179|undefined reference to `boost::thread::start_thread_noexcept()'|
obj/Debug/boost_thread_destructor_problem.o||In function `boost::thread::~thread()':|
/usr/include/boost/thread/detail/thread.hpp|254|undefined reference to `boost::thread::detach()'|
obj/Debug/boost_thread_destructor_problem.o||In function `boost::thread::get_id() const':|
/usr/include/boost/thread/detail/thread.hpp|741|undefined reference to `boost::thread::native_handle()'|
obj/Debug/boost_thread_destructor_problem.o||In function `boost::thread::join()':|
/usr/include/boost/thread/detail/thread.hpp|767|undefined reference to `boost::thread::join_noexcept()'|
obj/Debug/boost_thread_destructor_problem.o||In function `boost::condition_variable::wait(boost::unique_lock<boost::mutex>&)':|
/usr/include/boost/thread/pthread/condition_variable.hpp|84|undefined reference to `boost::this_thread::interruption_point()'|
obj/Debug/boost_thread_destructor_problem.o||In function `boost::shared_mutex::lock_shared()':|
/usr/include/boost/thread/pthread/shared_mutex.hpp|186|undefined reference to `boost::this_thread::disable_interruption::disable_interruption()'|
/usr/include/boost/thread/pthread/shared_mutex.hpp|186|undefined reference to `boost::this_thread::disable_interruption::~disable_interruption()'|
/usr/include/boost/thread/pthread/shared_mutex.hpp|186|undefined reference to `boost::this_thread::disable_interruption::~disable_interruption()'|
obj/Debug/boost_thread_destructor_problem.o||In function `boost::shared_mutex::lock()':|
/usr/include/boost/thread/pthread/shared_mutex.hpp|287|undefined reference to `boost::this_thread::disable_interruption::disable_interruption()'|
/usr/include/boost/thread/pthread/shared_mutex.hpp|287|undefined reference to `boost::this_thread::disable_interruption::~disable_interruption()'|
/usr/include/boost/thread/pthread/shared_mutex.hpp|287|undefined reference to `boost::this_thread::disable_interruption::~disable_interruption()'|
obj/Debug/boost_thread_destructor_problem.o||In function `boost::thread_group::join_all()':|
/usr/include/boost/thread/detail/thread_group.hpp|117|undefined reference to `boost::thread::joinable() const'|
obj/Debug/boost_thread_destructor_problem.o||In function `boost::detail::thread_data<boost::_bi::bind_t<void, boost::_mfi::mf1<void, threaded, int>, boost::_bi::list2<boost::_bi::value<threaded>, boost::_bi::value<int> > > >::thread_data(boost::_bi::bind_t<void, boost::_mfi::mf1<void, threaded, int>, boost::_bi::list2<boost::_bi::value<threaded>, boost::_bi::value<int> > >)':|
/usr/include/boost/thread/detail/thread.hpp|109|undefined reference to `boost::detail::thread_data_base::~thread_data_base()'|
obj/Debug/boost_thread_destructor_problem.o||In function `boost::detail::thread_data<boost::_bi::bind_t<void, boost::_mfi::mf1<void, threaded, int>, boost::_bi::list2<boost::_bi::value<threaded>, boost::_bi::value<int> > > >::~thread_data()':|
/usr/include/boost/thread/detail/thread.hpp|90|undefined reference to `boost::detail::thread_data_base::~thread_data_base()'|
/usr/include/boost/thread/detail/thread.hpp|90|undefined reference to `boost::detail::thread_data_base::~thread_data_base()'|
obj/Debug/boost_thread_destructor_problem.o:(.rodata._ZTIN5boost6detail11thread_dataINS_3_bi6bind_tIvNS_4_mfi3mf1Iv8threadediEENS2_5list2INS2_5valueIS6_EENS9_IiEEEEEEEE[_ZTIN5boost6detail11thread_dataINS_3_bi6bind_tIvNS_4_mfi3mf1Iv8threadediEENS2_5list2INS2_5valueIS6_EENS9_IiEEEEEEEE]+0x10)||undefined reference to `typeinfo for boost::detail::thread_data_base'|
||error: ld returned 1 exit status|
||=== Build failed: 24 error(s), 0 warning(s) (0 minute(s), 2 second(s)) ===|

A: Due to the way you've invoked boost::bind...
tg.add_thread(new boost::thread(boost::bind(&threaded::init, T, unlucky_number)));

T will be passed by value.  That can lead to any amount of copying of T being performed by the boost::bind implementation.
Since you know that T will, in this case, outlive the thread on which it's being used you can either force a pass by reference...
tg.add_thread(new boost::thread(boost::bind(&threaded::init, boost::ref(T), unlucky_number)));

or pass a pointer...
tg.add_thread(new boost::thread(boost::bind(&threaded::init, &T, unlucky_number)));

A: You can alleviate much of this by avoiding bind. Lambdas solve this issue - most often more efficiently:
C++11
tg.create_thread([=]() mutable { T.init(unlucky_number); });

In C++14 you can be a bit more advanced:
tg.create_thread([T=std::move(T), unlucky_number = 13]() mutable { T.init(unlucky_number); });

If object is expensive to copy, consider making it move-aware, e.g.
object(object const&)       = default;
object(object&&)            = default;
object& operator=(object&&) = default;

To ensure the compiler generates the special members even though you added user-declared (non-trivial) constructor/destructor members.


text:
Q: Centering vertically collapsing menus I've been learning some things about HTML, CSS and jQuery to make my personal website. So far I was able to fix most problems I've encountered, some with the precious help of the people here. Thanks!
Here is the current code:
http://jsfiddle.net/jcml/1eyz2z6g/
I've noticed one problem:
If I try to center the menus vertically using this code adding the class "center" to the div class "links" I get a weird behavior. As can be seen here:
http://jsfiddle.net/jcml/Lz4bq7mv/
.center ul {
    top: 50%;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    transform: translateY(-50%);
}

1- How can I center the menus vertically in this situation?
I also noticed something, when using the website in the phone, when I click any link "Bla" a big box shows that selects all the submenu (the parent link and sibling blas)
2- Is there a way to change this behavior?
Also:
3- Is there a way to add an animation time for the colapsing and expanding?
Thanks

A: I had searched and found different solutions that didn't work, this one yuk posted did. Here is the result:
http://jsfiddle.net/jcml/rm5bhrm8/1
I created a container class:
.container {
    display: table;
    height: 100%;
    position: absolute;
    overflow: hidden;
    width: 100%;
}

And added this to the links class:
display: table-cell;
vertical-align: middle;

And changed the structure adding a div container class before every links class.


text:
Q: Timeline Moving very slow since upgraded to Alpha version(?) Unity I just upgraded from Unity Alpha 2019 3.0a3 to Alpha 3.0a10. Everything was working fine before the upgrading to any Alpha version. But now in my new scenes when I try to move the player-ship to create a master timeline for each new scene. The ship moves very, very slow in-game scene. Unity Engineer said this may be due to Unity still updating Alpha versions. Currently I not able to view assets I placed in scenes like rocks also.
My questions do I need to wait for until Unity completes the Alpha version updates? Or is there something I can do with my network working on my project? The project has 20 scenes but all times-lines except scene 1 and 2 moving very slow when I create it by the way scene 1 and 2 were created before upgrades to Alpha. There are no code errors in the code in scene 1 and 2 it works fine. It is the other timelines that move very slow.
I tried uninstalling Unity reverting back to the previous version using new assets. Nothing worked


text:
Q: Names of specific phobias I need help. I'm trying to find the phobia names of these fears:

*

*Fear of your own identity

*Fear of not knowing

A: I'm not sure there are unambiguous, widely used precise terms for this, but this is what I've come up with:
autophobia:

a fear of being alone or of one's self

So this one has two meanings at best, and the fear of loneliness is the better known one. However there are sources that support the second meaning as well:

Autophobia may mean one of two things. First, it could mean that a person is scared of being alone or isolated. Second, if taken literally, it could mean an irrational fear of being oneself and is associated with self-hatred. Phobia Source.

The term seems to originate from the meaning you need:

autophobia (n.) "fear of referring to oneself," 1845 (as autophoby), from Greek autos "self" (see auto-) + -phobia "fear." Related: Autophobic; autophobe. Online Etymology Dictionary

As for the other one, I'm not sure that there is a word.
Agnosiophobia can be found on the internet, but I couldn't find a proper definition. There is a play with this name, apparently about a man who has a fear of not knowing:

Night Terror Winner:
  AGNOSIOPHOBIA
  Written by Jason Gray Platt and based on a play by Giuseppe Giacosa
  Directed by Rachel Karp
  Featuring Matt Stango, Marlowe Holden, Jack Gilbert, and Ellie Phillips
  A man's curiosity threatens to destroy his family. Can he ignore the secrets of those he loves, or will his fear of not knowing consume him?
(The Flea; bold emphasis mine)

The word might catch on, but for now the only argument for using it might be considering it the opposite of
gnosiophobia, the fear of knowledge.


text:
Q: Context Menu doesn't work with there is Switch in row layout I have a ListView in my fragment with custom adapter (extended from ArrayAdapter).
list.xml:
...
    <ListView android:id="@android:id/list" android:layout_width="match_parent"
        android:layout_height="match_parent" />
...

rowlayout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="60dp">
    <TextView
        android:id="@+id/alarm_list_rowlayout_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="15dp">

    </TextView>
    <Switch
        android:id="@+id/alarm_list_rowlayout_switch_active"
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:showText="false"
        android:layout_marginRight="20dp"
        android:layout_marginTop="15dp"
        android:layout_weight="1">
    </Switch>

</LinearLayout>

fragment.java:
...
        mListView = (AbsListView) view.findViewById(android.R.id.list); //my list
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(this);
        registerForContextMenu(mListView); //set up context menu
...

If there isn't switch in rowlayout than all work fine. But if it added than nothing happened when click on row.
How to solve this problem and use context menu and switch at the same time?

A: Add
android:descendantFocusability="blocksDescendants"

to your LinearLayout.
Add
android:textIsSelectable="false"

to your TextView
Add
android:focusable="false"

to your Switch


text:
Q: Removing specific characters from the elements in an array public static String[] removeCharacters(String[] arr){

    String[] str = new String[arr.length];

    for (int i = 0; i <arr.length; i++) {
        if(Character.isLetter(arr[i].charAt(i)))
            str[i] += arr[i].charAt(i);
        else
            str[i] = "";
    }
    return str;
}

I'm trying to write a method that returns to String array and takes an String array argument.
I need remove special characters from the element and return the element without specials.

*

*For example;
["Hel123&$$o", "#$%World", "###"]
will return to

*["Hello", "World", "",] as a output.

*I also converted back to String, remove those special characters and split back again to an Array but when i convert to String it all comes together and there is no split point and I don't want to do it with Regex so i'm trying to do without it. With my solution I'm getting null so i couldn't fix.

A: Here's a changed version. You have to use a nested for loop - the first iterates over the input String[] and the nested one over the char[] in each string.
I have also used some variables in place of repeated array references for easy reading.
public class StrArray{
    public static void main( String[] args ){
        String[] input = new String[]{ "Hel123&$$o", "#$%World", "###" };
        String[] strArr = removeCharacters( input );
        Arrays.stream( strArr ).forEach( s -> System.out.println( "'" + s + "'" ) );
    }

    public static String[] removeCharacters( String[] arr ){
        String[] str = new String[ arr.length ];

        for( int i = 0; i < arr.length; i++ ){
            String input = arr[ i ];

            /* If the input string in empty, skip.*/
            int k = 0;
            if( input == null || input.length() == 0 )
                str[ i ] = "";
            else{
                /* Construct a char[] containing all the relevant chars. */
                char[] chars = new char[ input.length() ];
                for( int j = 0; j < input.length(); j++ ){
                    char c = input.charAt( j );
                    if( Character.isLetter( c ) ) chars[ k++ ] = c;
                }

                /* Now, convert the char[] into a string. */
                str[ i ] = String.valueOf( chars, 0, k );
            }
        }

        return str;
    }
}

I have quoted each string while printing. Hence, running this gives the following output.
'Helo'
'World'
''

A: The problem is that you are iterating over the array of strings but not over the array of characters of each string. You can use a loop to iterate over the array of Strings and a nested loop to iterate over the characters of each String.
Here I'm using StringBuilder to concatenate the Strings since it is more efficient than using +. This is because the String object is immutable, so each call for concatenation will create a new String object. On the other hand, StringBuilder is a mutable array of characters.
import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {

        String[] stringArray =
        new String[]{ "Hell123&$$o", "#$%World", "###" };
        System.out.println(
        Arrays.toString(removeCharacters(stringArray)));
    }

    public static String[] removeCharacters(String[] arr) {
        String[] str = new String[arr.length];

        for (int i = 0; i < arr.length; i++) {
            StringBuilder strBuilder = new StringBuilder();
            for (int j = 0; j < arr[i].length(); j++) {
                if (Character.isLetter(arr[i].charAt(j)))
                    strBuilder.append(arr[i].charAt(j));
            }
            str[i] = strBuilder.toString();
        }
        return str;
    }
}


text:
Q: what's the best media solution for java in a chat application? I'm about to make a decision about the ideal technology for audio/video chat and I need your expert advice, specifically on the client side.
java media framework doesn't seem mature enough,
fms seems ok but are there any java clients for flash media server or Red5?
any clues, guides appreciated.
thanks

A: Stick with JMF. We have exhaustively researched the alternatives at my company and its prob the best thing out there. Sure, you could use FMJ, but for security reasons, we stayed away from open source. The unfortunate truth is that you really don't have to many options.


text:
Q: Restdb.io query parent child array, get all where customer's email is jos@gmail.com When i go to my url /rest/orders i get this. I would like to select * where customer is jos@gmail.com. I can't find something in their documentation about this.
https://collectandgo-6c14.restdb.io/rest/orders?&apikey=5ad8d75725a622ae4d528439
https://restdb.io/docs/querying-with-the-api?utm_source=syndicate&utm_medium=post&utm_campaign=sitepoint-aug17#restdb

Thanks in advance,
Calvin

A: This should work:
https://collectandgo-6c14.restdb.io/rest/orders?q={"Customer":{"$elementMatch":{"email":"jos@gmail.com"}}}&apikey=5ad8d75725a622ae4d528439


text:
Q: Deploying MVC 3 application in MVC 4 hosted IIS I have created MVC 3 application, everything is working fine.
Now we moved for deployment. However the IIS 7 got already installed with MVC 4 and running other MVC 4 application.
Can I simply host my MVC 3 application? Or do I need to do any changes in web.config, or global.asax etc? Any breakdown will happen?
I developed MVC 3 with Razor.

A: You can install MVC3 and and MVC4 side by side, but you may need to follow the advice here
If you don't want to install MVC3 on the server, simply BIN deploy it and make the changes in the attached link. That way you'll risk no knock on effects to other apps.


text:
Q: Get CBUUID from device How can I get the CBUUID from the device that my app is currently running on? I'm using Xamarin but answer in objective-c or swift would be good too.

A: use  Plugin.BLE (https://www.nuget.org/packages/Plugin.BLE/)
foreach(AdvertisementRecord record in e.Device.AdvertisementRecords)
{
   if (record.Type == AdvertisementRecordType.UuidsComplete128Bit || record.Type == AdvertisementRecordType.UuidsComplete16Bit)
   {
       b.ServiceUUID = record.Data;
       break;
   }
}

Then
foreach(Beacon beacon in beaconList)
{
    cbuuidList.Add(CBUUID.FromBytes(beacon.ServiceUUID));
}

CBUUID[] uuid = cbuuidList.ToArray();
BLEManager.ScanForPeripherals(uuid);

detail here: https://forums.xamarin.com/discussion/92838/proper-way-to-retrieve-uuid-of-device


text:
Q: An example of a non-paracompact tvs (over the reals, say) What is an example of a non-paracompact topological vector space?
I'm aware of this question, but I don't care if my tvs is locally convex. In fact the wilder the better. The only criterion is that it should be contractible, which it would be, assuming $\mathbb{R} \times V \to V$ is continuous.
This is in order to answer this other question.

A: If I have not goofed on some detail, here is an example.  Let $w$ be the first uncountable ordinal (= the set of countable ordinals).  Regarded as a topological space with its usual order topology, it is not paracompact.  The space $\mathbb R^w$ with the usual product topology is a topological vector space over $\mathbb R$ in an obvious way.  Let $V$ denote the subspace $\mathbb R^w$ consisting of those functions from $w$ to $\mathbb R$ whose support is at most countable.  Then $V$ is a topological vector space over R in an obvious way.  $V$ contains a closed subset homeomorphic to $w$ (namely the set of functions $g_x$, where $g_x(y) = 1$ if $y < x$ and $0$ otherwise; the map sending $x$ in $w$ to $g_x$ is a homeomorphism onto its range).  A closed subspace of a paracompact space must be paracompact, so $V$ is not paracompact.

A: This is an old question which has been answered satisfactorily but the following remark might shed some light on it and put it in a broader context: we can embed any completely regular space as a closed subspace of a separated locally convex space in a canonical manner.  We simply provide the free vector space over the set with the finest locally convex structure so that the natural inclusion is continuous.  Hence if any topological property is stable under closed subspaces (e.g., normality, paracompactness), then whenever we can find a completely regular space which fails it, we can find a locally convex space which fails it.

A: Henno Brandsma provided this answer in a comment to anon's answer, which I think is the easiest and best, hence I'm adding it as a community wiki answer.
Consider an uncountable set $\mathfrak{n}$ and the space $\mathbb{R}^\mathfrak{n}$ in the product topology. This is not normal, but still Hausdorff, hence not paracompact.

A: I find it: http://www.jstor.org/pss/2040014


text:
Q: How to split a list to add delimiters I want to add commas as separators except for the last pair of words using python. I believe I should split the list but not sure where to start.
def main():
word = input('Enter next word or quit: ')
store_words = [word]
while word != 'quit':
    if word == 'quit':
        break
    word = input('Enter next word or quit: ')
    store_words.append(word)

store_words.remove('quit')
print(*store_words, sep=',')

main()

I've tried splitting the list, but it states that the list has no attribute split. I did more researching and some suggested to open a file and use readline.

A: After you remove 'quit' from the list, add and/or modify the following lines as you see fit.
my_string = ','.join(store_words)
index = my_string.rfind(',')
my_string = my_string[0:index] + " and " + my_string[index + 1:]
print(my_string)

Example session:
Enter next word or quit: green
Enter next word or quit: eggs
Enter next word or quit: ham
Enter next word or quit: quit
green,eggs and ham

I hope this helps. Please let me know if there are any questions.

A: For the main part of your question, try using a join command:
print(', '.join(store_words[:-1]) + " and " + store_words[-1])

Also note, that you can write your loop in fewer lines.
Having if word == 'quit': break as the first line inside your while word != 'quit': loop doesn't do anything because it will only be called when word != 'quit' is True. Instead, consider something like this:
word = input('Enter next word or quit: ')
store_words = [word]
while word != 'quit':
    word = input('Enter next word or quit: ')
    if word != 'quit':
        store_words.append(word)


text:
Q: Lollipop vs Nougat Runtime directory permission to external storage folder I have a code that runs fine in Lollipop device but don't do anything in Nougat
private ArrayList<PDFDoc> getPDFs() {
    File downloadsFolder=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    if (downloadsFolder.exists()) {
        //GET ALL FILES IN DOWNLOAD FOLDER
        File[] files = downloadsFolder.listFiles();

        //LOOP THRU THOSE FILES GETTING NAME AND URI
        for (int i = 0; i < files.length; i++) {
            File file = files[i];

            if (file.getPath().endsWith("pdf")) {
                pdfDoc = new PDFDoc();
                pdfDoc.setName(file.getName());
                pdfDoc.setPath(file.getAbsolutePath());

                pdfDocs.add(pdfDoc);
            }

        }
    }

    return pdfDocs;
}

This block runs fine with desired result in lollipop but not in Nougat, kindly help me out with genuine changes or addition.

A: Before calling the method getPDFs() you need to check whether the storage permission is granted by the user or not.
From android marshmallow, only defining the permissions in Manifest file will not work you need to ask for the permission on runtime.
So first you need to check if the device running the app is marshmallow or above. You can do it by using this code.
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
  //ask for permission here
}

For asking the runtime permission you can use the following code.
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
        Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Permission is not granted
    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {
        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    } else {
        // No explanation needed; request the permission
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
} else {
    // Permission has already been granted
}

You have to do this for the storage permission. I copied the above code from the Android Developer's Page.
For more details check Requesting App's permission

A: For this you need to add runtime permissions
private static final int REQUEST_WRITE_PERMISSION = 786;

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        //call func here
    }
  }

private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
        } else {
            //call func here
        }
      }

A: AppConstants
public static final String CAMERA_PERMISSION = CAMERA;
public static final String READ_STORAGE_PERMISSION = READ_EXTERNAL_STORAGE;
public static final String WRITE_STORAGE_PERMISSION = WRITE_EXTERNAL_STORAGE;
public static final String LOCATION_PERMISSION = ACCESS_FINE_LOCATION;
public static final String READ_PHONE_STATE_PERMISSION= READ_PHONE_STATE;

Call this Function From your (Activity OR Fragment OR Button) for checking the permissions
  //Getting permission here
public boolean needPermission() {
    try {
        int readPhoneState = ContextCompat.checkSelfPermission(this, AppConstants.READ_PHONE_STATE_PERMISSION);
        int location = ContextCompat.checkSelfPermission(this, AppConstants.LOCATION_PERMISSION);
        if (readPhoneState == PackageManager.PERMISSION_GRANTED && location == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            if (readPhoneState != PackageManager.PERMISSION_GRANTED) {
                AppGlobal.checkSinglePermission(this, AppConstants.READ_PHONE_STATE_PERMISSION);
            } else if (location != PackageManager.PERMISSION_GRANTED) {
                AppGlobal.checkSinglePermission(this, AppConstants.LOCATION_PERMISSION);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

This function will check permission type
  //Check single permission
public static boolean checkSinglePermission(final Context context, String permissionType) {
    ArrayList<String> permissionList = new ArrayList<>();
    String type = "";

    if (permissionType != null) {
        if (permissionType.equals(AppConstants.CAMERA_PERMISSION)) {
            type = permissionType;
        }
        if (permissionType.equals(AppConstants.READ_STORAGE_PERMISSION)) {
            type = permissionType;
        }
        if (permissionType.equals(AppConstants.WRITE_STORAGE_PERMISSION)) {
            type = permissionType;
        }
        if (permissionType.equals(AppConstants.READ_PHONE_STATE_PERMISSION)) {
            type = permissionType;
        }
        if (permissionType.equals(AppConstants.LOCATION_PERMISSION)) {
            type = permissionType;
        }

        int getPermission = ContextCompat.checkSelfPermission(context, type);

        if (getPermission != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(type);
            if (!permissionList.isEmpty()) {
                ActivityCompat.requestPermissions((Activity) context, permissionList.toArray
                        (new String[permissionList.size()]), SINGLE_PERMISSION_REQUEST);
                return false;
            }
        }

    }
    return true;
}

Then you will get permission success and failure  response in this onRequestPermissionsResult()
 //Permission request result here
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    for (String permission : permissions) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            AppLog.e("denied" + permission);//denied
            needPermission();//needed permission for getting Country code

        } else {
            if (ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED) {
                AppLog.e("allowed" + permission);//allowed
                needPermission();//set data
            } else {
                //set to never ask again
                AppLog.e("set to never ask again" + permission);
                AppDialog.showAlertDialog(this, null,
                        getString(R.string.read_phone_state_permission_txt), getString(R.string.txt_ok), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                                AppGlobal.permissionSettingView(LoginActivity.this);

                            }
                        });

            }
        }

    }
}


text:
Q: Flattr API gives File Not found Error I try the following example: https://api.flattr.com/rest/v2/things?id=38589
The ID Exist but I get a File Not found Error.
Something wrong in the API? I know it worked a couple of days ago.

A: The correct URL to thing with id 38589 is https://api.flattr.com/rest/v2/things/38589
And to get multiple things you separate them with a comma:
https://api.flattr.com/rest/v2/things/38589,123
I spotted a error in the documentation concerning fetching multiple things and will update it at once.


text:
Q: Send string value from an acticity without builder to normal activity I want to pass the "infor" string to the class entrar_antes_camera how can i do it?
I tried using intent but i cant put the ManagingRequests class inside the intent along the entrar_antes_camera class
public class ManagingRequests
{
    private void makeMaps()
    {
        this.mapped.put
        (
            "homeActions", //\MakeMaps.homeActions
            new ManagingRequests.Callback()
            {
                public void callback(String callback, String[] proposed_data)
                    throws Exception
                {
                    JSONObject jo = comply(proposed_data).getJSONObject(0);
                    switch( jo.getString("action") )
                    {
                        case "Notification": {
                            ManagingRequests.this.db.updateAlertas(jo.getString("codigo"));
                        }
                        break;
                        case "Register": {
                            info = entry_point.getSharedPreferences("info", MODE_PRIVATE);
                            if (info.contains("cc")) {
                                String infor = info.getString("cc", "");
                                Log.i("CC INFO", infor);
                                Intent intent = new Intent (ManagingRequests.this, entrar_antes_camera.class)
                            }else
                            ManagingRequests.this.initiateRegister();
                        }
                        break;
                        case "Mirror":
                            ManagingRequests.this.showSystemTab( Asset.TIMESHEET_SUFFIX_URL );
                        break;
                        case "Schedule":
                            ManagingRequests.this.showSystemTab( Asset.SCHEDULE_SUFFIX_URL );
                        break;
                    }
                }
            }
        );

i want to put infor in this activity
public class entrar_antes_camera extends AppCompatActivity {

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

    }
}

A: The below line is causing the problem
Intent intent = new Intent (ManagingRequests.this, entrar_antes_camera.class);

AS you are putting ManagingRequests.this as the first argument of the Intent constructor, which is not right as ManagingRequests is not considered a context as it doesn't extend from AppCompatActivity. The Intent constructor first argument expects a context instead.
So to solve this, In order to launch entrar_antes_camera.class activity, you need to add the current activity context (which is not mentioned in your question) as the first argument to the Intent Constructor instead of ManagingRequests.this.


text:
Q: Show that $\mathbb{R}P^1 \simeq S^1$ I have known for a while that $\mathbb{R}P^1 \simeq S^1$. Indeed, visually it is easy to see why this is the case (any two antipodal points define a line through the origin)
Say we now forget everything we know, and let $F$ be a division ring and let $n \ge 0$. We definie an equivalence relation of $F - \{ 0 \}$ by $x \sim y$ if there exists $\lambda \in F - \{ 0 \}$ with $x = \lambda y$. The quotient set $F^{n+1}-\{ 0 \} / \sim$ is called the F-projective n-space. The class of $x = (x_0,\ldots ,x_n)$ is denoted by $[x] = [x_0, \ldots, x_n] \in FP^n$.
Based on this definition I would like to show $\mathbb{R}P^1 \simeq S^1$
So how do we go from this definition to prove the isomorphism? I am sure it is simple...but I am not really sure where to go. Do I just use the antipodal max $f(x)=-x$? (Note the next part is to extent to show $\mathbb{H}P^1 \simeq S^4$ which is a bit harder to visualise!)

A: First, consider the mapping
$$\varphi\colon (x,y) \mapsto \left(\frac{x}{\sqrt{x^2+y^2}}, \frac{y}{\sqrt{x^2+y^2}}\right)$$
which maps $\mathbb{R}^2-\{0\}$ to the unit circle $\mathcal{C}$.
If $(x,y)$ and $(z,w)$ map to the same point, then it follows that $x = \lambda z$ and $y=\lambda w$, where
$$\lambda = \frac{\sqrt{x^2+y^2}}{\sqrt{z^2+w^2}}.$$
However, it is possible for $(x,y)$ and $(z,w)$ to satisfy $(x,y)=\lambda(z,w)$ and not to map to the same point: indeed, if $(x,y)=\lambda(z,w)$, then it is easy to see that $(x,y)$ maps to
$$\frac{\lambda}{|\lambda|}\left(\frac{z}{\sqrt{z^2+w^2}},\frac{w}{\sqrt{z^2+w^2}}\right).$$
So we define an equivalence relation on the unit circle by $\mathbf{x}\sim\mathbf{y}$ if and only if $\mathbf{x}=\pm\mathbf{y}$, and consider $\mathcal{C}^1/\sim$.
Now we consider the composition of $\varphi$ and $\pi\colon \mathcal{C}^1\to\mathcal{C}^1/\sim$. If $(x,y) =\lambda (z,w)$, then $\pi\circ\varphi(x,y) = \pi\circ\varphi(z,w)$ by the discussion above. Conversely, if $\pi\circ\varphi(x,y) = \pi\circ\varphi(z,w)$, then either $\varphi(x,y)=\varphi(z,w)$, in which case $(x,y) = \lambda(z,w)$ with $\lambda$ as above; or else $\varphi(x,y) = -\varphi(z,w)$, hence
$$(x,y) = -\frac{\sqrt{x^2+y^2}}{\sqrt{z^2+w^2}}(z,w).$$
So we conclude that $\pi\circ\varphi$ factors through $\mathbb{R}^2-\{(0,0)\}/\equiv$, where $\equiv$ is the equivalence relation on $\mathbb{R}^2=\{(0,0)\}$ given by $\mathbf{x}\equiv \mathbf{z}\Longleftrightarrow \mathbf{x}=\lambda\mathbf{z}$ for some scalar $\lambda$, and induces a bijection
$$\frac{\mathbb{R}^2-\{(0,0)\}}{\equiv} \to \mathcal{C}^1/\sim \cong S^1.$$
The maps are all continuous.

A: I suppose you want a homeomorphism between $\mathbb R\mathbb P^1$ and $S^1$. ($S^1$ does not have an algebraic structure, so isomorphism in that sense would not make sense.)
Define $\mathbb R\mathbb P^1\to S^1$ by $[a:b]\mapsto (a/\sqrt{a^2+b^2}, b/\sqrt{a^2+b^2})$ and $S^1\to \mathbb R\mathbb P^1$ by $(a,b)\mapsto [a:b]$. These are inverses to each other and hence bijective. They are both clearly continuous, so we're done.
ps: Why do you skip $\mathbb C\mathbb P^1\sim S^2$?
pps: the proof is the same in all cases including $\mathbb C$ and $\mathbb H$. You just have to figure out the dimension of each division algebra over $\mathbb R$, but it seems you already know that.

A: Just to have in mind a picture of the procedure of identifying opposite points on the circle, you can think on this:


text:
Q: F# Matching on possible generic list or sequence types I am trying figure out if a generic type wrapped in a rop result is a list or not. This is what I tried but I got errors.
let checkType (result : RopResult<'tSuccess, 'errors>) =
    match result with
    | Success (s, msg) ->
        match s with
        | :? [] -> // error here

Sample
let isList<'s> () = true
let processList (ls : 'domain list) = true
let processType (s : 'domain) = true

let checkType (result : RopResult<'tSuccess, 'errors>) =
    match result with
    | Success (s, msg) ->
        match s with
        | s when isList<s>() -> processList s
        | _ -> processType s
    | Failure (x) -> false

A: I'll first explain the technicalities of how to get your code to work, and then try to convince you (as the other folks on this thread) that it may not be the right way to approach your problem.
Firstly, your match statement has a syntax error. You would write the type test and the cast in one swoop as
match s with
| :? List<int> as theIntList -> ...do something with theIntList ...

When you add that to your code, the F# compiler will complain "The runtime coercion or type test ... involves an indeterminate type. ... Further type annotations are needed". Fix that by being more specific about what kind of result your checkType is processing: it is some System.Object instance and the message, so you'd write:
let checkType (result : Result<obj*string, 'errors>) =
    match result with
    | Success (s, msg) ->
        match s with
        | :? List<int> as theIntList -> ... do something

Note that you can't change that to a generic thing like List<_> - F# will do the type test and the cast in one go, and would not hence know what to cast to. If you try to, you will see warnings that your List<_> has been inferred to be List<obj>
Having said all that: Using obj is not the idiomatic way to go, as others have tried to point out already. The answers of @robkuz and @TheInnerLight contain all you need: A map function, functions that operate on individual result types, which then becomes nicely composable:
let map f x =
    match x with
    | Success (s, msg) -> Success (f s, msg)
    | Failure f -> Failure f

// This will automatically be inferred to be of type Result<(int list * string), 'a>
let myFirstResult = Success ([1;2], "I've created an int list")
// This will automatically be inferred to be of type Result<(string list * string), 'a>
let mySecondResult = Success (["foo"; "bar"], "Here's a string list")
// Process functions for specific result types. No type tests needed!
let processIntList (l: int list) = Seq.sum l
let processStringList = String.concat "; "
// This will automatically be inferred to be of type Result<(int * string), 'a>
let mapFirst = myFirstResult |> map processIntList
// This will automatically be inferred to be of type Result<(string * string), 'a>
let mapSecond = mySecondResult |> map processStringList

A: I am not sure if I really understand your problem.
In general if you have some polymorphic type (like your RopResult) and you want to process the polymorphic part of it a good approach in F# would be
to disentagle your code into a wrapper code and a processor code where your processor code is delivered via a higher order function for the processing part.
Example:
type RopResult<'tSuccess, 'tError> =
    | Success of 'tSuccess
    | Error of 'tError

let checkType (process: 'tSuccess -> 'tResult) (result : RopResult<'tSuccess, 'tError>) =
    match result with
    | Success s -> process s |> Success
    | Error e -> Error e

and
let processList (ls : 'domain list) = true
let processType (s : 'domain) = true

and then you
checkType processList aListWrappedInResult
checkType processType aTypeWrappedInResult

A: Assuming you wanted to determine whether a supplied value was of a generic list type, you could do this:
let isList value =
    let valueType = value.GetType()
    match valueType.IsGenericType with
    |true -> valueType.GetGenericTypeDefinition() = typedefof<_ list>
    |false -> false

Example usage:

isList [5];;
val it : bool = true
isList ["a", "b"];;
val it : bool = true
isList "a";;
val it : bool = false

When working with something like RopResult, or more formally, Either, it's helpful to define the map function.  The map function takes a function 'a -> 'b and gives you a function which operates in some elevated domain, e.g. RopResult<'a,'c> -> RopResult<'b,'c>.
This is analogous to List.map : ('a ->'b) -> 'a List -> 'b List.
We define it like this:
let map f v =
    match v with
    |Success sv -> Success (f sv)
    |Failure fv -> Failure (fv)

You can then use isList on RopResults by simply doing:
ropResult |> map isList

Others here are warning you in the comments that there may be potential issues surrounding how you actually process the results once you've determined whether the type is a list or not.  Specifically, you will need to ensure that the return types of your processList and processType functions are the same (although I would recommend revisiting the naming of processType and call it processValue instead.  Since you are not operating on the type, I think the name is confusing).


text:
Q: Triangle-geometry problem Here is the question:

$\cos(A-B) = \frac{7}{8}$, $\cos(C) = ?$
By the Law of Cosines, I get:
$AB^2 = 41-40\cos(C)$
I also tried to expand $\cos(A-B)$ by the compound angle formula, getting:

*

*$\cos(A)\cos(B) + \sin(A)\sin(B)$
Which by the Law of Sines becomes:

*

*$\cos(A)\cos(B) + \frac{5}{4} \sin(B)^2 = \frac{7}{8}$
That's where I have been able to get so far. One thing though that has been bothering me is whether $AB =3$. I am tempted to go down that way because of the Pythagorean triple $3^2 + 4^2 = 5^2$. However, they have not specified that $\angle{A} = \frac{\pi}{2}$, so I am worried about wrongly assuming it. Any assistance would be greatly appreciated.

A:
Draw $\angle BAD = \angle B$. Then $\angle CAD = \angle A - \angle B$. Say $\angle A - \angle B = \alpha$.
If $BD = x, AD = x, CD = 5 - x$.
Applying law of cosines in $\triangle CAD$,
$(5-x)^2 = x^2 + 4^2 - 2 \cdot 4 \cdot x \cdot \cos \alpha$
$25 + x^2 - 10 x = 16 + x^2 - 7x \implies x = 3$
We now know the sides of $\triangle CAD$. Applying law of cosines again, we find $ ~ \cos \angle C = \dfrac{11}{16}$.

A: You can write the angles $A$ and $B$ as follows
$ A = \left( \dfrac{A + B}{2} \right) + \left( \dfrac{A - B}{2} \right) $
and
$ B = \left( \dfrac{A + B}{2} \right) - \left( \dfrac{A - B}{2} \right ) $
The angle $\theta = \dfrac{A - B}{2}$ is known, it is
$\theta = \dfrac{1}{2} \cos^{-1} (\frac{7}{8} ) $
From the law of sines we have
$ \dfrac{\sin A}{\sin B} = \frac{5}{4} $
Hence, since $C = \pi - (A+B) $  then $\phi =  \dfrac{A + B}{2} = \dfrac{\pi - C}{2} $
$ \dfrac{\sin( \phi + \theta ) }{\sin (\phi - \theta) } = \dfrac{5}{4} $
The only unknown here is $\phi$.
Cross multiplying and expanding
$ 4 \sin (\phi + \theta ) = 5 \sin(\phi - \theta) $
$ 4 ( \sin(\phi) \cos(\theta) + \cos(\phi) \sin(\theta) ) = 5 (\sin(\phi) \cos(\theta) - \cos(\phi) \sin(\theta) )$
Collecting terms
$ \sin(\phi) \cos(\theta) = 9 \cos(\phi) \sin(\theta) $
Hence,
$ \tan(\phi) = 9 \tan(\theta) $
Now
$\theta = \frac{1}{2} \cos^{-1} \frac{7}{8} $
Therefore,
$\cos(\theta) = \sqrt{ \dfrac{1 + \frac{7}{8} }{2} } = \dfrac{\sqrt{15}}{4} $
and
$\tan(\theta) = \sqrt{ \frac{16}{15} - 1 } = \dfrac{1}{\sqrt{15}} $
Hence
$\tan(\phi) = \dfrac{9}{\sqrt{15}} $
from which
$\sec(\phi) = \sqrt{\frac{32}{5}} $
and
$\cos(\phi) = \sqrt{\frac{5}{32}} $
Thus
$\cos(2 \phi) = 2 \left( \frac{5}{32} \right) - 1 = - \dfrac{11}{16}  $
But $ 2 \phi = \pi - C $, therefore, $C = \pi - 2 \phi $
From which $\cos(C) = - \cos(2 \phi) = \boxed{\dfrac{11}{16}}$

A:
With the given 3 pieces of independent information we can construct $\triangle{ABC}$. Then $\cos \widehat{C}$ can be calculated using side lengths.
Draw the circumcircle of $ABC$, then draw its tangent from $C$ and let that tangent meet the extension of $BA$ at $D$. Then $\widehat{BDC}=\widehat{A}-\widehat{B}$
$\triangle{ADC}$ and $\triangle{BDC}$ are similar. Therefore:
$$\frac{DA}{DC} = \frac{DC}{DB} = \frac{AC}{BC} = \frac45 $$
As a result, $\frac{AB}{DB}=\frac{9}{25}$ and if we calculate $DB$ then we will have $AB$.
Now, in $\triangle{ADC}$ draw altitude $AH$. Can you take it from here?


text:
Q: jQuery Cycle Plugin Breaks in IE6 with background image I'm using the jQuery Cycle plugin along with the tutorial here: Net Tuts tutorial "building-an-auto-scrolling-slideshow-that-works-with-and-without-javascript"
It all works good if I give my containing <div> a background color, but as soon as I apply a background via url(), my slide navigation which was originally positioned absolutely to the top right gets bumped down below my slides in IE6.
It doesn't matter if I apply the background to the <div> it's currently on, or the one the slideshow actually uses, or the <ul> that contains the slides.
You can witness the problem here: http://ainsworthstudios.com/beeson/example/ looks fine in IE7 and FF, but the nav is bumped down below the slides in IE6.
I think it has something to do with the clear type fix in Cycle, but I'm not certain. Any help would be appreciated!

A: Ended up hacking it up a bit by making an additional <div> positioned directly above the old <div> in the HTML, giving that a background, and positioning both of them on top of each other to simulate the background I was hoping for originally. It's working in IE6, IE7, and FF, so hopefully that's a good enough "solution."


text:
Q: Template class with a friend function which is inside a nested namespace I'm trying to create a template class with a friend function which is inside a nested namespace. It works fine if I remove all the namespaces or if I remove all the templatization. But with both in place it won't compile. Let's look at some code:
namespace MyNamespace
{
    // Forward declaration
    template <typename Type>
    class Container;

    // Forward declaration
    namespace AccessPrivateImplementation
    {
        template <typename Type>
        Type getValue(Container<Type>* container);
    }

    // Templatized class
    template <typename Type>
    class Container
    {
        friend Type AccessPrivateImplementation::getValue(Container<Type>* volume);
    private:
        Type value;
    };

    // Friend function inside a namespace
    namespace AccessPrivateImplementation
    {
        template <typename Type>
        Type getValue(Container<Type>* container)
        {
            return container->value;
        }
    }
}

int main(int argc, char* argv[])
{
    MyNamespace::Container<int> cont;
    MyNamespace::AccessPrivateImplementation::getValue(&cont);
    return 0;
}

The compiler (VS2010) tells me:

error C2248: 'MyNamespace::Container::value' : cannot access private member declared in class 'MyNamespace::Container'

Does anyone have any idea what I'm missing?

A: The friend declaration inside the Container class template declares a friend non-template function getValue() that lives in the AccessPrivateImplementation namespace.
However, you haven't provided such a function. Instead, what you have in the AccessPrivateImplementation namespace is a function template, whose appropriate specialization you want to be friend of Container<T> (for a given T).
To achieve this, the declaration you need is:
friend Type AccessPrivateImplementation::getValue<>(Container<Type>* volume);
//                                               ^^

Here is a live example that shows your code compiling with the above fix.

A: As per my comment, if you declare the friend like so it will work:
friend Type AccessPrivateImplementation::getValue<>(Container<Type>* volume);
                                                 ^^


text:
Q: Different results using RDD and DataFrames I was creating word count of a text file using Spark RDD and DataFrame but the answers are slightly different. The data I am using is available here.
Why are the answers different?
from pyspark.sql.functions import col, trim, lower, regexp_replace, explode, split, length
 from pyspark.sql import Row

 from nltk.corpus import stopwords
 stopwords = stopwords.words('english')

DataFrame
def clean1(line):
   return trim(lower(regexp_replace(line, '[^a-zA-Z0-9\s]','')))

 df1 = (spark.read.text("Quran.txt")
   .select(clean1('value').alias('line'))
   .select(explode(split('line', ' ')).alias('word'))
   .filter(length(col("word")) > 0)
   .filter(~col('word').isin(stopwords))
   .groupBy('word').count()
   .orderBy('count', ascending = False)
  )

  df1.show(10)

RDD
 import re

 def cleanline(line):
    return re.sub('[^a-zA-Z0-9\s]', '', line).lower().strip()

df2 = (sc.textFile('Quran.txt')
   .map(lambda x: cleanline(x))
   .flatMap(lambda x: x.split(' '))
   .filter(lambda x: len(x) > 0)
   .filter(lambda x: x not in stopwords)
   .map(lambda x: (x, 1))
   .reduceByKey(lambda a, b: a + b)
   .sortBy(lambda x: -x[1])
   .map(lambda x: Row(word = x[0], count = x[1]))
   .toDF()
   .select(['word','count'])
  )

  df2.show(10)

UPdate
I found out that if I change the regular expression in the DataFrame section from '[^a-zA-Z0-9\s]' to '[^a-zA-Z0-9 ]', the answers become the same. Are these two regular expression patterns not the same?

A: If you look at the function definition of trim
'ltrim': 'Trim the spaces from left end for the specified string value.',
'rtrim': 'Trim the spaces from right end for the specified string value.',
'trim': 'Trim the spaces from both ends for the specified string column.',

which says that trim removes only spaces and not tabs (\t). but there are tabs in some of the lines as below which is not removed by trim function.
God could destroy him if He chose, v. 19 (488)

Thats the reason god in the above line is not counted as there is tab in front of it. While the strip() function removed all the spaces including tabs in the front.
Similar is the case for other counts as well.
So defining a udf function where strip() python function can be used is your solution.
from pyspark.sql import functions as F
from pyspark.sql import types as T

def stripUdf(x):
    return x.strip()

callStripUdf = F.udf(stripUdf, T.StringType())

def clean1(line):
    return callStripUdf(F.trim(F.lower(F.regexp_replace(line, '[^a-zA-Z0-9\s]',''))))

Now as you mentioned, changing from [^a-zA-Z0-9\s] to [^a-zA-Z0-9 ] solved the issue, thats because \s means all the whitespaces including tab(\t) so the change replaced tabs to empty character before trim is applied.
I hope the answer is helpful


text:
Q: Ruby ERB Page: Render two partials side by side in a for loop I'm new to Ruby ERB pages and am trying to use one to render my blog. Currently I have this for loop which renders one post per row on the blog page
<% @posts.each do |post| %>
  <%= render :partial => 'post', :locals => {:post => post} %>
<% end %>

However, since that is a for-each loop I can't access two elements in one iteration to tell the loop to render two posts side by side on each row. How can I change this for-loop to render two posts side by side on one row?

A: If you really had to output into two separate wrapper elements you would start by splitting the collection.
<% odd, even = arr.partition.with_index{ |_, i| i.even? } %>

  <% odd.each do |post| %>
    <%= render :partial => 'post', :locals => {:post => post} %>
  <% end %>

  <% even.each do |post| %>
    <%= render :partial => 'post', :locals => {:post => post} %>
  <% end %>

Thats how it would have been done circa 2008 when you based your web design off a 720 or 960px width.
Nowadays this problem is better solved with CSS.

A: If you are using Bootstrap, you can use something like this also
<% @posts.in_groups_of(2).each do |posts| %>
   <% # posts is an Array of 2 items %>

<%= render :partial => 'post', :locals => {:post => posts[0]} %>

<%= render :partial => 'post', :locals => {:post => posts[0]} %>

<% end %>


text:
Q: TypeScript: how to extract the generic parameter from a type? Say I have a type like React.ComponentClass<Props> and I want to reference the Props part but it is unnamed in my current context.
To illustrate:
const x = makeComponent(); // typeof x = React.ComponentClass<Something>

In this situation, I can use typeof x but that doesn't give me direct
access to the Something type.
What I want is something like this:
type GetPropsType<C extends React.ComponentClass<P>> = P

So that I can extract Something with the type GetPropsType<typeof x>
Anything equivalent would be great.

A: You can use pattern matching for that:
namespace React {
    export class ComponentClass<T> {}
}

function doSomethingWithProps<T>(x : React.ComponentClass<T>) : T {
    return null as T;
}

class Something {}
let comp = new React.ComponentClass<Something>();
const instanceOfSomething = doSomethingWithProps(comp);

A: You can use infer:
type TypeWithGeneric<T> = T[]
type extractGeneric<Type> = Type extends TypeWithGeneric<infer X> ? X : never

type extracted = extractGeneric<TypeWithGeneric<number>>
// extracted === number

Playground

A: Thought I'd share a real world example to extract the R generic type for MatDialogRef<T, R = any> which is Angular material's dialog box.
I often have components like this, where the output 'model' is a simple interface that isn't quite worthy of its own named type.
export class DialogPleaseWaitComponent implements OnInit {

  constructor(@Inject(MAT_DIALOG_DATA) public data: DialogPleaseWaitModel,
              public dialogRef: MatDialogRef<DialogPleaseWaitModel, { timedOut: boolean }>) {

  }

So I came up with:
extractMatDialogResponse<T>

I made it work in two 'modes', either taking the component type or the MatDialogRef itself. So I can put extractMatDialogResponse<DialogPleaseWaitComponent> and get back { timedOut: boolean } :-)
Yes - if T is the component type then it requires dialogRef to be the exact name of the property, and it does need to be public.
type extractMatDialogResponse<T = MatDialogRef<any, any> | { dialogRef: MatDialogRef<any, any> }> =
     T extends MatDialogRef<any, infer R> ? R :
     T extends { dialogRef: MatDialogRef<any, infer R> } ? R : never;

Also yes this is the same mechanism as used by Xiv, but demonstrates how to make a 'targeted' extractor for a specific use.


text:
Q: Pandas storing NaN value when adding new column to existing DataFrame Reading .xls files that contains Brazilian population estimates since 2000,
I start with the 2000.xls file populating a dataframe called main_df that at first looks like
STATE    STATE_CODE    CITY       CITY_CODE      2000_POPSP       X             Sao Paulo  Y              10.000.000
...

After iterating over *.xls files from 2001 until 2020 main_df should look like:
STATE    STATE_CODE    CITY       CITY_CODE      2000_POP     2001_POP  2002_POP   ...  2020_POP
SP       X             Sao Paulo  Y              10.000.000   m         n          ...  p
...
To make it happen I'm using Pandas in a not very efficient way, iterating over df rows, but anyhow that was the way I found to find the population size looking for the city and state codes.
Being df the dataframes that represents city population estimates for 2001 ~ 2020.
Here's the code snippet that iterates over every df rows trying to populate main_df:
df = pd.read_excel(filename, encoding='latin_1', sep=',')

column_year_id = filename.strip('.xls')
df.columns = ['STATE', 'STATE_CODE', 'CITY', 'CITY_CODE', column_year_id]

for index, row in df.iterrows():
    target_uf = (row['STATE_CODE'])
    target_city_code = (str(row['CITY_CODE']))
    population_on_current_year = row[-1]

    selection = (main_df['STATE_CODE'] == target_uf) & (main_df['CITY_CODE'] == target_city_code)

    main_df.loc[selection, column_year_id] = population_on_current_year

The problem is that at the end of the day main_df ends up with only its original 2000 population size column filled, but, from 2001 to 2020 its filled with NaN values looking like:
STATE    STATE_CODE    CITY       CITY_CODE      2000_POP     2001_POP  2002_POP   ...  2020_POP
SP       X             Sao Paulo  Y              10.000.000   NaN       NaN        ...  NaN
...
Why is it happening and what should I do to make it work?
It seems that the problem is because I am not able to insert an element to an specific position like if main_df was an array using main_df[index, column]. Does Pandas allows this kind of insertion?
Edit 1:
This is how I create main_df:
main_df = pd.read_excel(filename, encoding='latin_1', sep=',')

A: I got able to do what I wish with:
selection = (main_df['COD_UF'] == target_state) & (main_df['COD_MUN'] == target_city)
index = main_df.loc[selection].index
main_df.loc[index.values[0], column_year_id] = population_on_current_year


text:
Q: un-reset css properties when I used css reset? I use CKEditor for my text editor, when client edit a text with CKEditor and change the font color, font size and ... I store the HTML code in my database and there is no problem.
but when I want to show the HTML Code in my page, the style will reset so many html tags not work, like font size or font color and ...
I use Eric Meyer's "Reset CSS" 2.0 :
http://meyerweb.com/eric/tools/css/reset/
this is CKEditor WYSIWYG screenshot :

This is CKEditor HTML Code :

And this is result :

and this is firebug screen shot for this layer style :

I need to un-reset the CSS for this layer, is it possible ?

A: You should be able to do this with the CSS :not selector, by resetting all the elements that are not within the WSYIWYG Editor code.
Or, if you have control over the styles, you could an !important declaration on the editor styles.

A: You may consider using http://binarystash.blogspot.com/2014/01/unresetcss.html. It restores default HTML styles removed by Eric Meyer's reset.css.


text:
Q: How to increase the number of text in Android programmatically I have a page in which I'm taking the START TIME and END TIME from DATABASE.
Let's say the START TIME is 7:00 and END TIME is 22:00
I want to use this START TIME and END TIME to show in my page as textview like 7:00    8:00   9:00 and sooo on till 22:00  as textview
Also I have an imageview that will also increase when the text increases.
How can I achieve this?
Also I want the result text in Horizontal Scroll View with Imageview at top and text view as bottom of each imageview
char first = StartTime.charAt(0);

int StartTimeint = Integer.parseInt(String.valueOf(first));

int l;
for( l = StartTimeint; l<=22; l++){
    Log.d("SeatsPage", "Time is "+l);
}

timeofseats.setText(Integer.toString(l));

This is I have done so far but I'm getting 23 as a result, the textview is not increasing
This is my XML File
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/llMain"
    android:layout_height="match_parent"
    tools:context=".SeatsPagewithDB.SeatsPage">

    <ImageView
        android:id="@+id/imageView11"
        android:layout_width="150px"
        android:layout_height="150px"
        android:layout_marginStart="28dp"
        android:layout_marginEnd="326dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/seat" />

    <TextView
        android:id="@+id/timeofseats"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="40dp"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="334dp"
        android:background="#FF0000"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:text="7:00"
        android:textColor="#fff"
        android:textSize="20dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView11" />

</android.support.constraint.ConstraintLayout>

This is the result I am getting as layout
This what I want programmatically

A: The XML code that you write in your layout.xml file to create the UI is for static UI only. What you are asking is to create views dynamically during runtime. Although you can definitely create views using java code on a click of a button or something. But it is better to code less for the UI whenever possible and keep it separated from the program code. Instead use the tools given to us by the framework we are using.
In Android those tools include stuff like ListView, GridView and the newer and better RecyclerView. These views help you add other views dynamically to your UI in runtime. You define one of them or more (depending on your UI needs) once in your layout.xml and configure them using java code like any other view.
This is how you can use RecyclerView to achieve your goal. I can't explain everything how RecyclerView works and what each line of code does as it will make a very long post but I have tried to highlight main things briefly.
1. Add RecyclerView in your layout file.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

2. Create another layout file and define the template UI of the item that the RecyclerView is going to display. RecyclerView will populate each item that it holds with this layout.
item_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView_alarm"
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:src="@drawable/alarm" />

    <TextView
        android:id="@+id/textView_Time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:background="#FF0000"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:text="Time"
        android:textColor="@android:color/background_light"
        android:textSize="24sp" />
</LinearLayout>

3. Create a ViewHolder class that extends from RecyclerView.ViewHolder. View holder is a RecyclerView related concept. In short it works as a wrapper around the view of a single item and aids in binding new data to the view of the item. Create a bind() function inside view holder to make your life easier.
EDIT: I have updated the class by implementing the View.OnClickListener interface, modified the constructor to pass in the context from onCreateViewHolder() and adding a setItemPosition() just for the sake to pass the item position number from onBindViewHolder() all over to here so we can use this position number in our onClick() method of the interface
MyViewHolder.java [UPDATED]
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    private TextView textView;
    private int itemPosition;
    private Context mContext;

    public MyViewHolder(@NonNull View itemView, Context context) {
        super(itemView);

        itemView.setOnClickListener(this);

        mContext = context;
        textView = itemView.findViewById(R.id.textView_Time);
    }

    void bind(String timeText)
    {
        textView.setText(timeText);
    }

    void setItemPosition(int position)
    {
        itemPosition = position;
    }

    @Override
    public void onClick(View v) {

        Toast.makeText(mContext, "You clicked item number: " + itemPosition , Toast.LENGTH_SHORT).show();

    }
}

4. Create an Adapter class that extends from RecyclerView.Adapter. Adapter works as a bridge between the UI data and RecyclerView itself. An Adapter tells the RecyclerView what layout file to inflate and how many to inflate. RecyclerView job is to deal with how to inflate it on the UI.
EDIT : Just changed myViewHolder in onCreateViewHolder() to match the modified constructor of MyViewHolder. Added the call to setItemPosition() in the onBindViewHolder().
MyAdapter.java [UPDATED]
public class MyAdapter extends RecyclerView.Adapter {

    List<String> timeIntervalList = new ArrayList<>();

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

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, parent, false);
        MyViewHolder myViewHolder = new MyViewHolder(view , parent.getContext());

        return myViewHolder;
    }

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

        MyViewHolder viewHolder = (MyViewHolder) holder;

        viewHolder.setItemPosition(position);
        viewHolder.bind(timeIntervalList.get(position));

    }

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

    public void addItem (String timeText)
    {
        timeIntervalList.add(timeText);
        notifyItemInserted(getItemCount());
    }
}

In this adapter you will see two functions. OnCreateViewHolder() inflates the view using the template layout file for a single item and OnBindViewHolder() binds new data to the default values of the of the view just created. The data used for binding is stored in a list inside this Adapter called the timeIntervalList. This list will hold your time interval strings so they can be updated on the view.
5. Finally, use this RecyclerView where you want to use it. Like in your MainActivity.java. RecyclerView needs to be told in what fashion to display the items (e.g list , grid etc ) using a LayoutManager. LinearLayoutManager will display items either vertically or horizontally. You can see I am using your logic to increment time from string and adding new views to RecyclerView using the addItem() function of the MyAdapter class.
MainActivity.java
public class MainActivity extends AppCompatActivity {

    private RecyclerView myRecyclerView;
    private MyAdapter myAdapter;

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

        myRecyclerView = findViewById(R.id.recyclerView);
        myAdapter = new MyAdapter();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this , LinearLayoutManager.HORIZONTAL, false);

        myRecyclerView.setLayoutManager(linearLayoutManager);
        myRecyclerView.setAdapter(myAdapter);

        // This is how you will populate the recycler view

        String START_TIME  = "7:00";
        String END_TIME = "22:00";

        char first = START_TIME.charAt(0);

        int StartTimeint = Integer.parseInt(String.valueOf(first));

        int l;
        for( l = StartTimeint; l<=22; l++){

            // This is where new item are added to recyclerView.
            myAdapter.addItem(l + ":00");

        }

    }
}

This is the final result.

A: Change your activity layout XML code as follows,
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/llMain"
    android:layout_height="match_parent"
    tools:context=".SeatsPagewithDB.SeatsPage">

    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ...
        ...>

        <LinearLayout
            android:id="@+id/container"
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </HorizontalScrollView>

</android.support.constraint.ConstraintLayout>

Move the textview and imageview to another XML file let's call it item_view.xml (you can name it whatever you wish). we are doing so because the root view of this file will be reused.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/imageView11"
        android:layout_width="150px"
        android:layout_height="150px"
        app:srcCompat="@drawable/seat"/>

    <TextView
        android:id="@+id/timeofseats"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#FF0000"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:text="7:00"
        android:textColor="#fff"
        android:textSize="20dp"/>

</LinearLayout>

Now make following changes in your Java file
    LinearLayout container = findViewById(R.id.container); // or rootView.findViewById() for custom View and Fragment

    char first = StartTime.charAt(0);

    int StartTimeint = Integer.parseInt(String.valueOf(first));

    for(int l = StartTimeint; l<=22; l++){
        Log.d("SeatsPage", "Time is "+l);
        View view = LayoutInflater.from(container.getContext()).inflate(R.layout.item_view, null);
        TextView timeofseats = view.findViewById(R.id.timeofseats);
        timeofseats.setText(Integer.toString(l));
        container.addView(view);
    }