问:
Uncaught TypeError: Cannot read property 'id' of undefined in shopify custom cart popup jQuery ajax
I get error in my jQuery AJAX code. Uncaught TypeError: Cannot read property 'id' of undefined. I don't understand how I can fix this. When I try to add product by click in variant this error is showing. Here is my shopify development site. Below is my jQuery code.

```<code>$('.varients-item').on('click', function(){
    var obj = $(this);
    var variants_id = $(this).attr("data-variant");
    $.ajax({
        type: 'POST',
        url: '/cart/add.js',
        data: {
            quantity: 1,
            id: variants_id
        },
        dataType: 'json',
        success: function (data) {
            $.ajax({
                type: 'GET',
                dataType: 'jsonp',
                url: '/cart.json',
                success: function(cart){

                    var item_count = cart['item_count'];
                    var total_price = cart['total_price']/100;

                    //If there are items in cart
                    if ( item_count > 0 ) {
                        // cart count
                        $('.cart-item-count span').text(item_count);

                        // mini cart data
                        $('.cart-popup').attr('id','cartPopup');
                        $('.cartpopup-total .price').text( '£' + total_price.toFixed(2) );

                        var cart_list = [];

                        for( var i = 0; i < item_count; i++ ){
                            if ( cart['items'][i]['id'] != null ) {
                                var item_id = cart['items'][i]['id'];
                                var product_title = cart['items'][i]['product_title'];
                                // var product_title = data['items'][i]['title'];
                                var product_handle = cart['items'][i]['handle'];
                                var quantity = cart['items'][i]['quantity'];
                                var line_price = cart['items'][i]['price']/100;
                                var url = cart['items'][i]['url'];
                                var image_url = cart['items'][i]['image'];
                                var variants = cart['items'][i]['variant_options'];

                                if ( product_title == 'Gift Wrap' ) {
                                    var product_url = product_title;
                                } else {
                                    var product_url = '<a href="' + url + '">' + product_title + '</a>';
                                }

                                var options = [];
                                for ( var o = 0; o < variants.length; o++ ) {
                                    var selected = cart['items'][i]['variant_options'][o];
                                    if ( selected !== 'Default Title' ) {
                                        options.push( selected + '<br>' );
                                    }
                                };
                                var selected_options = options.join('');

                                cart_list.push(
                                    '<div class="cartpopup-item d-flex flex-row">'+
                                        '<div class="cartpopup-item-image">'+
                                            '<a href="' + url + '">'+
                                                '<img class="img-fluid d-block" src="' + image_url + '"  alt="' + product_title + '" />'+
                                            '</a>'+
                                        '</div>'+
                                        '<div class="cartpopup-item-content d-flex flex-column">'+
                                            '<h5>' + product_url + '</h5>'+
                                            '<span class="variant">' + selected_options + '</span>'+
                                            '<span class="price">£' + total_price.toFixed(2) + '</span>'+
                                            '<div class="quantity-box d-flex flex-row">'+
                                                '<button class="quantity-button qminus" role="button" type="button" data-variant="' + item_id + '"><i class="fal fa-minus"></i></button>'+
                                                '<input class="quantity-input" type="number" disabled name="updates[]" id="updates_' + item_id + '" value="' + quantity + '" min="1" />'+
                                                '<button class="quantity-button qplus" role="button" type="button" data-variant="' + item_id + '"><i class="fal fa-plus"></i></button>'+
                                            '</div>'+
                                            '<div class="d-flex flex-row">'+
                                                '<a class="remove" data-cart-remove-id="' + item_id + '" href="/cart/change?line=' + item_count + '&quantity=0">Remove</a>'+
                                            '</div>'+
                                        '</div>'+
                                    '</div>'
                                );
                            } //endif
                        }; // endfor

                        $('.cartpopup-body').html( cart_list.join('') );
                    }
                    $('.cart-popup').addClass('active');
                    $('body').addClass('cartpopup-active');
                    $('body').append(
                        '<div class="popupbackdrop"></div>'
                    );
                }
            });
        }
    });
});
</code>```

This error will show when try to add same variant two times on click in variant button. When remove all products from cart and refresh page then add product again it will work perfectly.

I'm struggling about this issue in many days but no success.

答:
As stated in the comments, this is a common problem where you are trying to access the data that is not available. In this scenario, the reason behind this is your misinterpretation of item_count variable in Shopify cart. If you have a look at Shopify AJAX API reference, item_count is the total number of items in your cart. For example, you may have item_count as 3 while only 1 object in items array with quantity 3. However, you code does not handle this case and always assume that number of objects will always be equal to item_count. Moreover, to iterate over the array, don't rely on item_count but on items array length. Doing so, your code will be like

```<code>$('.varients-item').on('click', function(){
    var obj = $(this);
    var variants_id = $(this).attr("data-variant");
    $.ajax({
        type: 'POST',
        url: '/cart/add.js',
        data: {
            quantity: 1,
            id: variants_id
        },
        dataType: 'json',
        success: function (data) {
            $.ajax({
                type: 'GET',
                dataType: 'jsonp',
                url: '/cart.json',
                success: function(cart){
                    // change the below line
                    var item_count = cart['items'].length;
                    var total_price = cart['total_price']/100;

                    //If there are items in cart
                    if ( item_count > 0 ) {
                        // cart count
                        $('.cart-item-count span').text(item_count);

                        // mini cart data
                        $('.cart-popup').attr('id','cartPopup');
                        $('.cartpopup-total .price').text( '£' + total_price.toFixed(2) );

                        var cart_list = [];

                        for( var i = 0; i < item_count; i++ ){
                            if ( cart['items'][i]['id'] != null ) {
                                var item_id = cart['items'][i]['id'];
                                var product_title = cart['items'][i]['product_title'];
                                // var product_title = data['items'][i]['title'];
                                var product_handle = cart['items'][i]['handle'];
                                var quantity = cart['items'][i]['quantity'];
                                var line_price = cart['items'][i]['price']/100;
                                var url = cart['items'][i]['url'];
                                var image_url = cart['items'][i]['image'];
                                var variants = cart['items'][i]['variant_options'];

                                if ( product_title == 'Gift Wrap' ) {
                                    var product_url = product_title;
                                } else {
                                    var product_url = '<a href="' + url + '">' + product_title + '</a>';
                                }

                                var options = [];
                                for ( var o = 0; o < variants.length; o++ ) {
                                    var selected = cart['items'][i]['variant_options'][o];
                                    if ( selected !== 'Default Title' ) {
                                        options.push( selected + '<br>' );
                                    }
                                };
                                var selected_options = options.join('');

                                cart_list.push(
                                    '<div class="cartpopup-item d-flex flex-row">'+
                                        '<div class="cartpopup-item-image">'+
                                            '<a href="' + url + '">'+
                                                '<img class="img-fluid d-block" src="' + image_url + '"  alt="' + product_title + '" />'+
                                            '</a>'+
                                        '</div>'+
                                        '<div class="cartpopup-item-content d-flex flex-column">'+
                                            '<h5>' + product_url + '</h5>'+
                                            '<span class="variant">' + selected_options + '</span>'+
                                            '<span class="price">£' + total_price.toFixed(2) + '</span>'+
                                            '<div class="quantity-box d-flex flex-row">'+
                                                '<button class="quantity-button qminus" role="button" type="button" data-variant="' + item_id + '"><i class="fal fa-minus"></i></button>'+
                                                '<input class="quantity-input" type="number" disabled name="updates[]" id="updates_' + item_id + '" value="' + quantity + '" min="1" />'+
                                                '<button class="quantity-button qplus" role="button" type="button" data-variant="' + item_id + '"><i class="fal fa-plus"></i></button>'+
                                            '</div>'+
                                            '<div class="d-flex flex-row">'+
                                                '<a class="remove" data-cart-remove-id="' + item_id + '" href="/cart/change?line=' + item_count + '&quantity=0">Remove</a>'+
                                            '</div>'+
                                        '</div>'+
                                    '</div>'
                                );
                            } //endif
                        }; // endfor

                        $('.cartpopup-body').html( cart_list.join('') );
                    }
                    $('.cart-popup').addClass('active');
                    $('body').addClass('cartpopup-active');
                    $('body').append(
                        '<div class="popupbackdrop"></div>'
                    );
                }
            });
        }
    });
});
</code>```

Body:
I get error in my jQuery AJAX code. Uncaught TypeError: Cannot read property 'id' of undefined. I don't understand how I can fix this. When I try to add product by click in variant this error is showing. Here is my shopify development site. Below is my jQuery code.

$('.varients-item').on('click', function(){
    var obj = $(this);
    var variants_id = $(this).attr("data-variant");
    $.ajax({
        type: 'POST',
        url: '/cart/add.js',
        data: {
            quantity: 1,
            id: variants_id
        },
        dataType: 'json',
        success: function (data) {
            $.ajax({
                type: 'GET',
                dataType: 'jsonp',
                url: '/cart.json',
                success: function(cart){

                    var item_count = cart['item_count'];
                    var total_price = cart['total_price']/100;

                    //If there are items in cart
                    if ( item_count > 0 ) {
                        // cart count
                        $('.cart-item-count span').text(item_count);

                        // mini cart data
                        $('.cart-popup').attr('id','cartPopup');
                        $('.cartpopup-total .price').text( '£' + total_price.toFixed(2) );

                        var cart_list = [];

                        for( var i = 0; i < item_count; i++ ){
                            if ( cart['items'][i]['id'] != null ) {
                                var item_id = cart['items'][i]['id'];
                                var product_title = cart['items'][i]['product_title'];
                                // var product_title = data['items'][i]['title'];
                                var product_handle = cart['items'][i]['handle'];
                                var quantity = cart['items'][i]['quantity'];
                                var line_price = cart['items'][i]['price']/100;
                                var url = cart['items'][i]['url'];
                                var image_url = cart['items'][i]['image'];
                                var variants = cart['items'][i]['variant_options'];

                                if ( product_title == 'Gift Wrap' ) {
                                    var product_url = product_title;
                                } else {
                                    var product_url = '' + product_title + '';
                                }

                                var options = [];
                                for ( var o = 0; o < variants.length; o++ ) {
                                    var selected = cart['items'][i]['variant_options'][o];
                                    if ( selected !== 'Default Title' ) {
                                        options.push( selected + '
' );
                                    }
                                };
                                var selected_options = options.join('');

                                cart_list.push(
                                    '
'+
                                        '
'+
                                            ''+
                                                ''+
                                            ''+
                                        '
'+
                                        '
'+
                                            '
' + product_url + '
'+
                                            '' + selected_options + ''+
                                            '£' + total_price.toFixed(2) + ''+
                                            '
'+
                                                '<button class="quantity-button qminus" role="button" type="button" data-variant="' + item_id + '"></button>'+
                                                '<input class="quantity-input" type="number" disabled name="updates[]" id="updates_' + item_id + '" value="' + quantity + '" min="1" />'+
                                                '<button class="quantity-button qplus" role="button" type="button" data-variant="' + item_id + '"></button>'+
                                            '
'+
                                            '
'+
                                                'Remove'+
                                            '
'+
                                        '
'+
                                    '
'
                                );
                            } //endif
                        }; // endfor

                        $('.cartpopup-body').html( cart_list.join('') );
                    }
                    $('.cart-popup').addClass('active');
                    $('body').addClass('cartpopup-active');
                    $('body').append(
                        '

'
                    );
                }
            });
        }
    });
});

This error will show when try to add same variant two times on click in variant button. When remove all products from cart and refresh page then add product again it will work perfectly.

I'm struggling about this issue in many days but no success.

Body:
As stated in the comments, this is a common problem where you are trying to access the data that is not available. In this scenario, the reason behind this is your misinterpretation of item_count variable in Shopify cart. If you have a look at Shopify AJAX API reference, item_count is the total number of items in your cart. For example, you may have item_count as 3 while only 1 object in items array with quantity 3. However, you code does not handle this case and always assume that number of objects will always be equal to item_count. Moreover, to iterate over the array, don't rely on item_count but on items array length. Doing so, your code will be like

$('.varients-item').on('click', function(){
    var obj = $(this);
    var variants_id = $(this).attr("data-variant");
    $.ajax({
        type: 'POST',
        url: '/cart/add.js',
        data: {
            quantity: 1,
            id: variants_id
        },
        dataType: 'json',
        success: function (data) {
            $.ajax({
                type: 'GET',
                dataType: 'jsonp',
                url: '/cart.json',
                success: function(cart){
                    // change the below line
                    var item_count = cart['items'].length;
                    var total_price = cart['total_price']/100;

                    //If there are items in cart
                    if ( item_count > 0 ) {
                        // cart count
                        $('.cart-item-count span').text(item_count);

                        // mini cart data
                        $('.cart-popup').attr('id','cartPopup');
                        $('.cartpopup-total .price').text( '£' + total_price.toFixed(2) );

                        var cart_list = [];

                        for( var i = 0; i < item_count; i++ ){
                            if ( cart['items'][i]['id'] != null ) {
                                var item_id = cart['items'][i]['id'];
                                var product_title = cart['items'][i]['product_title'];
                                // var product_title = data['items'][i]['title'];
                                var product_handle = cart['items'][i]['handle'];
                                var quantity = cart['items'][i]['quantity'];
                                var line_price = cart['items'][i]['price']/100;
                                var url = cart['items'][i]['url'];
                                var image_url = cart['items'][i]['image'];
                                var variants = cart['items'][i]['variant_options'];

                                if ( product_title == 'Gift Wrap' ) {
                                    var product_url = product_title;
                                } else {
                                    var product_url = '<a href="' + url + '">' + product_title + '</a>';
                                }

                                var options = [];
                                for ( var o = 0; o < variants.length; o++ ) {
                                    var selected = cart['items'][i]['variant_options'][o];
                                    if ( selected !== 'Default Title' ) {
                                        options.push( selected + '<br>' );
                                    }
                                };
                                var selected_options = options.join('');

                                cart_list.push(
                                    '<div class="cartpopup-item d-flex flex-row">'+
                                        '<div class="cartpopup-item-image">'+
                                            '<a href="' + url + '">'+
                                                '<img class="img-fluid d-block" src="' + image_url + '"  alt="' + product_title + '" />'+
                                            '</a>'+
                                        '</div>'+
                                        '<div class="cartpopup-item-content d-flex flex-column">'+
                                            '<h5>' + product_url + '</h5>'+
                                            '<span class="variant">' + selected_options + '</span>'+
                                            '<span class="price">£' + total_price.toFixed(2) + '</span>'+
                                            '<div class="quantity-box d-flex flex-row">'+
                                                '<button class="quantity-button qminus" role="button" type="button" data-variant="' + item_id + '"><i class="fal fa-minus"></i></button>'+
                                                '<input class="quantity-input" type="number" disabled name="updates[]" id="updates_' + item_id + '" value="' + quantity + '" min="1" />'+
                                                '<button class="quantity-button qplus" role="button" type="button" data-variant="' + item_id + '"><i class="fal fa-plus"></i></button>'+
                                            '</div>'+
                                            '<div class="d-flex flex-row">'+
                                                '<a class="remove" data-cart-remove-id="' + item_id + '" href="/cart/change?line=' + item_count + '&amp;quantity=0">Remove</a>'+
                                            '</div>'+
                                        '</div>'+
                                    '</div>'
                                );
                            } //endif
                        }; // endfor

                        $('.cartpopup-body').html( cart_list.join('') );
                    }
                    $('.cart-popup').addClass('active');
                    $('body').addClass('cartpopup-active');
                    $('body').append(
                        '<div class="popupbackdrop"></div>'
                    );
                }
            });
        }
    });
});


来源: stackexchange

问:
my code for remove @user and punctuation does not work
I wrote the code below for tweets data set, I want to do preprocessing, I have removed #, website  but my code for remove @user and punctuation does not work ,im new to python can any one help me? </p>

```<code>from nltk.corpus import stopwords
import spacy, re

nlp = spacy.load('en')

stop_words = [w.lower() for w in stopwords.words()]

def sanitize(input_string):
    """ Sanitize one string """

    # normalize to lowercase
    string = input_string.lower()

    # spacy tokenizer
    string_split = [token.text for token in nlp(string)]

    # in case the string is empty
    if not string_split:
        return ''

    names = re.compile('@[A-Za-z0-9_][A-Za-z0-9_]+')
    string = [re.sub(names, '@USER', tweet) for tweet in input_string()]

    #remove # and @
    for punc in '":!#':
       string = string.replace(punc, '')

    # remove 't.co/' links
    string = re.sub(r'http//t.co\/[^\s]+', '', string, flags=re.MULTILINE)

    # removing stop words
    string = ' '.join([w for w in string.split() if w not in stop_words])

#punctuation
   # string = [''.join(w for w in string.split() if w not in #string.punctuation) for w in string]

    return string

list = ['@Jeff_Atwood Thank you for #stackoverflow', 'All hail @Joel_Spolsky t.co/Gsb7V1oVLU #stackoverflow' ]

list_sanitized = [sanitize(string) for string in tweets[:300]]
list_sanitized[:50]
</code>```

答:
The regex needs to be fixed. Try something like:

names = re.compile('@[A-Za-z0-9_]+')
string = re.sub(names, '@USER', input_string)
```

input_string is a variable and not a function, it's also a singular string so you don't want to traverse over it. This will work just fine shown here: https://regexr.com/55u44

Your punctuation removal works just fine, see: https://ideone.com/zScVPJ

ContentLicense: CC BY-SA 4.0

Body:
I wrote the code below for tweets data set, I want to do preprocessing, I have removed #, website  but my code for remove @user and punctuation does not work ,im new to python can any one help me?

from nltk.corpus import stopwords
import spacy, re

nlp = spacy.load('en')

stop_words = [w.lower() for w in stopwords.words()]

def sanitize(input_string):
    """ Sanitize one string """

    # normalize to lowercase
    string = input_string.lower()

    # spacy tokenizer
    string_split = [token.text for token in nlp(string)]

    # in case the string is empty
    if not string_split:
        return ''

    names = re.compile('@[A-Za-z0-9_][A-Za-z0-9_]+')
    string = [re.sub(names, '@USER', tweet) for tweet in input_string()]

    #remove # and @
    for punc in '":!#':
       string = string.replace(punc, '')

    # remove 't.co/' links
    string = re.sub(r'http//t.co\/[^\s]+', '', string, flags=re.MULTILINE)

    # removing stop words
    string = ' '.join([w for w in string.split() if w not in stop_words])

#punctuation
   # string = [''.join(w for w in string.split() if w not in #string.punctuation) for w in string]

    return string

list = ['@Jeff_Atwood Thank you for #stackoverflow', 'All hail @Joel_Spolsky t.co/Gsb7V1oVLU #stackoverflow' ]

list_sanitized = [sanitize(string) for string in tweets[:300]]
list_sanitized[:50]

Body:
The regex needs to be fixed. Try something like:

names = re.compile('@[A-Za-z0-9_]+')
string = re.sub(names, '@USER', input_string)

input_string is a variable and not a function, it's also a singular string so you don't want to traverse over it. This will work just fine shown here: https://regexr.com/55u44

Your punctuation removal works just fine, see: https://ideone.com/zScVPJ


问:
AS3: How to convert a Vector to an Array
What's the nicest way to convert a Vector to an Array in Actionscript3?

The normal casting syntax doesn't work:

```<code>var myVector:Vector.<Foo> = new Vector();
var myArray:Array = Array(myVector); // calls the top-level function Array()
</code>```

due to the existance of the Array function. The above results in an array, but it's an array with a single element consisting of the original Vector.

Which leaves the slightly more verbose:

```<code>var myArray:Array = new Array();
for each (var elem:Foo in myVector) {
    myArray.push(elem);
}
</code>```

which is fine, I guess, though a bit wordy. Is this the canonical way to do it, or is there a toArray() function hiding somewhere in the standard library?

答: var a:Array = some_vector as Array;</p>

ContentLicense: CC BY-SA 2.5

Body:
What's the nicest way to convert a Vector to an Array in Actionscript3?

The normal casting syntax doesn't work:

var myVector:Vector.<Foo> = new Vector();
var myArray:Array = Array(myVector); // calls the top-level function Array()

due to the existance of the Array function. The above results in an array, but it's an array with a single element consisting of the original Vector.

Which leaves the slightly more verbose:

var myArray:Array = new Array();
for each (var elem:Foo in myVector) {
    myArray.push(elem);
}

which is fine, I guess, though a bit wordy. Is this the canonical way to do it, or is there a toArray() function hiding somewhere in the standard library?

Body: var a:Array = some_vector as Array;

ContentLicense: CC BY-SA 3.0


问:
python API coding for tidal music
Hi currently a student working on a project for school.

I'm looking to use a music API to work with, and have found TidalAPI. However, my code can't seem to run.

Below is my code:

```<code>import tidalapi

def logindetails():
    username = input("What is your Tidal username? ")
    password = input("What is your Tidal password? ")
    session = tidalapi.Session()
    session.login(username, password)

def gettingalbum():
    logindetails()
    album_id = input("What is the album ID? ")

    tracks = session.get_album_tracks(album_id)
    print("Tracks in this album are:")
    x = 0
    for track in tracks:
        x = x+1
        print(x,track.name)

gettingalbum()
</code>```

NameError: name 'session' is not defined for session.get_album_tracks(album_id)

how can I link my first module with the second?

(It works if I combine both codes into one module, but I have to split them into 2 modules)

答:
I'd suggest making logindetails() return the logged-in session you can then pass into other functions. (The other option would be to make it a global variable.)

I also took the liberty of adding the use of  enumerate() for printing the track indexes.

```<code>import tidalapi

def logindetails():
    """
    Ask for login details and return a logged-in session.
    """
    username = input("What is your Tidal username? ")
    password = input("What is your Tidal password? ")
    session = tidalapi.Session()
    session.login(username, password)
    return session

def gettingalbum(session):
    album_id = input("What is the album ID? ")

    tracks = session.get_album_tracks(album_id)
    print("Tracks in this album are:")
    for x, track in enumerate(tracks, 1):
        print(x, track.name)

session = logindetails()
gettingalbum(session)
</code>```

Title: python API coding for tidal music

Body:
Hi currently a student working on a project for school.

I'm looking to use a music API to work with, and have found TidalAPI. However, my code can't seem to run.

Below is my code:

import tidalapi

def logindetails():
    username = input("What is your Tidal username? ")
    password = input("What is your Tidal password? ")
    session = tidalapi.Session()
    session.login(username, password)

def gettingalbum():
    logindetails()
    album_id = input("What is the album ID? ")

    tracks = session.get_album_tracks(album_id)
    print("Tracks in this album are:")
    x = 0
    for track in tracks:
        x = x+1
        print(x,track.name)

gettingalbum()

NameError: name 'session' is not defined for session.get_album_tracks(album_id)

how can I link my first module with the second?

(It works if I combine both codes into one module, but I have to split them into 2 modules)

Body:
I'd suggest making logindetails() return the logged-in session you can then pass into other functions. (The other option would be to make it a global variable.)

I also took the liberty of adding the use of  enumerate() for printing the track indexes.

import tidalapi

def logindetails():
    """
    Ask for login details and return a logged-in session.
    """
    username = input("What is your Tidal username? ")
    password = input("What is your Tidal password? ")
    session = tidalapi.Session()
    session.login(username, password)
    return session

def gettingalbum(session):
    album_id = input("What is the album ID? ")

    tracks = session.get_album_tracks(album_id)
    print("Tracks in this album are:")
    for x, track in enumerate(tracks, 1):
        print(x, track.name)

session = logindetails()
gettingalbum(session)


问:
React Native: Removed App Permission in FB caused Login Failed: You can't use Facebook to log into this app or website
I'm using React Native 0.61.5 with react-native-fbsdk 2.0.0. Facebook app is Live and configured.

The problem is with the Facebook Login when the permission is removed, facebook cannot re-authorise the Facebook Login anymore and keep displaying error in the facebook app.

error message with Facebook App already signed-in and try to use facebook login

Above was just one of the test case. Prior to "Removing" the app permission in Facebook, the facebook login seems to be fine.

This is the basic RN code for Facebook Login

```<code><LoginButton
  onLoginFinished={
    (error, result) => {
      if (error) {
        console.log("login has error: " + result.error);
      } else if (result.isCancelled) {
        console.log("login is cancelled.");
      } else {
        AccessToken.getCurrentAccessToken().then(
          (data) => {
            console.log(data.accessToken.toString())
          }
        )
      }
    }
  }
  onLogoutFinished={() => console.log("logout.")}/>
</code>```

Any of you have any clue or solution?

I'm expecting that the facebook login will re-authorize again but it's not.

答:
Thank you @imjaad for your attempt to answer my question.

I've resolved this by appealing on Facebook App which the app was Lived, but it has a message that "some of the functions are being restricted".

So, even if Facebook App is Live, make sure there is nothing else / warning / error message that shows up.

I tried to create another Facebook App and it was working fine as well. So nothing wrong with the fbsdk, rn or the code itself.

It was just rare event in Facebook while the appeal is in progress, the Facebook QC made it live temporary, but the message that the app is still being restricted still appear.

So make sure your FB App is Live and there is no other error / warning message in your Facebook App Dashboard.

Good Luck!

Body:
I'm using React Native 0.61.5 with react-native-fbsdk 2.0.0. Facebook app is Live and configured.

The problem is with the Facebook Login when the permission is removed, facebook cannot re-authorise the Facebook Login anymore and keep displaying error in the facebook app.

error message with Facebook App already signed-in and try to use facebook login

Above was just one of the test case. Prior to "Removing" the app permission in Facebook, the facebook login seems to be fine.

This is the basic RN code for Facebook Login

<LoginButton
  onLoginFinished={
    (error, result) => {
      if (error) {
        console.log("login has error: " + result.error);
      } else if (result.isCancelled) {
        console.log("login is cancelled.");
      } else {
        AccessToken.getCurrentAccessToken().then(
          (data) => {
            console.log(data.accessToken.toString())
          }
        )
      }
    }
  }
  onLogoutFinished={() => console.log("logout.")}/>

Any of you have any clue or solution?

I'm expecting that the facebook login will re-authorize again but it's not.


问:
Android ViewModels: Should dataclasses expose livedata properties?
Given this scenario:

Model

```<code>data class User(var id: int, var name: String)
</code>```

View Model

```<code>val Users: LiveData<List<User>>
val SelectedUser: LiveData<User>

fun changeSelectedUserName(){SelectedUser.Name = "foo"}
</code>```

UI

```<code><android:TextView Text="@{viewmodel.SelectedUser.name}"/>
<android:Button Text="Change!" onClik="@{() -> viewmodel.changeSelectedUserName()}"/>
</code>```

When user clicks 'Change!' button the textview won't change because the 'name' field is not LiveData.

Questions

Should data class re-expose its fields as LiveData too?

If so, what will happen to regular fields? Are they replaced or keeped with another naming convention?

What is the correct naming convention if I'm using retrofit? So I can keep both the interface methods and LiveData working with the less amount of code?

答:
Your issue is that you are modifying the User object properties directly, rather than update the LiveData.

For this to work, you have to do one of the following:

Make User extend BaseObservable, and invoke notifyPropertyChanged(BR.name) when the name property changes, and remove the LiveData<User>.

Make User extend BaseObservable, and put @Bindable annotation on the property getters, and remove LiveData<User>.

Make User properties val, and to make a modification, create a new User instance with the changed properties, and set it as value of the MutableLiveData<User>.

Ditch SelectedUser entirely, and replace it with two ObservableFields, one for selectedId: ObservableInt, and one for selectedName: ObservableField<String>. Now you can modify the values in place and also create bindings against it from databinding.

Remove databinding and use viewbinding instead, now you don't have to worry about notifying the databinding framework of property changes.

Should data class re-expose its fields as LiveData too?

No

Body:
Given this scenario:

Model

data class User(var id: int, var name: String)

View Model

val Users: LiveData<List<User>>
val SelectedUser: LiveData<User>

fun changeSelectedUserName(){SelectedUser.Name = "foo"}

UI

<android:TextView Text="@{viewmodel.SelectedUser.name}"/>
<android:Button Text="Change!" onClik="@{() -> viewmodel.changeSelectedUserName()}"/>

When user clicks 'Change!' button the textview won't change because the 'name' field is not LiveData.

Questions

Should data class re-expose its fields as LiveData too?

If so, what will happen to regular fields? Are they replaced or keeped with another naming convention?

What is the correct naming convention if I'm using retrofit? So I can keep both the interface methods and LiveData working with the less amount of code?


问:
Can I force the MVC-6-Grid to understand the data annotation on the fields
I have added the following model class inside my asp.net MVC core web application 3.1:-

```<code>[ModelMetadataType(typeof(Submission_Validation))]
    public partial class Submission
    {

    }
</code>```

and the following Submission_Validation class:-

```<code>public class Submission_Validation
    {

[DisplayFormat(ApplyFormatInEditMode = true,
DataFormatString = "{0:dd MMMM yyyy hh:mm:ss tt}")]
public DateTime Created { get; set; }
    }
</code>```

now if i show the Created field using @Html.DisplayFor(model => model.Created) the date will have the correct format as specified inside the data annotation, but if i render the value inside the MVC-6-Grid ( https://mvc6-grid.azurewebsites.net/) as follow:-

```<code>@(Html
    .Grid(Model)
    .Build(columns =>
    {
columns.Add(model => model.Created).Titled("Created")
})
    .Using(GridFilterMode.Header)
    .Empty("No data found")
    .Filterable()
    .Sortable()
    .Pageable(pager =>
    {

        pager.RowsPerPage = 250;
    })
</code>```

the date will ignore the data annotation specified. any idea how i can fix this?

答:
You can format it in the Grid:</p>

```<code>columns.Add(model => model.Created).Titled("Created").Formatted("{0:dd MMMM yyyy hh:mm:ss tt}");
</code>```

Body:
I have added the following model class inside my asp.net MVC core web application 3.1:-

[ModelMetadataType(typeof(Submission_Validation))]
    public partial class Submission
    {

    }

and the following Submission_Validation class:-

public class Submission_Validation
    {

[DisplayFormat(ApplyFormatInEditMode = true,
DataFormatString = "{0:dd MMMM yyyy hh:mm:ss tt}")]
public DateTime Created { get; set; }
    }

now if i show the Created field using @Html.DisplayFor(model => model.Created) the date will have the correct format as specified inside the data annotation, but if i render the value inside the MVC-6-Grid ( https://mvc6-grid.azurewebsites.net/) as follow:-

@(Html
    .Grid(Model)
    .Build(columns =>
    {
columns.Add(model => model.Created).Titled("Created")
})
    .Using(GridFilterMode.Header)
    .Empty("No data found")
    .Filterable()
    .Sortable()
    .Pageable(pager =>
    {

        pager.RowsPerPage = 250;
    })

the date will ignore the data annotation specified. any idea how i can fix this?

Body:
You can format it in the Grid:

columns.Add(model => model.Created).Titled("Created").Formatted("{0:dd MMMM yyyy hh:mm:ss tt}");


问:
pass 2 dimensional array as a parameter in a web-service in java
I am trying to make a web-service in java where you pass in a 2 dimensional array as a parameter. When I test it with the web-service explore I keep getting this error:

```<code><soapenv:Fault>
  <faultcode>soapenv:Server.userException</faultcode>
  <faultstring>org.xml.sax.SAXException: Found character data inside an array element while deserializing</faultstring>
- <detail>
  <ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">Name</ns1:hostname>
  </detail>
</soapenv:Fault>
</code>```

Any idea as to why?

答:
You are best off wrappering your two-dimensional array inside of an object, and even then use something like ArrayList instead of an actual Array. It works better with web services with Java and your JAXB bindings.</p>

```<code>public class MyTwoDimensionalArrayWrapper {
  private Collection dimensionOne = new ArrayList();
  private Collection dimensionTwo = new ArrayList();

  ...
  //getters and setters, etc.
  //note I did not put any annotations on this..just a skeleton to give you an idea to help.
}
</code>```

Body:
I am trying to make a web-service in java where you pass in a 2 dimensional array as a parameter. When I test it with the web-service explore I keep getting this error:

<soapenv:Fault>
  <faultcode>soapenv:Server.userException</faultcode>
  <faultstring>org.xml.sax.SAXException: Found character data inside an array element while deserializing</faultstring>
- <detail>
  <ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">Name</ns1:hostname>
  </detail>
</soapenv:Fault>

Any idea as to why?

Body:
You are best off wrappering your two-dimensional array inside of an object, and even then use something like ArrayList instead of an actual Array. It works better with web services with Java and your JAXB bindings.

public class MyTwoDimensionalArrayWrapper {
  private Collection dimensionOne = new ArrayList();
  private Collection dimensionTwo = new ArrayList();

  ...
  //getters and setters, etc.
  //note I did not put any annotations on this..just a skeleton to give you an idea to help.
}


问:
How to delete the complete spreadsheet using gspread, python

Explanation:

I got into a situation where I just had to delete the SpreadSheet after the work is finished.

I went through the documentation and I failed to find the function to delete the SpreadSheet.

Code:

```<code>import gspread
from oauth2client.service_account import ServiceAccountCredentials

def update_data():
    return

def export_data():
    return

def delete_sheet():
    # ----------------------------------------------------
    # DELETE SHEET HERE
    # ----------------------------------------------------
    return

if __name__ == "__main__":
    scope = ["https://spreadsheets.google.com/feeds",
             "https://www.googleapis.com/auth/spreadsheets",
             "https://www.googleapis.com/auth/drive.file",
             "https://www.googleapis.com/auth/drive"]
    creds = ServiceAccountCredentials.from_json_keyfile_name('Client_secret.json', scope)
    client = gspread.authorize(creds)

    url = "Url of my SpreadSheet"
    sheet = client.open_by_url(url).sheet1

    update_data(sheet)
    export_data(sheet)
    delete_sheet(sheet)
</code>```

答: You can delete a spreadsheet with Client.del_spreadsheet() method.

Body:
Explanation:

I got into a situation where I just had to delete the SpreadSheet after the work is finished.

I went through the documentation and I failed to find the function to delete the SpreadSheet.

Code:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

def update_data():
    return

def export_data():
    return

def delete_sheet():
    # ----------------------------------------------------
    # DELETE SHEET HERE
    # ----------------------------------------------------
    return

if __name__ == "__main__":
    scope = ["https://spreadsheets.google.com/feeds",
             "https://www.googleapis.com/auth/spreadsheets",
             "https://www.googleapis.com/auth/drive.file",
             "https://www.googleapis.com/auth/drive"]
    creds = ServiceAccountCredentials.from_json_keyfile_name('Client_secret.json', scope)
    client = gspread.authorize(creds)

    url = "Url of my SpreadSheet"
    sheet = client.open_by_url(url).sheet1

    update_data(sheet)
    export_data(sheet)
    delete_sheet(sheet)


问:
How can I convert the following to VB.NET (Where Clause)
I have a legacy application that is is VB.NET and I need to convert this C# into VB.NET.  I don't know how to deal with the Where clause.  Can anyone help please.</p>

```<code>ImageCodecInfo pngCodec = ImageCodecInfo.GetImageEncoders().Where(codec => codec.FormatID.Equals(ImageFormat.Png.Guid)).FirstOrDefault();
if (pngCodec != null)
{
EncoderParameters parameters = new EncoderParameters();
parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 8);
myImage.Save(myStream, pngCodec, parameters);
}
</code>```

答:
I hope , this should work:</p>

```<code> Dim pngCodec As ImageCodecInfo = ImageCodecInfo.GetImageEncoders().Where(Function(codec) codec.FormatID.Equals(ImageFormat.Png.Guid)).FirstOrDefault

 If Not pngCodec Is Nothing Then
     Dim parameters As New EncoderParameters
     parameters.Param(0) = New EncoderParameter(Encoder.ColorDepth, 8)
     myImage.Save(myStream, pngCodec, parameters)
 End If
</code>```

Body:
I have a legacy application that is is VB.NET and I need to convert this C# into VB.NET.  I don't know how to deal with the Where clause.  Can anyone help please.

ImageCodecInfo pngCodec = ImageCodecInfo.GetImageEncoders().Where(codec => codec.FormatID.Equals(ImageFormat.Png.Guid)).FirstOrDefault();
if (pngCodec != null)
{
EncoderParameters parameters = new EncoderParameters();
parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 8);
myImage.Save(myStream, pngCodec, parameters);
}

Body:
I hope , this should work:

 Dim pngCodec As ImageCodecInfo = ImageCodecInfo.GetImageEncoders().Where(Function(codec) codec.FormatID.Equals(ImageFormat.Png.Guid)).FirstOrDefault

 If Not pngCodec Is Nothing Then
     Dim parameters As New EncoderParameters
     parameters.Param(0) = New EncoderParameter(Encoder.ColorDepth, 8)
     myImage.Save(myStream, pngCodec, parameters)
 End If


问:
C++ classes vs. C different files
Currently in a project there is a clear set of functions that pertain to a clear responsibility. Because the responsibility is a periodic process that requires buffers and counters for each iteration, I have to reset the variables used by those functions after each cycle. The variables are mostly static because per cycle the functions are called thousands of times. (It is a set of digital FIR filters that process the 5 second data that is coming in every 2 minutes or so). The variables have to be declared in the file scope, because the functions share them. E.g. the reset / initialize function and the actual filter functions.

As of now, the whole project is in C (but C++ is easily supported, as the possibly breaking parts already contain 'extern C {}'). To make the code cleaner, I thought to group the functions and variables in a separate implementation file. But of course, I could also use C++ classes, which I would like to work with more.

What are the essential differences between these options?

Simplified example of what I mean:
In this example, I just kept the structure of the program. The Filter() function is called for example 1000 times in 5 seconds for the first iteration. Then for the next iterations, the Reset() function is called prior to the actual Filter() function calls, to reset all the buffers that are used.

```<code>// File-scope variables
static float   buffer[BUFFER_SIZE];
static uint8_t bufferOffset = 0;

// Filter
static float Filter (const float sample)
{
  buffer[bufferOffset] = sample;

  // Removed actual filter code here

  return result;
}

// Reset functions
static void Reset (void)
{
  memset(buffer, 0, sizeof(buffer));
  bufferOffset = 0;
}
</code>```

答:
The usual approach in C to avoid those shared states is to define a structure encapsulating all the relevant state, pass it to every function and operate solely on it.

Example:

```<code>// buffer.h
#pragma once

// opaque data structure whose content
// isn't available to the outside
struct buffer;

// but you may allocate and free such a data structure
struct buffer *alloc_buffer();
void free_buffer(struct buffer *b);

// and you may operate on it with the following functions
float filter_buffer(struct buffer *b);
void reset_buffer(struct buffer *b);
void add_to_buffer(struct buffer *b, const float *data, size_t size);
</code>```

And the source looks like this:

```<code>// buffer.c
#include "buffer.h"

struct buffer {
    float content[BUFFER_SIZE];
    uint8_t offset;
}

struct buffer *alloc_buffer() {
    return malloc(sizeof(struct buffer));
}

void free_buffer(struct buffer *b) {
    free(b);
}

float filter_buffer(struct buffer *b) {
    // work with b->content and b->offset instead
    // on global buffer and bufferOffset
    return result;
}

void reset_buffer(struct buffer *b) {
    memset(b->content, 0, BUFFER_SIZE);
    b->offset = 0;
}

void add_to_buffer(struct buffer *b, const float *data, size_t num) {
    memcpy(b->content + b->offset, data, sizeof(float) * num);
    b->offset += num;
}
</code>```

Thus you avoid a global state which for example dramatically simplifies multi-threaded applications of your code. And since you return an opaque data structure, you avoid leaking information about the internal structure of your buffer.

Now you may use this data structure in a different source file:

```<code>#include "buffer.h"

int main() {
    struct buffer *const b = alloc_buffer();

    // b->content[0] = 1; // <-- error, buffer is an opaque data type and
                          //     you may only use the functions declared in
                          //     buffer.h to access and modify it

    const float data[2] = { 3.1415926, 2.71828 }
    add_to_buffer(b, data, sizeof(data) / sizeof(data[0]));
    const float result = filter_buffer(b);

    return 0;
}
</code>```

To answer you question: Even though you could separate your functions and global state even further into several compilation units, in the end you still have a shared global state. Except in some special cases I consider this a code smell.

The above described solution more or less corresponds to a C++ solution. You define a class encapsulating some state and methods operating on it. All instantiated objects are independent from each other.

Title: C++ classes vs. C different files

Body:
Currently in a project there is a clear set of functions that pertain to a clear responsibility. Because the responsibility is a periodic process that requires buffers and counters for each iteration, I have to reset the variables used by those functions after each cycle. The variables are mostly static because per cycle the functions are called thousands of times. (It is a set of digital FIR filters that process the 5 second data that is coming in every 2 minutes or so). The variables have to be declared in the file scope, because the functions share them. E.g. the reset / initialize function and the actual filter functions.

As of now, the whole project is in C (but C++ is easily supported, as the possibly breaking parts already contain 'extern C {}'). To make the code cleaner, I thought to group the functions and variables in a separate implementation file. But of course, I could also use C++ classes, which I would like to work with more.

What are the essential differences between these options?

Simplified example of what I mean:
In this example, I just kept the structure of the program. The Filter() function is called for example 1000 times in 5 seconds for the first iteration. Then for the next iterations, the Reset() function is called prior to the actual Filter() function calls, to reset all the buffers that are used.

// File-scope variables
static float   buffer[BUFFER_SIZE];
static uint8_t bufferOffset = 0;

// Filter
static float Filter (const float sample)
{
  buffer[bufferOffset] = sample;

  // Removed actual filter code here

  return result;
}

// Reset functions
static void Reset (void)
{
  memset(buffer, 0, sizeof(buffer));
  bufferOffset = 0;
}

Body:
The usual approach in C to avoid those shared states is to define a structure encapsulating all the relevant state, pass it to every function and operate solely on it.

Example:

// buffer.h
#pragma once

// opaque data structure whose content
// isn't available to the outside
struct buffer;

// but you may allocate and free such a data structure
struct buffer *alloc_buffer();
void free_buffer(struct buffer *b);

// and you may operate on it with the following functions
float filter_buffer(struct buffer *b);
void reset_buffer(struct buffer *b);
void add_to_buffer(struct buffer *b, const float *data, size_t size);

And the source looks like this:

// buffer.c
#include "buffer.h"

struct buffer {
    float content[BUFFER_SIZE];
    uint8_t offset;
}

struct buffer *alloc_buffer() {
    return malloc(sizeof(struct buffer));
}

void free_buffer(struct buffer *b) {
    free(b);
}

float filter_buffer(struct buffer *b) {
    // work with b->content and b->offset instead
    // on global buffer and bufferOffset
    return result;
}

void reset_buffer(struct buffer *b) {
    memset(b->content, 0, BUFFER_SIZE);
    b->offset = 0;
}

void add_to_buffer(struct buffer *b, const float *data, size_t num) {
    memcpy(b->content + b->offset, data, sizeof(float) * num);
    b->offset += num;
}

Thus you avoid a global state which for example dramatically simplifies multi-threaded applications of your code. And since you return an opaque data structure, you avoid leaking information about the internal structure of your buffer.

Now you may use this data structure in a different source file:

#include "buffer.h"

int main() {
    struct buffer *const b = alloc_buffer();

    // b->content[0] = 1; // <-- error, buffer is an opaque data type and
                          //     you may only use the functions declared in
                          //     buffer.h to access and modify it

    const float data[2] = { 3.1415926, 2.71828 }
    add_to_buffer(b, data, sizeof(data) / sizeof(data[0]));
    const float result = filter_buffer(b);

    return 0;
}

To answer you question: Even though you could separate your functions and global state even further into several compilation units, in the end you still have a shared global state. Except in some special cases I consider this a code smell.

The above described solution more or less corresponds to a C++ solution. You define a class encapsulating some state and methods operating on it. All instantiated objects are independent from each other.


问:
How to skip angularjs interceptor for an HTTP request?
I have an angularjs app, in which I have an interceptor that adds the authorization token to the header of each request.

However, somewhere in the application I need to use and external API where the interceptor ruins it, because it adds this authorization header which is not acceptable by this external API provider. How can I make angularjs HTTP skip the interceptor, only on this one specific case?

The interceptor code is below:

```<code>app.factory('authInterceptorService', ['$q', '$injector', '$location', 'localStorageService', function ($q, $injector, $location, localStorageService) {
    var authInterceptorServiceFactory = {};
    var $http;

    var _request = function (config) {

        config.headers = config.headers || {};

        var authData = localStorageService.get('authorizationData');
        if (authData) {
            //console.log("token: " + authData.token.substring(0, 10));
            //console.log("user: " + authData.userName);
            config.headers.Authorization = 'Bearer ' + authData.token;
        }
        return config;
    }

    var _responseError = function (rejection) {
        var deferred = $q.defer();
        if (rejection.status === 401) {
            var authService = $injector.get('authService');
            authService.refreshToken().then(function (response) {
                _retryHttpRequest(rejection.config, deferred);
            }, function () {
                authService.logOut();
                $location.path('/login');
                deferred.reject(rejection);
            });
        } else {
            deferred.reject(rejection);
        }
        return deferred.promise;
    }

    var _retryHttpRequest = function (config, deferred) {
        console.log('retrying');
        $http = $http || $injector.get('$http');
        $http(config).then(function (response) {
            deferred.resolve(response);
            //console.log("success:" +response);
        }, function (response) {
            deferred.reject(response);
            //console.log("error:" + response);
        });
    }

    authInterceptorServiceFactory.request = _request;
    authInterceptorServiceFactory.responseError = _responseError;

    return authInterceptorServiceFactory;
}]);
</code>```

答:
If you are looking for the auth0 interceptor:</p>

```<code>export class InterceptorService implements HttpInterceptor {
    constructor(private auth: AuthService) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        var allow = ['/assets/i18n/de.json', '/assets/i18n/en.json'];

        if (allow.includes(req.url)) {
            const noToken = req.clone();
            return next.handle(noToken);
        }
        return this.auth.getTokenSilently$().pipe(
            mergeMap(token => {
                const tokenReq = req.clone({
                    setHeaders: { Authorization: `Bearer ${token}` }
                });
                return next.handle(tokenReq);
            }),
            catchError(err => throwError(err))
        );
    }
}
</code>```

Body:
I have an angularjs app, in which I have an interceptor that adds the authorization token to the header of each request.

However, somewhere in the application I need to use and external API where the interceptor ruins it, because it adds this authorization header which is not acceptable by this external API provider. How can I make angularjs HTTP skip the interceptor, only on this one specific case?

The interceptor code is below:

app.factory('authInterceptorService', ['$q', '$injector', '$location', 'localStorageService', function ($q, $injector, $location, localStorageService) {
    var authInterceptorServiceFactory = {};
    var $http;

    var _request = function (config) {

        config.headers = config.headers || {};

        var authData = localStorageService.get('authorizationData');
        if (authData) {
            //console.log("token: " + authData.token.substring(0, 10));
            //console.log("user: " + authData.userName);
            config.headers.Authorization = 'Bearer ' + authData.token;
        }
        return config;
    }

    var _responseError = function (rejection) {
        var deferred = $q.defer();
        if (rejection.status === 401) {
            var authService = $injector.get('authService');
            authService.refreshToken().then(function (response) {
                _retryHttpRequest(rejection.config, deferred);
            }, function () {
                authService.logOut();
                $location.path('/login');
                deferred.reject(rejection);
            });
        } else {
            deferred.reject(rejection);
        }
        return deferred.promise;
    }

    var _retryHttpRequest = function (config, deferred) {
        console.log('retrying');
        $http = $http || $injector.get('$http');
        $http(config).then(function (response) {
            deferred.resolve(response);
            //console.log("success:" +response);
        }, function (response) {
            deferred.reject(response);
            //console.log("error:" + response);
        });
    }

    authInterceptorServiceFactory.request = _request;
    authInterceptorServiceFactory.responseError = _responseError;

    return authInterceptorServiceFactory;
}]);

Body:
If you are looking for the auth0 interceptor:

export class InterceptorService implements HttpInterceptor {
    constructor(private auth: AuthService) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        var allow = ['/assets/i18n/de.json', '/assets/i18n/en.json'];

        if (allow.includes(req.url)) {
            const noToken = req.clone();
            return next.handle(noToken);
        }
        return this.auth.getTokenSilently$().pipe(
            mergeMap(token => {
                const tokenReq = req.clone({
                    setHeaders: { Authorization: `Bearer ${token}` }
                });
                return next.handle(tokenReq);
            }),
            catchError(err => throwError(err))
        );
    }
}


问:
Critical directive not working inside sections in openmp
```<code>#include <omp.h>
#include <iostream>

int main(int argc, char *argv[]) {

#pragma omp parallel  num_threads(2)
{

#pragma omp sections
 {

 #pragma omp section
     {

     #pragma omp cirtical
     {
     std::cout<<"first section is executed by thread "<<omp_get_thread_num()<<"\n";
     }
     }

 #pragma omp section
     {
    #pragma omp cirtical
     {
 std::cout<<"second section is executed by thread "<<omp_get_thread_num()<<"\n";
     }
     }

 }

  }
 return 0;
 }
</code>```

In the above code output operation in two section have race between then although they are in critical section. Can you tell why this is happening and how should I ensure no race between them?

答:
The problem is almost certainly that pointed out by High Performance Mark: you have mis-spelled the word "critical" in the OpenMP pragma.

However, this points out the more general issue that you should (at least) enable warnings when compiling. With GCC you can achieve that with -Wall, or, if you only want to be warned about this error, you can use -Wunknown-pragmas.

If you want to be both stricter and more selective you can use -Werror=unknown-pragmas, which will cause code like this with mis-spelled pragmas to fail to compile. The downside of any of these is that if you then compile the code without -fopenmp you get the warning/error for every OpenMP pragma.

You may, therefore, want to enable -Werror=unknown-pragmas only when you also have -fopenmp. (This should be simple to do in Make; how easy it is in "simple","modern" build systems, I have no idea :-)).

Thanks to High Performance Mark for the original answer, and to Jakub Jelinek for GCC argument education.

Body:
#include <omp.h>
#include <iostream>

int main(int argc, char *argv[]) {

#pragma omp parallel  num_threads(2)
{

#pragma omp sections
 {

 #pragma omp section
     {

     #pragma omp cirtical
     {
     std::cout<<"first section is executed by thread "<<omp_get_thread_num()<<"\n";
     }
     }

 #pragma omp section
     {
    #pragma omp cirtical
     {
 std::cout<<"second section is executed by thread "<<omp_get_thread_num()<<"\n";
     }
     }

 }

  }
 return 0;
 }

In the above code output operation in two section have race between then although they are in critical section. Can you tell why this is happening and how should I ensure no race between them?


问:
Rails help model design problem
I am having that problem when I update my konkurrencer the do_foobar is called. The problem is that the konkurrancer have no ratings. And I get a off course a ZeroDivisionerror.

What is the best solution to solve this kind of problem?

My model:

```<code>before_update :do_foobar
def do_foobar
  self.rating = (rating_score/ratings)
end
</code>```

答:
```<code>self.rating = (ratings == 0) ? nil : rating_score/ratings
</code>```

or

```<code>self.rating = rating_score/ratings rescue nil
</code>```

Title: Rails help model design problem

Body:
I am having that problem when I update my konkurrencer the do_foobar is called. The problem is that the konkurrancer have no ratings. And I get a off course a ZeroDivisionerror.

What is the best solution to solve this kind of problem?

My model:

before_update :do_foobar
def do_foobar
  self.rating = (rating_score/ratings)
end

Body:
self.rating = (ratings == 0) ? nil : rating_score/ratings

or

self.rating = rating_score/ratings rescue nil


问:
toFixed() dynamically in js
```<code>let a = 2.0123456789;
let b = 10;
let c = 7.000123456;
let d = 4.10002345;
a.toFixed(2); // "2.01"  // It's fine.
b.toFixed(2); // "10.00" // It should be "10"
c.toFixed(2); // "7.00"  // It should be "7"
d.toFixed(2); // "4.10"  // It should be "4.1"
</code>```

I have no idea how do I cut the number dynamically.

答:
If you convert it to number, this will happen automatically.

let a = 2.0123456789;
let b = 10;
let c = 7.000123456;
let d = 4.10002345;

console.log(Number(a.toFixed(2)));
console.log(Number(b.toFixed(2)));
console.log(Number(c.toFixed(2)));
console.log(Number(d.toFixed(2)));```

Title: toFixed() dynamically in js

Body:
let a = 2.0123456789;
let b = 10;
let c = 7.000123456;
let d = 4.10002345;
a.toFixed(2); // "2.01"  // It's fine.
b.toFixed(2); // "10.00" // It should be "10"
c.toFixed(2); // "7.00"  // It should be "7"
d.toFixed(2); // "4.10"  // It should be "4.1"

I have no idea how do I cut the number dynamically.


问:
How to find the minimal element of each column in a two-dimensional array in Python
```<code>import random
x =[[random.randint(1,10) for j in range(5)] for i in range(4)]
for i in range(4):
    for j in range(5):
        print("%4d" % (x[i][j]), end="")
    print(end='\n')
</code>```

I need to find minimal element of each column in a  two-dimensional array and add them in a new array(one-dimensional array)

答:
You should look into numpy() and specifically np.min(). The code can then be:</p>

```<code># Convert 'x' to np array-
x_np = np.asarray(x)

# Sanity check-
x_np
'''
array([[ 8,  7, 10,  8,  8],
       [ 6,  6,  3,  6,  6],
       [ 9,  4,  2,  8,  3],
       [ 2,  4,  5,  3,  4]])
'''

# Minimum elements by squashing the columns-
np.min(x_np, axis = 1)
# array([7, 3, 2, 2])

# Minimum elements by squashing the rows-
np.min(x_np, axis = 0)
# array([2, 4, 2, 3, 3])
</code>```

Body:
import random
x =[[random.randint(1,10) for j in range(5)] for i in range(4)]
for i in range(4):
    for j in range(5):
        print("%4d" % (x[i][j]), end="")
    print(end='\n')

I need to find minimal element of each column in a  two-dimensional array and add them in a new array(one-dimensional array)

Body:
You should look into numpy() and specifically np.min(). The code can then be:

# Convert 'x' to np array-
x_np = np.asarray(x)

# Sanity check-
x_np
'''
array([[ 8,  7, 10,  8,  8],
       [ 6,  6,  3,  6,  6],
       [ 9,  4,  2,  8,  3],
       [ 2,  4,  5,  3,  4]])
'''

# Minimum elements by squashing the columns-
np.min(x_np, axis = 1)
# array([7, 3, 2, 2])

# Minimum elements by squashing the rows-
np.min(x_np, axis = 0)
# array([2, 4, 2, 3, 3])


问:
How to add support for new "Insertable Streams" feature in current browsers?
I want to encrypt streams before sending to my media server, like here and here.
the problem is they are using very new experimental feature (Insertable Streams), I tried to find a hack to make it work in current browsers. right now the only half way that I've found is to display streams in a canvas and capture altered streams from that canvas here, but I don't know how to do it and whether it's a right approach or not?</p>

答: You can enable the API in Chrome for users of your site using a Chrome origin trial. Origin trials are intended for experimentation. More info about origin trials in general can be found here.</p>


问:
Skip Parent Background in Child class while inherit other properties
I don't want child class to inherit the immediate parent class background color which has background color as white. Instead it should skip and take background color from parent component which is bluebackground. When I use the transparent background in child class it should show blue color not white. Rest of the property of parent (whitebackground class) should be inherited just not the white background in child class.

I cannot do any changes on Parent component just I can do changes using css.

app component :

```<code><div class="bluebackground">
<app-test>
</app-test>
</div>
</code>```

Component: test

```<code>BlueBackGround Start
  <div class="whitebackground">
      Some White Background Stuff that I need
      <div class="child">
          Here i want background which should skip the parent whitebackground and show blue color same as bluebackground class <br />
      </div>
  </div>
BlueBackGround End
</code>```

Here is the Css

```<code>.child {
    font-size: 2rem;
    text-align: center;
    color: green;
    background:transparent;
  }
  .bluebackground{
    background: blue;
     font-size: 3rem;
  }

  .whitebackground {
    background:white;
  }
</code>```

StackBlitz

https://stackblitz.com/edit/angular-ivy-hbfvjs

答:
Try like this:

```<code><div class="bluebackground">
  Blue Background Start
  <div class="whitebackground">
      Some White Background Stuff that I need
      <div class="child bluebackground">
          Here i want background which should skip the parent whitebackground and show blue color same as mainbackground class <br />
      </div>
  </div>
  Blue Background End
<div>
</code>```

Working Demo

Body:
I don't want child class to inherit the immediate parent class background color which has background color as white. Instead it should skip and take background color from parent component which is bluebackground. When I use the transparent background in child class it should show blue color not white. Rest of the property of parent (whitebackground class) should be inherited just not the white background in child class.

I cannot do any changes on Parent component just I can do changes using css.

app component :

<app-test>
</app-test>

Component: test

BlueBackGround Start

      Some White Background Stuff that I need

          Here i want background which should skip the parent whitebackground and show blue color same as bluebackground class

BlueBackGround End

Here is the Css

.child {
    font-size: 2rem;
    text-align: center;
    color: green;
    background:transparent;
  }
  .bluebackground{
    background: blue;
     font-size: 3rem;
  }

  .whitebackground {
    background:white;
  }

StackBlitz

https://stackblitz.com/edit/angular-ivy-hbfvjs

Body:
Try like this:

<div class="bluebackground">
  Blue Background Start
  <div class="whitebackground">
      Some White Background Stuff that I need
      <div class="child bluebackground">
          Here i want background which should skip the parent whitebackground and show blue color same as mainbackground class <br />
      </div>
  </div>
  Blue Background End
<div>

Working Demo


问:
MySQL Python connector - Update not updating
I'm using MySQL in Python but my update function isn't updating the row and I can't understand the message error.

```<code>def atualizaCartelaTabela(campo,valor,jogador):
    try:
        connection = mysql.connector.connect(host='localhost',
                                     user='root',
                                     password='root',
                                     database='modular')
        cursor = connection.cursor()
        sql = """UPDATE Cartela
                SET %s = %s
                WHERE PONTOS = %s"""
        atualiza = (campo,valor,jogador)
        cursor.execute(sql,atualiza)
    except Error as e:
        print("Erro ao atualizar campos da tabela Cartela ->", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

def atualizaCartelaTabela(campo,valor,jogador):
    try:
        connection = mysql.connector.connect(host='localhost',
                                     user='root',
                                     password='root',
                                     database='modular')
        cursor = connection.cursor()
        sql = """UPDATE Cartela
                SET %s = %s
                WHERE PONTOS = %s"""
        atualiza = (campo,valor,jogador)
        cursor.execute(sql,atualiza)
    except Error as e:
        print("Erro ao atualizar campos da tabela Cartela ->", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

atualizaCartelaTabela('Um',2,'Jogador 1')
</code>```

The error I'm getting:

1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Um' = 2
WHERE PONTOS = 'Jogador 1'' at line 2

And, this is the function used to create the table(working):

```<code>def criaTabelaCartela():
    try:
        connection = mysql.connector.connect(host='localhost',
                                     user='root',
                                     password='root',
                                     database='modular')
        cursor = connection.cursor()
        cursor.execute("CREATE TABLE Cartela (PONTOS VARCHAR(10), Um int(2), Dois int(1), Tres int(1), Quatro int(1), Cinco int(1), Seis int(1), Full int(1), SequenciaBaixa int(1), Trinca int(1), Quadra int(1), SequenciaAlta int(1), Yahtzee int(1), PontuaçãoFinal int(1))")
        connection.commit()
    except Error as e:
        print("Erro ao criar tabela Cartela ->", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
</code>```

答:
I am guessing the int - 2 is the problem here .
Try this out :

Make your SQL-query this :

```<code>sql = """
    UPDATE Cartela
    SET %s = CAST(%s AS int)
    WHERE PONTOS = %s
"""
</code>```

And where you're calling the method atualizaCartelaTabela make it this :

```<code>atualizaCartelaTabela('Um','2','Jogador 1')
</code>```

Body:
I'm using MySQL in Python but my update function isn't updating the row and I can't understand the message error.

def atualizaCartelaTabela(campo,valor,jogador):
    try:
        connection = mysql.connector.connect(host='localhost',
                                     user='root',
                                     password='root',
                                     database='modular')
        cursor = connection.cursor()
        sql = """UPDATE Cartela
                SET %s = %s
                WHERE PONTOS = %s"""
        atualiza = (campo,valor,jogador)
        cursor.execute(sql,atualiza)
    except Error as e:
        print("Erro ao atualizar campos da tabela Cartela ->", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

def atualizaCartelaTabela(campo,valor,jogador):
    try:
        connection = mysql.connector.connect(host='localhost',
                                     user='root',
                                     password='root',
                                     database='modular')
        cursor = connection.cursor()
        sql = """UPDATE Cartela
                SET %s = %s
                WHERE PONTOS = %s"""
        atualiza = (campo,valor,jogador)
        cursor.execute(sql,atualiza)
    except Error as e:
        print("Erro ao atualizar campos da tabela Cartela ->", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

atualizaCartelaTabela('Um',2,'Jogador 1')

The error I'm getting:

1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Um' = 2
WHERE PONTOS = 'Jogador 1'' at line 2

And, this is the function used to create the table(working):

def criaTabelaCartela():
    try:
        connection = mysql.connector.connect(host='localhost',
                                     user='root',
                                     password='root',
                                     database='modular')
        cursor = connection.cursor()
        cursor.execute("CREATE TABLE Cartela (PONTOS VARCHAR(10), Um int(2), Dois int(1), Tres int(1), Quatro int(1), Cinco int(1), Seis int(1), Full int(1), SequenciaBaixa int(1), Trinca int(1), Quadra int(1), SequenciaAlta int(1), Yahtzee int(1), PontuaçãoFinal int(1))")
        connection.commit()
    except Error as e:
        print("Erro ao criar tabela Cartela ->", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

Body:
I am guessing the int - 2 is the problem here .
Try this out :

Make your SQL-query this :

sql = """
    UPDATE Cartela
    SET %s = CAST(%s AS int)
    WHERE PONTOS = %s
"""

And where you're calling the method atualizaCartelaTabela make it this :

atualizaCartelaTabela('Um','2','Jogador 1')


问:
how to group a string in a column in python?
i have a dataframe

```<code>   PROD  TYPE  QUANTI
0  wood    i2      20
1    tv    ut1      30
2  tabl    il3      50
3   rmt    z1      40
4   zet    u1      60
5    rm    t1      60
6    rt    t2      80
7   dud    i4      40
</code>```

I want to group the column "TYPE" in-group categories of (i,u,z,y...etc)

Expected Output

```<code>   PROD      TYPE    QUANTI
0  wood    i_group      20
1    tv    ut_group      30
2  tabl    il_group      50
3   rmt    z_group      40
4   zet    y_group      60
5    rm    t_group      60
6    rt    t_group      80
7   dud    i_group      40
</code>```

答:
Use Series.replace for replace number to _group:

```<code>df['TYPE'] = df['TYPE'].replace('\d+', '_group', regex=True)
print (df)
   PROD      TYPE  QUANTI
0  wood   i_group      20
1    tv  ut_group      30
2  tabl  il_group      50
3   rmt   z_group      40
4   zet   u_group      60
5    rm   t_group      60
6    rt   t_group      80
7   dud   i_group      40
</code>```

If possible some values with no number use:

```<code>df['TYPE'] = df['TYPE'].replace('\d+', '', regex=True) + '_group'
</code>```

Body:
i have a dataframe

   PROD  TYPE  QUANTI
0  wood    i2      20
1    tv    ut1      30
2  tabl    il3      50
3   rmt    z1      40
4   zet    u1      60
5    rm    t1      60
6    rt    t2      80
7   dud    i4      40

I want to group the column "TYPE" in-group categories of (i,u,z,y...etc)

Expected Output

   PROD      TYPE    QUANTI
0  wood    i_group      20
1    tv    ut_group      30
2  tabl    il_group      50
3   rmt    z_group      40
4   zet    y_group      60
5    rm    t_group      60
6    rt    t_group      80
7   dud    i_group      40

Body:
Use Series.replace for replace number to _group:

df['TYPE'] = df['TYPE'].replace('\d+', '_group', regex=True)
print (df)
   PROD      TYPE  QUANTI
0  wood   i_group      20
1    tv  ut_group      30
2  tabl  il_group      50
3   rmt   z_group      40
4   zet   u_group      60
5    rm   t_group      60
6    rt   t_group      80
7   dud   i_group      40

If possible some values with no number use:

df['TYPE'] = df['TYPE'].replace('\d+', '', regex=True) + '_group'


问:
How can I solve this String and int problem?
You see I have a problem: Is there any possibility to somehow change that path to int without changing the code entirely?

Im using android studio and currently developing app but Im strugling with one thing.

I have a String path of image which needs to be int for it to work.

```<code>String path1 = Environment.getDataDirectory().getAbsolutePath() + "/data/sk.lotario.bg/app_imgBuns/0.png";
String path2 = Environment.getDataDirectory().getAbsolutePath() + "/data/sk.lotario.bg/app_imgBuns/1.png";

    List<SliderBN> sliderBNS = new ArrayList<>();
    for(int i = 0; i < Recipe.bnPos; i++){
        sliderBNS.add(new SliderBN(path1));
        sliderBNS.add(new SliderBN(path2));
</code>```

In class SliderBN I have this:

```<code>public class SliderBN {

    private int image;

    SliderBN(int image){
        this.image = image;
    }

    public int getImage() {
        return image;
    }
</code>```

Problem is I dont want to change it here to String cause then I would have to change a lot of code.

Here is adapter to that class:

```<code>
    private List<SliderBN> sliderBNS;
    private ViewPager2 vpBN;
    private static final String TAG = "SliderBNAdapter";
    public static int vpBNPosition = 0;

    public SliderBNAdapter(List<SliderBN> sliderBNS, ViewPager2 vpBN) {
        this.sliderBNS = sliderBNS;
        this.vpBN = vpBN;
    }

    public SliderBNAdapter() {

    }

    @NonNull
    @Override
    public SliderViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new SliderViewHolder(
                    LayoutInflater.from(parent.getContext()).inflate(
                            R.layout.slider_item_container,
                            parent,
                            false
                )
        );
    }

    @Override
    public void onBindViewHolder(@NonNull SliderViewHolder holder, int position) {
        holder.setImage(sliderBNS.get(position));
        if (position == sliderBNS.size()) {
            vpBN.post(runnable);
        }
    }

    @Override
    public int getItemCount() {
        vpBNPosition = vpBN.getCurrentItem();
        Log.i(TAG,"position "+vpBNPosition);
        return sliderBNS.size();
    }

    class SliderViewHolder extends RecyclerView.ViewHolder {

        private ImageView imageView;

        SliderViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageSlide);
        }
        void setImage(SliderBN sliderBN){
            imageView.setImageResource(sliderBun.getImage());
        }
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            sliderBNS.addAll(sliderBNS);
            notifyDataSetChanged();
        }
    };
</code>```

答:
You can add to the SliderBN two properties. One is String path and the other is int index. When you create SliderBN you can just set the values that you want. Then inside your code you can use the property which you need.

```<code>public class SliderBN {

    private int index;
    private String path;

    SliderBN(String path, int index){
        this.index = index;
        this.path = path;
    }

    public int getIndex() {
        return index;
    }

    public String getPath() {
        return path;
    }
}
</code>```

In the beginning when you create image you can do:

```<code>String pathToImages = Environment.getDataDirectory().getAbsolutePath() + "/data/sk.lotario.bg/app_imgBuns/";

List<SliderBN> sliderBNS = new ArrayList<>();
// Here you need to be sure that you always have the images else you will
// receive exceptions! If this images will be dynamically added/removed then
// you need another way for retrieving the names and loading them in the list.
for(int i = 0; i < Recipe.bnPos; i++){
    sliderBNS.add(new SliderBN(pathToImages + i + ".png", i));
}
</code>```

For example where you need to set the image path you can just call getPath method:

```<code>class SliderViewHolder extends RecyclerView.ViewHolder {

    private ImageView imageView;

    SliderViewHolder(@NonNull View itemView) {
        super(itemView);
        imageView = itemView.findViewById(R.id.imageSlide);
    }
    void setImage(SliderBN sliderBN){
        // Here you can set the path to the image
        // I saw that you setImageResource(int resId)
        // But for this to work you need the Image ids
        // In the current case we can use setImageURI(Uri uri)
        // With Uri you need to provide the path to the image not the id

         File imgFile = new File(sliderBun.getPath());
         if(imgFile.exists())
         {
             Uri uri = Uri.fromFile(imgFile);
             imageView.setImageURI(uri);
         }
         else
         {
             // Log here message that the file does not exist
             // and also log the path so you can see what is going wrong
         }
    }
}
</code>```

NOTE: As your code is right now you do not need index (int) in class SliderBN because you have this information in the list where you add all images in the beginning. Still I don't know all of your use-cases that why I left it. See example of using index of the list to get the Object on that position:

```<code>@Override
public void onBindViewHolder(@NonNull SliderViewHolder holder, int position)
{
    // Here we get SliderBN object from the list by list position and not by
    // internal properties
    holder.setImage(sliderBNS.get(position));
    if (position == sliderBNS.size()) {
        vpBN.post(runnable);
    }
}
</code>```

One place where you will need index is if you have List with unsorted SliderBN objects and you need easily to sort them. Then you can use this property index to sort the objects in that List. But in your case you create the images from growing index inside of for loop so your list actually is sorted.

Good luck to all!

Body:
You see I have a problem: Is there any possibility to somehow change that path to int without changing the code entirely?

Im using android studio and currently developing app but Im strugling with one thing.

I have a String path of image which needs to be int for it to work.

String path1 = Environment.getDataDirectory().getAbsolutePath() + "/data/sk.lotario.bg/app_imgBuns/0.png";
String path2 = Environment.getDataDirectory().getAbsolutePath() + "/data/sk.lotario.bg/app_imgBuns/1.png";

    List<SliderBN> sliderBNS = new ArrayList<>();
    for(int i = 0; i < Recipe.bnPos; i++){
        sliderBNS.add(new SliderBN(path1));
        sliderBNS.add(new SliderBN(path2));

In class SliderBN I have this:

public class SliderBN {

    private int image;

    SliderBN(int image){
        this.image = image;
    }

    public int getImage() {
        return image;
    }

Problem is I dont want to change it here to String cause then I would have to change a lot of code.

Here is adapter to that class:

    private List<SliderBN> sliderBNS;
    private ViewPager2 vpBN;
    private static final String TAG = "SliderBNAdapter";
    public static int vpBNPosition = 0;

    public SliderBNAdapter(List<SliderBN> sliderBNS, ViewPager2 vpBN) {
        this.sliderBNS = sliderBNS;
        this.vpBN = vpBN;
    }

    public SliderBNAdapter() {

    }

    @NonNull
    @Override
    public SliderViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new SliderViewHolder(
                    LayoutInflater.from(parent.getContext()).inflate(
                            R.layout.slider_item_container,
                            parent,
                            false
                )
        );
    }

    @Override
    public void onBindViewHolder(@NonNull SliderViewHolder holder, int position) {
        holder.setImage(sliderBNS.get(position));
        if (position == sliderBNS.size()) {
            vpBN.post(runnable);
        }
    }

    @Override
    public int getItemCount() {
        vpBNPosition = vpBN.getCurrentItem();
        Log.i(TAG,"position "+vpBNPosition);
        return sliderBNS.size();
    }

    class SliderViewHolder extends RecyclerView.ViewHolder {

        private ImageView imageView;

        SliderViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageSlide);
        }
        void setImage(SliderBN sliderBN){
            imageView.setImageResource(sliderBun.getImage());
        }
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            sliderBNS.addAll(sliderBNS);
            notifyDataSetChanged();
        }
    };

Body:
You can add to the SliderBN two properties. One is String path and the other is int index. When you create SliderBN you can just set the values that you want. Then inside your code you can use the property which you need.

public class SliderBN {

    private int index;
    private String path;

    SliderBN(String path, int index){
        this.index = index;
        this.path = path;
    }

    public int getIndex() {
        return index;
    }

    public String getPath() {
        return path;
    }
}

In the beginning when you create image you can do:

String pathToImages = Environment.getDataDirectory().getAbsolutePath() + "/data/sk.lotario.bg/app_imgBuns/";

List<SliderBN> sliderBNS = new ArrayList<>();
// Here you need to be sure that you always have the images else you will
// receive exceptions! If this images will be dynamically added/removed then
// you need another way for retrieving the names and loading them in the list.
for(int i = 0; i < Recipe.bnPos; i++){
    sliderBNS.add(new SliderBN(pathToImages + i + ".png", i));
}

For example where you need to set the image path you can just call getPath method:

class SliderViewHolder extends RecyclerView.ViewHolder {

    private ImageView imageView;

    SliderViewHolder(@NonNull View itemView) {
        super(itemView);
        imageView = itemView.findViewById(R.id.imageSlide);
    }
    void setImage(SliderBN sliderBN){
        // Here you can set the path to the image
        // I saw that you setImageResource(int resId)
        // But for this to work you need the Image ids
        // In the current case we can use setImageURI(Uri uri)
        // With Uri you need to provide the path to the image not the id

         File imgFile = new File(sliderBun.getPath());
         if(imgFile.exists())
         {
             Uri uri = Uri.fromFile(imgFile);
             imageView.setImageURI(uri);
         }
         else
         {
             // Log here message that the file does not exist
             // and also log the path so you can see what is going wrong
         }
    }
}

NOTE: As your code is right now you do not need index (int) in class SliderBN because you have this information in the list where you add all images in the beginning. Still I don't know all of your use-cases that why I left it. See example of using index of the list to get the Object on that position:

@Override
public void onBindViewHolder(@NonNull SliderViewHolder holder, int position)
{
    // Here we get SliderBN object from the list by list position and not by
    // internal properties
    holder.setImage(sliderBNS.get(position));
    if (position == sliderBNS.size()) {
        vpBN.post(runnable);
    }
}

One place where you will need index is if you have List with unsorted SliderBN objects and you need easily to sort them. Then you can use this property index to sort the objects in that List. But in your case you create the images from growing index inside of for loop so your list actually is sorted.

Good luck to all!