问:
C comparison between -1 and 65535/4294967295/18446744073709551615
I have a misunderstanding about the following statements:

```<code>printf("%d\n", -1 == 65535);
printf("%d\n", -1 == 4294967295UL);
printf("%d\n", -1 == 18446744073709551615);
printf("%d\n", -1 == 18446744073709551615UL);
</code>```

The output is:

```<code>0
0
0
1
</code>```

If if don't add the UL suffixes the compiler gives the following warning: main.c:36:28: warning: integer constant is so large that it is unsigned

Can someone explain this to me please? Why for 18446744073709551615 the result is 0 but for 18446744073709551615UL the results is 1? It's ok not to add that suffix?

Thanks

答:
The result depends on the type the compiler selects for integer constants.

If an integer decimal constant does not have a suffix then the compiler considers the following types to represent a constant: int, long int. long long int.

This value 18446744073709551615 is a maximum value that can be stored in an object of the type unsigned long or unsigned long long. It can not be represented as having the type signed long int or signed long long int.

When a constant is specified with a suffix ul or UL the compiler considers sequentially the types unsigned long int and unsigned long long int and selects the first type an object of which can represent the constant.

So in this expression

```<code>-1 == 18446744073709551615UL
</code>```

the right operand of the comparison has the maximum value represented in the corresponding unsigned integer type selected by the compiler and the left operand is converted to this type by promoting the sign bit due to the usual arithmetic conversions. As a result -1 is represented as the maximum unsigned value stored in the selected unsigned integer type.

By the way it seems that in the used by you system sizeof( unsigned long ) is equal to sizeof( unsigned long long ). Otherwise if sizeof( unsigned long ) would be equal to sizeof( unsigned int ) (as it is in Windows) then this call

```<code>printf("%d\n", -1 == 4294967295UL);
</code>```

also outputted 1.

Body:
I have a misunderstanding about the following statements:

printf("%d\n", -1 == 65535);
printf("%d\n", -1 == 4294967295UL);
printf("%d\n", -1 == 18446744073709551615);
printf("%d\n", -1 == 18446744073709551615UL);

The output is:

0
0
0
1

If if don't add the UL suffixes the compiler gives the following warning: main.c:36:28: warning: integer constant is so large that it is unsigned

Can someone explain this to me please? Why for 18446744073709551615 the result is 0 but for 18446744073709551615UL the results is 1? It's ok not to add that suffix?

Thanks

Body:
The result depends on the type the compiler selects for integer constants.

If an integer decimal constant does not have a suffix then the compiler considers the following types to represent a constant: int, long int. long long int.

This value 18446744073709551615 is a maximum value that can be stored in an object of the type unsigned long or unsigned long long. It can not be represented as having the type signed long int or signed long long int.

When a constant is specified with a suffix ul or UL the compiler considers sequentially the types unsigned long int and unsigned long long int and selects the first type an object of which can represent the constant.

So in this expression

-1 == 18446744073709551615UL

the right operand of the comparison has the maximum value represented in the corresponding unsigned integer type selected by the compiler and the left operand is converted to this type by promoting the sign bit due to the usual arithmetic conversions. As a result -1 is represented as the maximum unsigned value stored in the selected unsigned integer type.

By the way it seems that in the used by you system sizeof( unsigned long ) is equal to sizeof( unsigned long long ). Otherwise if sizeof( unsigned long ) would be equal to sizeof( unsigned int ) (as it is in Windows) then this call

printf("%d\n", -1 == 4294967295UL);

also outputted 1.


来源: stackexchange

问:
How to pass the latitude and longitude values to the ns url?
Iam developing one application.In that i use the google api for getting the location information.For that i use the CLLocationManager for getting the location latitude and longitude values.And my pblm is how to pass these latitude and longitude values to nsurl .ANd iam directly given the one location values to the url like below.

```<code>NSURL *URL = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search           /json?location=40.7143528,-74.0059731&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];
</code>```

I write this one in below method for get and pass the latitude and longitude values.

```<code>- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}
</code>```

So please tell me how to pass the newlocation.Coordinates.latitude and newlocation.Coordinates.longitude to that url in that method. Or Is there any way to pass that values in any other method.

答:
Try This,</p>

```<code>NSURL *addressUrl = [NSURL URLWithString:[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%@,%@&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM",newLocation.latitude, newLocation.longitude, nil]];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Iam developing one application.In that i use the google api for getting the location information.For that i use the CLLocationManager for getting the location latitude and longitude values.And my pblm is how to pass these latitude and longitude values to nsurl .ANd iam directly given the one location values to the url like below.

NSURL *URL = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search           /json?location=40.7143528,-74.0059731&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];

I write this one in below method for get and pass the latitude and longitude values.

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}

So please tell me how to pass the newlocation.Coordinates.latitude and newlocation.Coordinates.longitude to that url in that method. Or Is there any way to pass that values in any other method.

Body:
Try This,

NSURL *addressUrl = [NSURL URLWithString:[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%@,%@&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM",newLocation.latitude, newLocation.longitude, nil]];


问:
Fetching YT video, channel or none
Given a url list, how can I divide it to 3 sum lists?

one for YT videos, second for YT channels, third for all the rest?

```<code>const paragraph1 = 'www.youtube.com/watch?v=NsjeEt1ZpqQ';
const regex1 = /www.youtube.com/(\c*)(watch?v=)?<videoId>[A-Z,0-9])/gi;

const paragraph2 = 'https://www.youtube.com/channel/UCKqFqiCe1dCUxRe0_YNZ6gg';
const regex2 = /www.youtube.com/channel/?<channelId>[A-Z,_,0-9])/gi;

const found = paragraph1.match(regex1);
console.log(found);
// expected output: Array ["T", "I"]

const found = paragraph2.match(regex2);
console.log(found);
</code>```

Tried to sandbox on this site.

答:
Since you are planning to split some URL string list into three different parts, you can use three different patterns:

www\.youtube\.com\/watch\?v=(?<videoId>\S+)
www\.youtube\.com\/channel\/(?<videoId>\S+)
www\.youtube\.com(?!\/(?:channel\/|watch\?v=))\S*
```

See regex #1, regex #2 and regex #3 demos. Note you need an ECMAScript 2018+ compliant JavaScript environment for the named capturing groups to work. Also, see the dots are escaped everywhere they denote literal dots.

The patterns mean

www\.youtube\.com\/watch\?v= - a literal www.youtube.com/watch?v=
string

(?<videoId>\S+) - Group "videoId": one or more non-whitespace chars

www\.youtube\.com\/channel\/(?<videoId>\S+) - a literal www.youtube.com/channel/ string and then Group "videoId" capturing one or more non-whitespace chars

www\.youtube\.com(?!\/(?:channel\/|watch\?v=))\S* - www.youtube.com string and then a negative lookahead that fails the match if, immediately to the right, there is a / char, then channel/ or watch?v=, and then zero or more non-whitespace chars are consumed.

If you plan to use the patterns agains some mark-up text, make sure you subtract the mark-up chars from the \S pattern, that is, change it into a negated character class with a reverse shorthand, [^\s], and add the chars after \s. Say, if the links are inside double quotes, put " there, [^\s"].

ContentLicense: CC BY-SA 4.0

Title: Fetching YT video, channel or none

Body:
Given a url list, how can I divide it to 3 sum lists?

one for YT videos, second for YT channels, third for all the rest?

const paragraph1 = 'www.youtube.com/watch?v=NsjeEt1ZpqQ';
const regex1 = /www.youtube.com/(\c*)(watch?v=)?<videoId>[A-Z,0-9])/gi;

const paragraph2 = 'https://www.youtube.com/channel/UCKqFqiCe1dCUxRe0_YNZ6gg';
const regex2 = /www.youtube.com/channel/?<channelId>[A-Z,_,0-9])/gi;

const found = paragraph1.match(regex1);
console.log(found);
// expected output: Array ["T", "I"]

const found = paragraph2.match(regex2);
console.log(found);

Tried to sandbox on this site.

Body:
Since you are planning to split some URL string list into three different parts, you can use three different patterns:

www\.youtube\.com\/watch\?v=(?<videoId>\S+)
www\.youtube\.com\/channel\/(?<videoId>\S+)
www\.youtube\.com(?!\/(?:channel\/|watch\?v=))\S*

See regex #1, regex #2 and regex #3 demos. Note you need an ECMAScript 2018+ compliant JavaScript environment for the named capturing groups to work. Also, see the dots are escaped everywhere they denote literal dots.

The patterns mean

www\.youtube\.com\/watch\?v= - a literal www.youtube.com/watch?v=
string

(?<videoId>\S+) - Group "videoId": one or more non-whitespace chars

www\.youtube\.com\/channel\/(?<videoId>\S+) - a literal www.youtube.com/channel/ string and then Group "videoId" capturing one or more non-whitespace chars

www\.youtube\.com(?!\/(?:channel\/|watch\?v=))\S* - www.youtube.com string and then a negative lookahead that fails the match if, immediately to the right, there is a / char, then channel/ or watch?v=, and then zero or more non-whitespace chars are consumed.

If you plan to use the patterns agains some mark-up text, make sure you subtract the mark-up chars from the \S pattern, that is, change it into a negated character class with a reverse shorthand, [^\s], and add the chars after \s. Say, if the links are inside double quotes, put " there, [^\s"].


问:
UITableView's indexPathsForVisibleRows updates all cells except one
I have a UITableView which populate it cells with a NSFetchedResultsController. Also I use indexPathsForVisibleRows to update visible cells except the one I tapped and edit. But the UI updates all cells with proper calculation except one. If I scroll that tableView then that cell recalculate itself next time it becomes visible.

GIF with the problem: CLICK

There I define the cell to edit and reload Rows for all cells except the one I am editing:

```<code>    func textFieldDidChangeSelection(_ textField: UITextField) {
    let tapLocation = textField.convert(textField.bounds.origin, to: tableView)
    guard let indexPath = tableView.indexPathForRow(at: tapLocation) else { return }
    pickedCurrency = fetchedResultsController.object(at: indexPath)

    let visibleIndexPath = tableView.indexPathsForVisibleRows ?? []
    var nonActiveIndexPaths = [IndexPath]()

    for index in visibleIndexPath where index != indexPath {
        nonActiveIndexPaths.append(index)
    }

    tableView.reloadRows(at: nonActiveIndexPaths, with: .none)
}
</code>```

Why the UI updates all cells except one? Can't find the reason...

答:
Here is how I managed to solve my problem. The thing I understood is I should avoid using tableView.indexPathsForVisibleRows for my case since as @ShawnFrank stated it will reload only visible cells:

```<code>func textFieldDidChangeSelection(_ textField: UITextField) {

     //Code for defining an active cell (on which I clicked to edit its textField)
    let tapLocation = textField.convert(textField.bounds.origin, to: tableView)
    guard let pickedCurrencyIndexPath = tableView.indexPathForRow(at: tapLocation) else { return }
    pickedCurrency = fetchedResultsController.object(at: pickedCurrencyIndexPath)

    //Array for all IndexPaths which is not selected, i.e. not active
    var nonActiveIndexPaths = [IndexPath]()

    //Define all rows tableView has at the moment for particular section
    //In my case it can be only 1 section which starts at 0 index
    let tableViewRows = tableView.numberOfRows(inSection: 0)
    for i in 0..<tableViewRows {
    //Create indexPath with the rows and section
        let indexPath = IndexPath(row: i, section: 0)
    //Add all IndexPaths to previously created array, except the one that is active now
        if indexPath != pickedCurrencyIndexPath {
            nonActiveIndexPaths.append(indexPath)
        }
    }
    //Reload only rows from the array
    tableView.reloadRows(at: nonActiveIndexPaths, with: .none)
}
</code>```

Body:
I have a UITableView which populate it cells with a NSFetchedResultsController. Also I use indexPathsForVisibleRows to update visible cells except the one I tapped and edit. But the UI updates all cells with proper calculation except one. If I scroll that tableView then that cell recalculate itself next time it becomes visible.

GIF with the problem: CLICK

There I define the cell to edit and reload Rows for all cells except the one I am editing:

    func textFieldDidChangeSelection(_ textField: UITextField) {
    let tapLocation = textField.convert(textField.bounds.origin, to: tableView)
    guard let indexPath = tableView.indexPathForRow(at: tapLocation) else { return }
    pickedCurrency = fetchedResultsController.object(at: indexPath)

    let visibleIndexPath = tableView.indexPathsForVisibleRows ?? []
    var nonActiveIndexPaths = [IndexPath]()

    for index in visibleIndexPath where index != indexPath {
        nonActiveIndexPaths.append(index)
    }

    tableView.reloadRows(at: nonActiveIndexPaths, with: .none)
}

Why the UI updates all cells except one? Can't find the reason...

Body:
Here is how I managed to solve my problem. The thing I understood is I should avoid using tableView.indexPathsForVisibleRows for my case since as @ShawnFrank stated it will reload only visible cells:

func textFieldDidChangeSelection(_ textField: UITextField) {

     //Code for defining an active cell (on which I clicked to edit its textField)
    let tapLocation = textField.convert(textField.bounds.origin, to: tableView)
    guard let pickedCurrencyIndexPath = tableView.indexPathForRow(at: tapLocation) else { return }
    pickedCurrency = fetchedResultsController.object(at: pickedCurrencyIndexPath)

    //Array for all IndexPaths which is not selected, i.e. not active
    var nonActiveIndexPaths = [IndexPath]()

    //Define all rows tableView has at the moment for particular section
    //In my case it can be only 1 section which starts at 0 index
    let tableViewRows = tableView.numberOfRows(inSection: 0)
    for i in 0..<tableViewRows {
    //Create indexPath with the rows and section
        let indexPath = IndexPath(row: i, section: 0)
    //Add all IndexPaths to previously created array, except the one that is active now
        if indexPath != pickedCurrencyIndexPath {
            nonActiveIndexPaths.append(indexPath)
        }
    }
    //Reload only rows from the array
    tableView.reloadRows(at: nonActiveIndexPaths, with: .none)
}


问:
Turbo-rails distinct scoped partial broadcast update
I want to broadcast updates of ActiveRecord to distinct partials depending on their scoped route. How could I do that?

Ex: I have a Post model that has_many :comments. Comments can be updated and we have two partials for a comment in the following folders to display them using a distinct template:

/views/comments/_comment.html.erb

```<code><%= turbo_stream_from comment %>
<%= turbo_frame_tag dom_id(comment) do %>
  //one way of displaying the comment
<% end %>
</code>```

/views/visitor/comments/_comment.html.erb

```<code><%= turbo_stream_from comment %>
<%= turbo_frame_tag dom_id(comment) do %>
  //another way of displaying the comment
<% end %>
</code>```

Every time I update the record it is broadcasted using turbo-stream.

```<code>class Comment < ApplicationRecord
 broadcasts_to :post
end
</code>```

The issue is that the broadcasted result is using the /views/comments/_comment.html.erb all over the application.
I would want a way to broadcast and re-render the comment using the scoped partial when the view is under a specific scope, and to use the unscoped partial when no scope is defined, is that even possible?

答:
I found the answer in the gem...
This can be performed by changing the dom_id of the visitor comment to "#{dom_id(comment)}_visitor" and passing the partial explicitly in the broadcast_replace_to

/views/visitor/comments/_comment.html.erb

```<code><%= turbo_stream_from comment %>
<%= turbo_frame_tag "#{dom_id(comment)}_visitor" do %>
  //another way of displaying the comment
<% end %>
</code>```
```<code>class Comment < ApplicationRecord
  after_update_commit do
    broadcast_replace_to self
    broadcast_replace_to self, target: "#{dom_id(self)}_visitor", partial: 'visitor/comments/comment'
  end
end
</code>```

Body:
I want to broadcast updates of ActiveRecord to distinct partials depending on their scoped route. How could I do that?

Ex: I have a Post model that has_many :comments. Comments can be updated and we have two partials for a comment in the following folders to display them using a distinct template:

/views/comments/_comment.html.erb

<%= turbo_stream_from comment %>
<%= turbo_frame_tag dom_id(comment) do %>
  //one way of displaying the comment
<% end %>

/views/visitor/comments/_comment.html.erb

<%= turbo_stream_from comment %>
<%= turbo_frame_tag dom_id(comment) do %>
  //another way of displaying the comment
<% end %>

Every time I update the record it is broadcasted using turbo-stream.

class Comment < ApplicationRecord
 broadcasts_to :post
end

The issue is that the broadcasted result is using the /views/comments/_comment.html.erb all over the application.
I would want a way to broadcast and re-render the comment using the scoped partial when the view is under a specific scope, and to use the unscoped partial when no scope is defined, is that even possible?

Body:
I found the answer in the gem...
This can be performed by changing the dom_id of the visitor comment to "#{dom_id(comment)}_visitor" and passing the partial explicitly in the broadcast_replace_to

/views/visitor/comments/_comment.html.erb

<%= turbo_stream_from comment %>
<%= turbo_frame_tag "#{dom_id(comment)}_visitor" do %>
  //another way of displaying the comment
<% end %>

class Comment < ApplicationRecord
  after_update_commit do
    broadcast_replace_to self
    broadcast_replace_to self, target: "#{dom_id(self)}_visitor", partial: 'visitor/comments/comment'
  end
end


问:
Android Studio - RecyclerView with API level 19 (API 19)
I need to use RecyclerView with API 19 (API level 19).

I already have tried adding

```<code>implementation 'com.android.support:recyclerview-v7:+'
</code>```

and

```<code>implementation 'androidx.recyclerview:recyclerview:1.0.0'
</code>```

in build.gradle but no success. I am new to Android development. I have checked 3-4 similar questions but no solution worked for me.
Please if someone can tell me all of the changes I need to make in build.gradle, XML and/or in manifest file?

Thank you!

答: For these cases, apart from the things you mentioned, I also invalidate cache and restart. This helps me a lot sometimes.</p>

Body:
I need to use RecyclerView with API 19 (API level 19).

I already have tried adding

implementation 'com.android.support:recyclerview-v7:+'

and

implementation 'androidx.recyclerview:recyclerview:1.0.0'

in build.gradle but no success. I am new to Android development. I have checked 3-4 similar questions but no solution worked for me.
Please if someone can tell me all of the changes I need to make in build.gradle, XML and/or in manifest file?

Thank you!


问:
How can make a view get rendered for changing a value in SwiftUI
Here is my code:

```<code>struct ContentView: View {
    @State private var value: Int = 0
    var body: some View {

        VStack {
            if value.isMultiple(of: 2) {
                myView1
            }
            else {
                myView2
            }
        }

        Button("update with + 1") { value += 1 }

        Button("update with + 2") { value += 2 }

    }

    var myView1: some View {
        return Circle().frame(width: 100, height: 100)
    }

    var myView2: some View {
        return Rectangle().frame(width: 100, height: 100)
    }
}
</code>```

As you can see I am drawing a new view depending on value if isMultiple of 2 or not in button one. How ever it is possible that value updated to new value but the new and old value are both multiple of 2 or not in same time that cause no update in view on second button action.

I thought that could help me if check for value.hashValue.isMultiple(of: 2) but that did not helped so much also because sometimes hashValue of value could be same for old and new value, so I am looking for a sold way to draw new view depending on change of value regardless what the value could be, odd or even, I want my view get re-draw in any case. How can solve this problem? for me having if (Condition) {} else {} is a must in my question.

Also I am not looking to save old value and compare to newValue. I am looking the best Condition for if condition without having look to old value.

答:
I think what you are looking for is to simply use modulo "%" which gives you the remainder in division. To determine whether a number is even use value % 2 == 0. If true, then it is even, if not it is odd. Your code then becomes:

```<code>struct ContentView: View {
    @State private var value: Int = 0
    var body: some View {

        VStack {
            if value % 2 == 0 {
                myView1
                    .padding()
            }
            else {
                myView2
                    .padding()
            }

        Button("update with + 1") { value += 1 }
        .padding()

        Button("update with + 2") { value += 2 }
        }
    }

    var myView1: some View {
        return Circle().frame(width: 100, height: 100)
    }

    var myView2: some View {
        return Rectangle().frame(width: 100, height: 100)
    }
}
</code>```

Edit:

I am not sure how you are having issues with this, but here is your the above code running in the simulator:

Body:
Here is my code:

struct ContentView: View {
    @State private var value: Int = 0
    var body: some View {

        VStack {
            if value.isMultiple(of: 2) {
                myView1
            }
            else {
                myView2
            }
        }

        Button("update with + 1") { value += 1 }

        Button("update with + 2") { value += 2 }

    }

    var myView1: some View {
        return Circle().frame(width: 100, height: 100)
    }

    var myView2: some View {
        return Rectangle().frame(width: 100, height: 100)
    }
}

As you can see I am drawing a new view depending on value if isMultiple of 2 or not in button one. How ever it is possible that value updated to new value but the new and old value are both multiple of 2 or not in same time that cause no update in view on second button action.

I thought that could help me if check for value.hashValue.isMultiple(of: 2) but that did not helped so much also because sometimes hashValue of value could be same for old and new value, so I am looking for a sold way to draw new view depending on change of value regardless what the value could be, odd or even, I want my view get re-draw in any case. How can solve this problem? for me having if (Condition) {} else {} is a must in my question.

Also I am not looking to save old value and compare to newValue. I am looking the best Condition for if condition without having look to old value.

Body:
I think what you are looking for is to simply use modulo "%" which gives you the remainder in division. To determine whether a number is even use value % 2 == 0. If true, then it is even, if not it is odd. Your code then becomes:

struct ContentView: View {
    @State private var value: Int = 0
    var body: some View {

        VStack {
            if value % 2 == 0 {
                myView1
                    .padding()
            }
            else {
                myView2
                    .padding()
            }

        Button("update with + 1") { value += 1 }
        .padding()

        Button("update with + 2") { value += 2 }
        }
    }

    var myView1: some View {
        return Circle().frame(width: 100, height: 100)
    }

    var myView2: some View {
        return Rectangle().frame(width: 100, height: 100)
    }
}

Edit:

I am not sure how you are having issues with this, but here is your the above code running in the simulator:


问:
Angular can’t reach Django REST deployed in AWS private subnet
I have a web application divided in two projects django rest api as a backend and angular as a frontend. And there is for sure http api calls from angular to Django

Django is hosted in elastic beanstalk in a private subnet
While angular is on cloudfront + S3 bucket.

I know that when using a static web app in cloudfront and S3, Http calls will be from the user browser.

my question is

How to make the two of them connect together without exposing my Django app to the internet?

And what is the preferred solution architecture for cases like this?

As the Django rest API is built to serve the angular app only it’s not for public use!!

答:
How to make the two of them connect together without exposing my Django app to the internet?

That is impossible. Everyone's browser needs access to it, so it has to be on the Internet.

You can look into something like placing AWS API Gateway in front of it, and enable API tokens or something to add a layer of security. But ultimately the API endpoints that the Angular app hits must be on the public Internet.


问:
How to reference property of static library
I'm referencing another project's target static library. I successfully followed instructions from this site. Below is the project using a class named FileIO from the library.

I create a FileIO object and assign a string to its name property. Then I get a __TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION__ on the assignment of name.

In applicationDidFinishLaunching I do this:

```<code>fileObj = [[FileIO alloc] init];
fileObj.name = @"test";
</code>```

and this is in the .h file:

```<code>@class FileIO;

@interface Nav1AppDelegate : NSObject <UIApplicationDelegate> {

    UIWindow *window;
    UINavigationController *navigationController;
    FileIO *fileObj;
}
</code>```

In the library, FileIO is a simple class with name in it. I have also tried [fileObj setName:@"test"] but get the same results.  Here's the stack trace:

```<code>2009-04-01 20:37:17.721 NavNew[81425:20b] *** -[FileIO setName:]: unrecognized selector sent to instance 0x5219b0

2009-04-01 20:37:17.723 NavNew[81425:20b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[FileIO setName:]: unrecognized selector sent to instance 0x5219b0'

2009-04-01 20:37:17.724 NavNew[81425:20b] Stack: (

    2454561035,
    2461146683,
    2454590218,
    2454583564,
    2454583762,
    11275,
    816111650,
    816149355,
    2455110190,
    2454063909,
    2454064344,
    827745792,
    827745989,
    816114848,
    816160924,
    11128,
    10982
)
(gdb)
</code>```

I have discovered this is a problem only with instance members (property or method).  Static methods work fine.  I also opened the library .a file in the hosting project.  I don't see the instance property anywhere in it.

Any suggestions on what I'm doing wrong?

答:
In the instructions you used to "import" the static library, the author describes several cases of strange errors occurring somewhat randomly, which is why I'd suggest a different approach: using an Xcode cross-project reference and shared build output directory. Here's a link to a tutorial with screenshots: http://www.clintharris.net/2009/iphone-app-shared-libraries/

I've been using this strategy for several months with multiple projects and static libraries--it's been great and I haven't experienced any problems. The other really nice perk is that you use an Xcode environment variable to reference the project with the static library (including the header files); this makes the solution really flexible if you have multiple developers working on the same project, need to move directories around, etc.

Body:
I'm referencing another project's target static library. I successfully followed instructions from this site. Below is the project using a class named FileIO from the library.

I create a FileIO object and assign a string to its name property. Then I get a __TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION__ on the assignment of name.

In applicationDidFinishLaunching I do this:

fileObj = [[FileIO alloc] init];
fileObj.name = @"test";

and this is in the .h file:

@class FileIO;

@interface Nav1AppDelegate : NSObject <UIApplicationDelegate> {

    UIWindow *window;
    UINavigationController *navigationController;
    FileIO *fileObj;
}

In the library, FileIO is a simple class with name in it. I have also tried [fileObj setName:@"test"] but get the same results.  Here's the stack trace:

2009-04-01 20:37:17.721 NavNew[81425:20b] *** -[FileIO setName:]: unrecognized selector sent to instance 0x5219b0

2009-04-01 20:37:17.723 NavNew[81425:20b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[FileIO setName:]: unrecognized selector sent to instance 0x5219b0'

2009-04-01 20:37:17.724 NavNew[81425:20b] Stack: (

    2454561035,
    2461146683,
    2454590218,
    2454583564,
    2454583762,
    11275,
    816111650,
    816149355,
    2455110190,
    2454063909,
    2454064344,
    827745792,
    827745989,
    816114848,
    816160924,
    11128,
    10982
)
(gdb)

I have discovered this is a problem only with instance members (property or method).  Static methods work fine.  I also opened the library .a file in the hosting project.  I don't see the instance property anywhere in it.

Any suggestions on what I'm doing wrong?

OwnerDisplayName: Clint

ContentLicense: CC BY-SA 2.5


问:
Positioning a image onto another
I want to develop a program (in C#) that has following needs:

I want a webcam to take a image and display it on a picturebox (THIS I CAN DO)

Now i have a set of other images with me and i want to drag and drop these images on the clicked image and position them right with the mouse. Is it possible to put that photoshop functionality where you drag and position a picture over another and when you click save that becomes one single picture.It is more like i have a background image and i want to exactly position another image(s) onto the background image using the drag and drop functionality  Any answers are most appreciated. Thanking you guys in advance.

答:
The code in the following links may help you:

http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/360629bb-633c-4eeb-92a4-0af75de893fd/

http://www.codeguru.com/forum/showthread.php?t=378090

A PictureBox Problem

Title: Positioning a image onto another


问:
How to make one capturing group of regular expression on bigquery?
I am getting the following error: Regular expressions passed into extraction functions must not have more than 1 capturing group.

And this is what I am trying to extract : regexp_substr(UPPER(tags), r'(TG\d{6})|(BD\d{6})')

Does anyone know how can I change this to one capturing group?

Any help would be appreciated.

答:
Use either of below instead

```<code>regexp_substr(UPPER(tags), r'(TG\d{6}|BD\d{6})')
</code>```

or

```<code>regexp_substr(UPPER(tags), r'(?:TG|BD)\d{6}')
</code>```

Body:
Use either of below instead

regexp_substr(UPPER(tags), r'(TG\d{6}|BD\d{6})')

or

regexp_substr(UPPER(tags), r'(?:TG|BD)\d{6}')


问:
Converting pandas dataframe into a dataframe for network analysis
I read multiple questions, but do not see a solution or missing something

I have a dataframe

```<code>Author_id Article_id Rank
    100     10         1
    101     10         2
    102     10         3
    100     11         1
    105     11         2
    106     11         3
</code>```

Expected output:

```<code> Author_id1 Author_id2 Article_id Rank
   100        101         10        1
   100        102         10        1
   100        105         11        1
   100        106         11        1
   101        100         10        2
   101        102         10        2
   102        100         10        3
   102        101         10        3
   105        100         11        2
   105        106         11        2
   106        100         11        3
   106        105         11        3
</code>```

If my understanding of the the desired dataset is not correct, please advise on how to restructure this data. Thanks!

答:
If the DataFrame isn't duplicated on ['Author_id', 'Article_id'], you can do a self-merge within article, and filter out the rows that merged with themself.

```<code>df1 = (df.merge(df.drop(columns='Rank'), on='Article_id', suffixes = ['1', '2'])
         .query('Author_id1 != Author_id2')
         .sort_values(['Author_id1', 'Rank'])
         .reset_index(drop=True))
</code>```

```<code>    Author_id1  Article_id  Rank  Author_id2
0          100          10     1         101
1          100          10     1         102
2          100          11     1         105
3          100          11     1         106
4          101          10     2         100
5          101          10     2         102
6          102          10     3         100
7          102          10     3         101
8          105          11     2         100
9          105          11     2         106
10         106          11     3         100
11         106          11     3         105
</code>```

Body:
I read multiple questions, but do not see a solution or missing something

I have a dataframe

Author_id Article_id Rank
    100     10         1
    101     10         2
    102     10         3
    100     11         1
    105     11         2
    106     11         3

Expected output:

 Author_id1 Author_id2 Article_id Rank
   100        101         10        1
   100        102         10        1
   100        105         11        1
   100        106         11        1
   101        100         10        2
   101        102         10        2
   102        100         10        3
   102        101         10        3
   105        100         11        2
   105        106         11        2
   106        100         11        3
   106        105         11        3

If my understanding of the the desired dataset is not correct, please advise on how to restructure this data. Thanks!

Body:
If the DataFrame isn't duplicated on ['Author_id', 'Article_id'], you can do a self-merge within article, and filter out the rows that merged with themself.

df1 = (df.merge(df.drop(columns='Rank'), on='Article_id', suffixes = ['1', '2'])
         .query('Author_id1 != Author_id2')
         .sort_values(['Author_id1', 'Rank'])
         .reset_index(drop=True))

    Author_id1  Article_id  Rank  Author_id2
0          100          10     1         101
1          100          10     1         102
2          100          11     1         105
3          100          11     1         106
4          101          10     2         100
5          101          10     2         102
6          102          10     3         100
7          102          10     3         101
8          105          11     2         100
9          105          11     2         106
10         106          11     3         100
11         106          11     3         105


问:
Get DIV that has an IMG child with an ALT "dog"?
Is it possible to get a DIV that has an IMG child with an ALT "dog" with XPath?</p>
```<code>....
<div>fake<div>
<div><img alt="cat"/>sike<div>
<div><img alt="dog"/>real<div> <-- get this div
....
</code>```

答:
Yes, it is possible.

This XPath will do that:

//div[.//img[@alt='dog']]
```

Body:
Is it possible to get a DIV that has an IMG child with an ALT "dog" with XPath?

....

fake

sike

real
 <-- get this div
....


问:
Why does pthread_join not take a thread pointer?
Pretty self explanatory question. For example, the header for pthread_create shows it takes a pointer to a thread:

```<code>int WINPTHREAD_API pthread_create(pthread_t *th, const pthread_attr_t *attr, void *(* func)(void *), void *arg);
</code>```

OK, makes sense, you allocate a pthread in memory then pass a pointer to pthread_create so it gets initialized... but now looking at the header for pthread_join:

```<code>int WINPTHREAD_API pthread_join(pthread_t t, void **res);
</code>```

It takes a copy of the pthread_t. I just don't get why it doesn't take a pointer to that already existing thread, rather than copying it and passing it over; it seems like if anything, doing so would cause more problems and more memory use. Am I missing something? I read the manpage, it doesn't seem to offer a reason to this.

答:
A pthread_t is a small object which identifies a thread. It could be a pointer, integer or perhaps a tiny structure. The pthread_t isn't actually the thread itself any more than a HWND object in Win32 is the window itself.

The pthread_create function returns this identifier via a pointer pointer because it already returns a value of type int for error indication. Other functions take pthread_t by value.

For instance, to compare whether two pthread_t objects refer to the same thread, you should use pthread_equal, which takes two pthread_t parameters. It's possible that all this function does is compare the two values using ==, but doing that directly wouldn't be as portable. It won't even compile if pthread_t happens to be a small structure.

Body:
Pretty self explanatory question. For example, the header for pthread_create shows it takes a pointer to a thread:

int WINPTHREAD_API pthread_create(pthread_t *th, const pthread_attr_t *attr, void *(* func)(void *), void *arg);

OK, makes sense, you allocate a pthread in memory then pass a pointer to pthread_create so it gets initialized... but now looking at the header for pthread_join:

int WINPTHREAD_API pthread_join(pthread_t t, void **res);

It takes a copy of the pthread_t. I just don't get why it doesn't take a pointer to that already existing thread, rather than copying it and passing it over; it seems like if anything, doing so would cause more problems and more memory use. Am I missing something? I read the manpage, it doesn't seem to offer a reason to this.


问:
Why is JWE better than just encrypting content/payload with RSA/AES?
We want to use token for some services (which we own and develop) and we are considering to implement JWE or Paseto.

Token and payload should be encrypted (some string or json).

What is benefit of using JWE or something rather than just encrypting payload with some algorithm and use it as a token?

答:
Why is JWE better than just encrypting content/payload with RSA/HMAC?

HMAC would be "signing" (not technically I know) but it's not encryption, it's ensuring integrity and authenticity. RSA in the context of JOSE would be either public key encryption key management (encryption for a recipient using a "wrapped" random content encryption key) to achieve confidentiality, or digital signatures (integrity and authenticity but not confidentiality).

What using either of the protocols will do over just barebones encryption is that it ensures you won't end up with unauthenticated encryption. JOSE and PASETO always ensure integrity in their used cipher (or combination of ciphers).

You can find plenty of polarizing opinions on PASETO and JOSE, in the end it boils down to what you prefer for your service.

You can achieve everything PASETO can do with JOSE. PASETO has public tokens (signed) using RSASSA-PSS, ECDSA, and EdDSA - JOSE does too. PASETO has local (symmetrically encrypted) tokens using AES and XChaCha - JOSE does too (former always, latter not yet registered and widely supported).

OTOH you cannot achieve everything JOSE can do with PASETO. JOSE supports encryption for a recipient using their public key. PASETO on its own does not - that's what PASERK, an independent - rather new protocol with very lacking library support, from the authors of PASETO, is for.

It sounds like what you want to do is symmetric encryption. Using either of the two protocols it boils down to whether you want cryptographic agility (JOSE) or not (PASETO) and whether there's existing library/module to use for the languages you intend to use.

I've implemented both JOSE and PASETO in their (almost) full specification for javascript runtimes.

Edit covering the comments in the original questions:

We just do not see any benefit of using JWE

The benefit is confidentiality. A signed payload anyone can decode and read. An encrypted one only the intended recipient can. You should make up your mind whether you want just authentic and integrity protected tokens (that's JWS or public PASETO) or confidential ones (that's JWE or local PASETO).


问:
Why doesn't .NET have a SoftReference as well as a WeakReference, like Java?
I really love WeakReference's. But I wish there was a way to tell the CLR how much (say, on a scale of 1 to 5) how weak you consider the reference to be. That would be brilliant.

Java has SoftReference, WeakReference and I believe also a third type called a "phantom reference". That's 3 levels right there which the GC has a different behaviour algorithm for when deciding if that object gets the chop.

I am thinking of subclassing .NET's WeakReference (luckily and slightly bizzarely it isn't sealed) to make a pseudo-SoftReference that is based on a expiration timer or something.

答: I believe the fundamental reason that NET does not have soft references is because it can rely on an operating system with virtual memory.  A Java process must specify its maximum OS memory (e.g. with -Xmx128M), and it never takes more OS memory than that.  Whereas a NET process keeps taking OS memory that it needs, which the OS supplies with disk-backed virtual memory when RAM runs out.  If NET allowed soft references, then the NET runtime would not know when to release them unless it either peeked deep into the OS to see if its memory is actually paged on disk (a nasty OS/CLR dependency), or it requested the runtime to specify a maximum process memory footprint (e.g. an equivalent of -Xmx).  I guess that Microsoft does not want to add -Xmx to NET because they think the OS should decide how much RAM each process gets (by choosing which virtual memory pages to hold in RAM or on disk), and not the process itself.

OwnerDisplayName: Nathan Evans


问:
pandas: combine columns if they share a partly similar name
I have a DataFrame as follows,

```<code>import pandas as pd
df = pd.DataFrame({'sent_a.1': [0, 3, 2, 1],
               'sent_a.2': [0, 1, 4, 0],
               'sent_b.3': [0, 6, 0, 8],
               'sent_b.4': [1, 1, 8, 6]
               })
</code>```

I want to combine the columns that share a name. so the desired output would be,

```<code>    sent_a  sent_b
0     0,0    0,1
1     3,1    6,1
2     2,4    0,8
3     1,0    8,6
</code>```

I have done the following and the code works, but since my original DataFrame has more than 200 columns, I am looking for a faster way of doing that.

```<code>df['sent_a'] = df['sent_a.1']+','+ df['sent_a.2']
df['sent_b'] = df['sent_b.1']+','+ df['sent_b.2']
df = df.drop(['sent_a.1', 'sent_a.2', 'sent_b.3', 'sent_b.4'], axis=1)
</code>```

答:
You can make the columns MultiIndex and unstack and groupby the index and apply join to get a Series similar to the desired outcome. swaplevel + unstack will fetch the desired DataFrame.

```<code>df.columns = pd.MultiIndex.from_tuples(col.split('.') for col in df.columns)
out = df.unstack().astype(str).droplevel(1).groupby(level=[0,1]).agg(','.join).swaplevel().unstack()
</code>```

Output:

```<code>  sent_a sent_b
0    0,0    0,1
1    3,1    6,1
2    2,4    0,8
3    1,0    8,6
</code>```

Body:
I have a DataFrame as follows,

import pandas as pd
df = pd.DataFrame({'sent_a.1': [0, 3, 2, 1],
               'sent_a.2': [0, 1, 4, 0],
               'sent_b.3': [0, 6, 0, 8],
               'sent_b.4': [1, 1, 8, 6]
               })

I want to combine the columns that share a name. so the desired output would be,

    sent_a  sent_b
0     0,0    0,1
1     3,1    6,1
2     2,4    0,8
3     1,0    8,6

I have done the following and the code works, but since my original DataFrame has more than 200 columns, I am looking for a faster way of doing that.

df['sent_a'] = df['sent_a.1']+','+ df['sent_a.2']
df['sent_b'] = df['sent_b.1']+','+ df['sent_b.2']
df = df.drop(['sent_a.1', 'sent_a.2', 'sent_b.3', 'sent_b.4'], axis=1)

Body:
You can make the columns MultiIndex and unstack and groupby the index and apply join to get a Series similar to the desired outcome. swaplevel + unstack will fetch the desired DataFrame.

df.columns = pd.MultiIndex.from_tuples(col.split('.') for col in df.columns)
out = df.unstack().astype(str).droplevel(1).groupby(level=[0,1]).agg(','.join).swaplevel().unstack()

Output:

  sent_a sent_b
0    0,0    0,1
1    3,1    6,1
2    2,4    0,8
3    1,0    8,6


答:
You can groupby on the columns using the left part of the column names as group:

```<code># get left part of name
group = df.columns.str.split('.').str[0]

# groupby and join as string
(df.astype(str).groupby(group, axis=1)
   .apply(lambda d: d.apply(','.join, axis=1))
)
</code>```

output:

```<code>  sent_a sent_b
0    0,0    0,1
1    3,1    6,1
2    2,4    0,8
3    1,0    8,6
</code>```

Title: pandas: combine columns if they share a partly similar name

Body:
You can groupby on the columns using the left part of the column names as group:

# get left part of name
group = df.columns.str.split('.').str[0]

# groupby and join as string
(df.astype(str).groupby(group, axis=1)
   .apply(lambda d: d.apply(','.join, axis=1))
)

output:

  sent_a sent_b
0    0,0    0,1
1    3,1    6,1
2    2,4    0,8
3    1,0    8,6


问:
What is the difference between a virtual environment and a virtual envelope?
Can someone please explain the difference (if any) between a "virtual environment" and a "virtual envelope", within the context of the various Python virtual environment managers?</p>

答:
I can see only three real references to "virtual envelope" using google and two of them appear to potentially be autocomplete issues.

The only reference I see that repeatedly uses this term is from this SO answer:

https://stackoverflow.com/a/59923461/218663

that uses it numerous times to describe what otherwise would be called a "virtual environment".

So:

There is either no difference between "virtual environment" and
"virtual envelope" as they are synonyms or better yet, there just
really is no common term "virtual envelope" and when you see it, the
author meant to type "virtual environment".


问:
JSON column parse in SQL
one of the columns in my database contains an imported JSON file.

Format of JSON:

```<code>"result": true,
"data": {
    "3271012": {
        "taskId": 3271012,
        "opl": 1245,
        "owner": "name",
        "description": "note",
        "date": {
            "date": "2021-06-25 00:00:00.000000",
            "timezone_type": 3,
            "timezone": ""
        },
        "responsible": "responsible name",
        "subject": "note",
    },
    "3261201": {
        "taskId": 3261201,
        "opl": 1236,
        "owner": "name",
        "description": "note",
        "startDate": {
            "date": "2019-08-08 11:46:28.000000",
            "timezone_type": 3,
            "timezone": ""
        },
        "responsible": "responsible name",
        "subject": "note",
</code>```

There are hundreds of objects with taskId (3271012,3261201,...) how can i parse this tasks from one column to multiple rows?

expected output:

答:
First you can get all the "data" items as key-value pairs with OPENJSON and then extract the values of interest

```<code>DECLARE @s varchar(max) =
'{"result": true,
"data": {
    "3271012": {
        "taskId": 3271012,
        "opl": 1245,
        "owner": "name",
        "description": "note",
        "date": {
            "date": "2021-06-25 00:00:00.000000",
            "timezone_type": 3,
            "timezone": ""
        },
        "responsible": "responsible name",
        "subject": "note"
    },
    "3261201": {
        "taskId": 3261201,
        "opl": 1236,
        "owner": "name",
        "description": "note",
        "startDate": {
            "date": "2019-08-08 11:46:28.000000",
            "timezone_type": 3,
            "timezone": ""
        },
        "responsible": "responsible name",
        "subject": "note"
     }
 }}';

select
     json_value(d.value, '$.taskId')  taskid,
     json_value(d.value, '$.opl') opl,
     json_value(d.value, '$.owner') owner,
     cast (json_value(d.value, '$.startDate.date') as datetime2) dt2

from openjson (@s, '$.data') d;
</code>```

The same  for the table tbl(id,jsonstr)

```<code> select t.id,
     json_value(d.value, '$.taskId')  taskid,
     json_value(d.value, '$.opl') opl,
     json_value(d.value, '$.owner') owner,
     cast (json_value(d.value, '$.startDate.date') as datetime2) dt2
from tbl t
cross apply openjson (jsonstr, '$.data') d;
</code>```

db<>fiddle

Title: JSON column parse in SQL

Body:
one of the columns in my database contains an imported JSON file.

Format of JSON:

"result": true,
"data": {
    "3271012": {
        "taskId": 3271012,
        "opl": 1245,
        "owner": "name",
        "description": "note",
        "date": {
            "date": "2021-06-25 00:00:00.000000",
            "timezone_type": 3,
            "timezone": ""
        },
        "responsible": "responsible name",
        "subject": "note",
    },
    "3261201": {
        "taskId": 3261201,
        "opl": 1236,
        "owner": "name",
        "description": "note",
        "startDate": {
            "date": "2019-08-08 11:46:28.000000",
            "timezone_type": 3,
            "timezone": ""
        },
        "responsible": "responsible name",
        "subject": "note",

There are hundreds of objects with taskId (3271012,3261201,...) how can i parse this tasks from one column to multiple rows?

expected output:

Body:
First you can get all the "data" items as key-value pairs with OPENJSON and then extract the values of interest

DECLARE @s varchar(max) =
'{"result": true,
"data": {
    "3271012": {
        "taskId": 3271012,
        "opl": 1245,
        "owner": "name",
        "description": "note",
        "date": {
            "date": "2021-06-25 00:00:00.000000",
            "timezone_type": 3,
            "timezone": ""
        },
        "responsible": "responsible name",
        "subject": "note"
    },
    "3261201": {
        "taskId": 3261201,
        "opl": 1236,
        "owner": "name",
        "description": "note",
        "startDate": {
            "date": "2019-08-08 11:46:28.000000",
            "timezone_type": 3,
            "timezone": ""
        },
        "responsible": "responsible name",
        "subject": "note"
     }
 }}';

select
     json_value(d.value, '$.taskId')  taskid,
     json_value(d.value, '$.opl') opl,
     json_value(d.value, '$.owner') owner,
     cast (json_value(d.value, '$.startDate.date') as datetime2) dt2

from openjson (@s, '$.data') d;

The same  for the table tbl(id,jsonstr)

 select t.id,
     json_value(d.value, '$.taskId')  taskid,
     json_value(d.value, '$.opl') opl,
     json_value(d.value, '$.owner') owner,
     cast (json_value(d.value, '$.startDate.date') as datetime2) dt2
from tbl t
cross apply openjson (jsonstr, '$.data') d;

db<>fiddle


问:
React native web view Android back button not exit the app
React native web view Android back button not exit the app. When i pressed back button it will not exixt the app. The following are my sample code.</p>
```<code>import React, { useEffect, useRef } from 'react';
import { BackHandler } from 'react-native';
import WebView from 'react-native-webview';

const App = () => {
    const webview = useRef(null);
    const onAndroidBackPress = () => {
    if (webview.current) {
      webview.current.goBack();
      return true;
    }
    return false;
    };

    useEffect(() => {
    BackHandler.addEventListener('hardwareBackPress', onAndroidBackPress);

    return () => {
      BackHandler.removeEventListener('hardwareBackPress', onAndroidBackPress);
    };
    }, []);

    return (
    <WebView source={{ uri: 'https://google.com' }} ref={webview}/>
    )
}
export default App;
</code>```

答: There is a method in Backhandler for exiting app. Did you try it?</p>

Body:
React native web view Android back button not exit the app. When i pressed back button it will not exixt the app. The following are my sample code.

import React, { useEffect, useRef } from 'react';
import { BackHandler } from 'react-native';
import WebView from 'react-native-webview';

const App = () => {
    const webview = useRef(null);
    const onAndroidBackPress = () => {
    if (webview.current) {
      webview.current.goBack();
      return true;
    }
    return false;
    };

    useEffect(() => {
    BackHandler.addEventListener('hardwareBackPress', onAndroidBackPress);

    return () => {
      BackHandler.removeEventListener('hardwareBackPress', onAndroidBackPress);
    };
    }, []);

    return (
    <WebView source={{ uri: 'https://google.com' }} ref={webview}/>
    )
}
export default App;


问:
Connecting to Postgres database with read only access.
Is it possible to restrict my connection to a database through the psql client to be read only. I.E. The role using to connect to the database has full privileges on it, but I want to restrict some of my connections to being read-only.

Is this possible or do I have to simply create a new database role with my desired privileges.

答:
Why not just

SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY;

This command can be issued after the connection is made, i.e. typed into 'psql' after it has started and connected to the database. It will affect all transactions started within the current psql session. There is a variant on the command which affects only the current transaction (see docs below).

This does provide a safeguard against operators accidentally modifying important data, but is not securely read-only - an attacker with access to this connection can simply set the characteristics back to "READ WRITE" again.

Postgresql documentation here.


问:
Importing npm/node.js packages to snel
While exploring 'snel' a compiler for svelte applications, I came across an issue when trying to import remote svelte components

I got the following error, uppon trying to import components.

```<code>TypeError: Cannot read properties of undefined (reading 'svelte')
    at Object.resolveId (https://deno.land/x/snel@v0.6.0/src/shared/bundler.js:57:37)
    at https://unpkg.com/rollup@2.58.0/dist/es/rollup@2.58.0/dist/es/rollup.browser.js:11:370111
</code>```

I did not find any similar problem or could not find out why this import statement would not work.
So I wondered how I can import external components for svelte using deno and snel?

答:
After some more digging I was able to resolve this issue by reading more about how deno works.
I now understand that in deno, and thus in snel, to use npm/node.js svelte packages, you need use CDNs to import something, as shown in the deno manual

I resolved my issue, by using a CDN inside of the following import statement

import * as L from 'https://cdn.skypack.dev/leaflet';
```

You can also use it in an import map as shown in the snel documentation

Title: Importing npm/node.js packages to snel

Body:
While exploring 'snel' a compiler for svelte applications, I came across an issue when trying to import remote svelte components

I got the following error, uppon trying to import components.

TypeError: Cannot read properties of undefined (reading 'svelte')
    at Object.resolveId (https://deno.land/x/snel@v0.6.0/src/shared/bundler.js:57:37)
    at https://unpkg.com/rollup@2.58.0/dist/es/rollup@2.58.0/dist/es/rollup.browser.js:11:370111

I did not find any similar problem or could not find out why this import statement would not work.
So I wondered how I can import external components for svelte using deno and snel?

Body:
After some more digging I was able to resolve this issue by reading more about how deno works.
I now understand that in deno, and thus in snel, to use npm/node.js svelte packages, you need use CDNs to import something, as shown in the deno manual

I resolved my issue, by using a CDN inside of the following import statement

import * as L from 'https://cdn.skypack.dev/leaflet';

You can also use it in an import map as shown in the snel documentation


问:
How to copy notebooks between different Sagemaker instances?
My search didn't yield anything useful so I was wondering if there is any easy way to copy notebooks from one instance to another instance on Sagemaker? Of course other than manually downloading the notebooks on one instance and uploading to the other one!</p>

答:
I might be late to the show, but I had recently to deal with copying the contents of a Sagemaker notebook to a different notebook. This problem may become urgent for users of Sagemaker notebooks on amazon Linux 1 (al1) platform. Such notebooks have 'notebook-al1-v1' platform identifier.  Amazon announced that "Amazon SageMaker Notebook Instance is ending its standard support on Amazon Linux AMI (AL1)" on April 22, 2022.

Now, what are the steps needed to copy of file from one Sagemaker instances to a different one. Or, put it differently, how to synchronize EBS volume attached to one instance (let's call it A) to instance B.

Amazon published  a step-by-step explanation how to do it. The idea is first to synchronize EBS volume of notebook A to a specially created AWS s3 bucket, and second to synchronize contents of that s3 bucket to notebook B. I followed instructions in the post, and it didn't work for me )). I later discovered that the script 'on_start.sh' in 'migrate-ebs-data-backup' provided in Amazon solution has some issues with s3 bucket creation.

Personally I found that rather than do what the Amazon post recommends it's much easier to create the ad hoc basket (let's call it 'ebs-data-backup') manually via console and then:

launch Terminal of notebook A and enter the following code, which will synchronize contents of notebook A to bucket 'ebs-data-backup'

$ cd /home/ec2-user/SageMaker

$ BUCKET_NAME=ebs-data-backup

$ TIMESTAMP=date +%F-%H-%M-%S

$ SNAPSHOT=${NOTEBOOK_NAME}_${TIMESTAMP}

$ aws s3 sync --exclude "/lost+found/" /home/ec2-user/SageMaker/ s3://${BUCKET_NAME}/${SNAPSHOT}/

Start notebook B, launch Terminal in notebook B and enter the following code:

$ cd /home/ec2-user/SageMaker

$ aws s3 sync s3://${BUCKET_NAME}/${SNAPSHOT}/ /home/ec2-user/SageMaker/`

in notebook B use the same values for BUCKET_NAME and SNAPSHOT as in notebook B

echo "THAT SHOULD BE IT. HOPE IT HELPS"


问:
Slug field does not work for Bengali language in django. How to work with slug in bengali
Django slug field does not work for any other language except English. I want to work with Bengali language
here is the code</p>
```<code>class Post(models.Model):
    title = models.CharField(max_length=140)
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
    content = RichTextField(default="")
    image = models.ImageField(upload_to="media/post")
    url = models.SlugField(unique=True, max_length=250, null=True, blank=True)
    likes = models.IntegerField(default=0)
    created_date = models.DateTimeField(auto_now_add=True)
    update_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.title}"

    def save(self, *args, **kwargs):  # new
        if not self.url:
            slug_str = f"{self.title}-{datetime.datetime.now()}"
            self.url = slugify(slug_str)
        return super().save(*args, **kwargs)
</code>```

答:
Here is an example how I've done this in one of my project.

Title : স্পেনের মাদ্রিদে বাংলা প্রেসক্লাবের দ্বিবার্ষিক সম্মেলন

You can use SlugField and allow unicode but you will get the slug: সপনর-মদরদ-বল-পরসকলবর-দববরষক-সমমলন

Let's solve this issue:

models.py

```<code>    slug = models.CharField(
        max_length=200,
        unique=True, blank=True, null=True, editable=True
    )

</code>```

```<code>    def save(self,*args, **kwargs):
        if not self.slug:
            self.slug = self.title.replace(" ", "-").replace(",", "")
        return super(BanglaModel, self).save(*args, **kwargs)

</code>```

Output slug: স্পেনের-মাদ্রিদে-বাংলা-প্রেসক্লাবের-দ্বিবার্ষিক-সম্মেলন

Body:
Django slug field does not work for any other language except English. I want to work with Bengali language
here is the code

class Post(models.Model):
    title = models.CharField(max_length=140)
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
    content = RichTextField(default="")
    image = models.ImageField(upload_to="media/post")
    url = models.SlugField(unique=True, max_length=250, null=True, blank=True)
    likes = models.IntegerField(default=0)
    created_date = models.DateTimeField(auto_now_add=True)
    update_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.title}"

    def save(self, *args, **kwargs):  # new
        if not self.url:
            slug_str = f"{self.title}-{datetime.datetime.now()}"
            self.url = slugify(slug_str)
        return super().save(*args, **kwargs)

Body:
Here is an example how I've done this in one of my project.

Title : স্পেনের মাদ্রিদে বাংলা প্রেসক্লাবের দ্বিবার্ষিক সম্মেলন

You can use SlugField and allow unicode but you will get the slug: সপনর-মদরদ-বল-পরসকলবর-দববরষক-সমমলন

Let's solve this issue:

models.py

    slug = models.CharField(
        max_length=200,
        unique=True, blank=True, null=True, editable=True
    )

    def save(self,*args, **kwargs):
        if not self.slug:
            self.slug = self.title.replace(" ", "-").replace(",", "")
        return super(BanglaModel, self).save(*args, **kwargs)

Output slug: স্পেনের-মাদ্রিদে-বাংলা-প্রেসক্লাবের-দ্বিবার্ষিক-সম্মেলন


问:
Writing and editing a PHP config file from a HTML form?
Hi just looking for some direction, I have a HTML form which has several fields and basically what I am wanting to do is save the data entered from the form to a PHP config file and also have the ability to edit the saved data by accessing and submitting the form again. I would prefer to do this without the use of a database.

So here's an example:

```<code><form method="post" name="config_form">
<div id="field">
<label>Keywords</label>
<br />
<input type="text" name="keyword">
</div>

<br />

<select name="color">
<option value="green">Green</option>
<option value="orange">Orange</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
</select>

</form>
</code>```

So the user enters 'computer' as the keyword and selects the color 'blue'. I want to then save this data into my config.php file as variables allowing my other website pages to access this data. Should this all be in an array as well?

```<code><?php
//config file
$keyword = "computer";
$color = "blue";

?>
</code>```

Also when I go back access the form again can I make it so the fields are prefilled with the data from the config.php file?

Any help would be much appreciated thank you!

答:
when you submit the form and you want to store the submitted form's data in one php file,ni must use the file action functions fopen the config.php,and write php code into it.
when you display the form,you can fopen the config.php,and use the function "eval" to get data.forgive my english.</p>

```<code>//when submit form
$string = '<?php $keyword="computer";$color="blue";?>';
$fp = fopen('config.php', 'w');
fwrite($fp, $string);
fclose($fp);
//when display form
include("config.php");
//so you can use $keyword and $color
</code>```

Body:
Hi just looking for some direction, I have a HTML form which has several fields and basically what I am wanting to do is save the data entered from the form to a PHP config file and also have the ability to edit the saved data by accessing and submitting the form again. I would prefer to do this without the use of a database.

So here's an example:

<form method="post" name="config_form">

Keywords

<input type="text" name="keyword">

<select name="color">
<option value="green">Green</option>
<option value="orange">Orange</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
</select>

</form>

So the user enters 'computer' as the keyword and selects the color 'blue'. I want to then save this data into my config.php file as variables allowing my other website pages to access this data. Should this all be in an array as well?

<?php
//config file
$keyword = "computer";
$color = "blue";

?>

Also when I go back access the form again can I make it so the fields are prefilled with the data from the config.php file?

Any help would be much appreciated thank you!

Body:
when you submit the form and you want to store the submitted form's data in one php file,ni must use the file action functions fopen the config.php,and write php code into it.
when you display the form,you can fopen the config.php,and use the function "eval" to get data.forgive my english.

//when submit form
$string = '<?php $keyword="computer";$color="blue";?>';
$fp = fopen('config.php', 'w');
fwrite($fp, $string);
fclose($fp);
//when display form
include("config.php");
//so you can use $keyword and $color


问:
No module 'pandas_gbq'
Hi I need a solution how to add this module.I get an error while running some code :
import pandas_gbq
ModuleNotFoundError: No module named 'pandas_gbq'

I try use: pip install pandas-gbq ( but it doesn't work)

答:
you can install with  git

```<code> pip install git+https://github.com/googleapis/python-bigquery-pandas.git
</code>```

or

```<code>pip install pandas-gbq -U
</code>```

Title: No module 'pandas_gbq'

Body:
you can install with  git

 pip install git+https://github.com/googleapis/python-bigquery-pandas.git

or

pip install pandas-gbq -U


问:
if statement error while running source ~/.bashrc error
I tried running source ~/.bashrc but it shows

```<code>~/.bashrc (line 5): Missing end to balance this if statement
if  [ -x /usr/bin/starship ]; then
^
from sourcing file ~/.bashrc
source: Error while reading file “/home/alokjha/.bashrc”
</code>```

How do i solve it?

I am currently on Garuda Linux (arch linux distro) and new in this linux universe, I want to install nvm, i followed steps as written in https://github.com/nvm-sh/nvm. I am not familiar with bash language so kindly help please ( Restart PC or Terminal is't helping)

Edit: Complete BashRc file

```<code># If not running interactively, don't do anything
[[ $- != *i* ]] && return

# Load starship prompt if starship is installed
if  [ -x /usr/bin/starship ]; then
    __main() {
        local major="${BASH_VERSINFO[0]}"
        local minor="${BASH_VERSINFO[1]}"

        if ((major > 4)) || { ((major == 4)) && ((minor >= 1)); }; then
            source <("/usr/bin/starship" init bash --print-full-init)
        else
            source /dev/stdin <<<"$("/usr/bin/starship" init bash --print-full-init)"
        fi
    }
    __main
    unset -f __main
fi

# Advanced command-not-found hook
source /usr/share/doc/find-the-command/ftc.bash

# Aliasessource ~/.bashrc error
alias dir='dir --color=auto'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias fixpacman="sudo rm /var/lib/pacman/db.lck"
alias grep='grep --color=auto'
alias grubup="sudo update-grub"
alias hw='hwinfo --short'
alias psmem10='ps auxf | sort -nr -k 4 | head -10'
alias psmem='ps auxf | sort -nr -k 4'
alias rmpkg="sudo pacman -Rdd"
alias tarnow='tar -acf '
alias untar='tar -zxvf '
alias upd='/usr/bin/update'
alias vdir='vdir --color=auto'
alias wget='wget -c '

# Help people new to Arch
alias apt-get='man pacman'
alias apt='man pacman'
alias helpme='cht.sh --shell'
alias please='sudo'
alias tb='nc termbin.com 9999'

# Cleanup orphaned packages
alias cleanup='sudo pacman -Rns `pacman -Qtdq`'

# Get the error messages from journalctl
alias jctl="journalctl -p 3 -xb"

# Recent installed packages
alias rip="expac --timefmt='%Y-%m-%d %T' '%l\t%n %v' | sort | tail -200 | nl"

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion
</code>```

答:
I ran into the same problem.

First I want to make it clear that I am a newbie in Arch and Garuda, so maybe some of my statements are not entirely correct.

Just as someone told you in the comments, you are using fish, look at the title of the Konsole window. Or edit the .bashrc file and set the if to fish syntax (change fi to end) and you'll see that the next error tells you clearly that you are using fish.

Quick "fix"

Switch to bash by running bash, then you can run source ~/.bashrc.

The problem with this is that if you exit bash (by executing exit) and return to fish, you lose what you get by executing source ~/.bashrc. I mean, you have to keep working in bash.

Solutions without switching to bash

Use nvm.fish.

Or convert the lines you need (the last 3 of your bashrc file) to fish syntax, and add them to the ~/.config/fish/config.fish file, then run source ~/.config/fish/config.fish.

Body:
I tried running source ~/.bashrc but it shows

~/.bashrc (line 5): Missing end to balance this if statement
if  [ -x /usr/bin/starship ]; then
^
from sourcing file ~/.bashrc
source: Error while reading file “/home/alokjha/.bashrc”

How do i solve it?

I am currently on Garuda Linux (arch linux distro) and new in this linux universe, I want to install nvm, i followed steps as written in https://github.com/nvm-sh/nvm. I am not familiar with bash language so kindly help please ( Restart PC or Terminal is't helping)

Edit: Complete BashRc file

# If not running interactively, don't do anything
[[ $- != *i* ]] && return

# Load starship prompt if starship is installed
if  [ -x /usr/bin/starship ]; then
    __main() {
        local major="${BASH_VERSINFO[0]}"
        local minor="${BASH_VERSINFO[1]}"

        if ((major > 4)) || { ((major == 4)) && ((minor >= 1)); }; then
            source <("/usr/bin/starship" init bash --print-full-init)
        else
            source /dev/stdin <<<"$("/usr/bin/starship" init bash --print-full-init)"
        fi
    }
    __main
    unset -f __main
fi

# Advanced command-not-found hook
source /usr/share/doc/find-the-command/ftc.bash

# Aliasessource ~/.bashrc error
alias dir='dir --color=auto'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias fixpacman="sudo rm /var/lib/pacman/db.lck"
alias grep='grep --color=auto'
alias grubup="sudo update-grub"
alias hw='hwinfo --short'
alias psmem10='ps auxf | sort -nr -k 4 | head -10'
alias psmem='ps auxf | sort -nr -k 4'
alias rmpkg="sudo pacman -Rdd"
alias tarnow='tar -acf '
alias untar='tar -zxvf '
alias upd='/usr/bin/update'
alias vdir='vdir --color=auto'
alias wget='wget -c '

# Help people new to Arch
alias apt-get='man pacman'
alias apt='man pacman'
alias helpme='cht.sh --shell'
alias please='sudo'
alias tb='nc termbin.com 9999'

# Cleanup orphaned packages
alias cleanup='sudo pacman -Rns `pacman -Qtdq`'

# Get the error messages from journalctl
alias jctl="journalctl -p 3 -xb"

# Recent installed packages
alias rip="expac --timefmt='%Y-%m-%d %T' '%l\t%n %v' | sort | tail -200 | nl"

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion


问:
How to add a new empty field or delimiter in a text file before to be read by a OPENROWSET?
I have inherited one ETL process and one of the new aims is try to get all the data from a text file and insert it into a SQL Server Instance. The problem is that the new format of the text file changed and my stored procedure does not work anymore so I trying to change the format of the txt file to fit to my SP.

First of all I was able to delete some data with this powershell script

```<code>$newdata=foreach($line in get-content "C:\users\user12\text_file1.txt")
{
   $line -replace 'text to delete1',' '

}
else
{
   $line

}

$newdata+=$newdata1

$newdata1=foreach($line in $newdata)
{
   $line -replace 'text to delete2',' '

}
else
{
   $line

}

$newdata1 | set-content "C:\users\user12\text_file1.txt" -force
$newdata1 | set-contect "C:\users\user12\text_file1.txt" -WorksheetName "datachanged" -AutoSize

</code>```

The challenge begins when I exported to excel

Here a pseudo-example about how looks the excel and what I expect

How actual looks

Time
Action
User
Size
Data
Folder
SO
Direction
Age

10:00 PM
Delete
Admin
3KB
PDF
/pdf/system_data.pdf
WO
10.0.0.0
14

10:30 PM
Created
Admin
5KB
XLSX
UB
10.1.0.0
12

10:45 PM
Sent
User
8KB
CSV
/pdf/system_data1.csv
WO
10.0.1.0
07

10:30 PM
Created
Admin
12KB
XLSX
UB
10.1.0.0
12

What I expect

Time
Action
User
Size
Data
Folder
SO
Direction
Age

10:00 PM
Delete
Admin
3KB
PDF
/pdf/system_data.pdf
WO
10.0.0.0
14

10:30 PM
Created
Admin
5KB
XLSX

UB
10.1.0.0
12

10:45 PM
Sent
User
8KB
CSV
/pdf/system_data1.csv
WO
10.0.1.0
07

10:30 PM
Created
Admin
12KB
XLSX

UB
10.1.0.0
12

I need to create an empty field or move to the right side all the values from "folder" to be able to read the file correctly with an OPENROWSET function and insert into a table.

答:
Assuming that your data is tab-delimited, and that you with to insert an extra tab in lines containing exactly 8 fields (7 tabs), the following may work.

```<code>$Header = "Time", "Action", "User", "Size", "Data", "Folder", "SO", "Direction", "Age"
$Content = `
"10:00 PM`tDelete`tAdmin`t3KB`tPDF`t/pdf/system_data.pdf`tWO`t10.0.0.0`t14",
"10:30 PM`tCreated`tAdmin`t5KB`tXLSX`tUB`t10.1.0.0`t12",
"10:45 PM`tSent`tUser`t8KB`tCSV`t/pdf/system_data1.csv`tWO`t10.0.1.0`t07",
"10:30 PM`tCreated`tAdmin`t12KB`tXLSX`tUB`t10.1.0.0`t12"

$Content | ConvertFrom-Csv -Delimiter "`t" -Header $Header | Format-Table

$match = '^([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)$'
$replace = '$1\t$2\t$3\t$4\t$5\t\t$6\t$7\t$8' -replace '\\t',"`t"  # Is there a better way to code this?
$Content = $Content | foreach { $_ -replace $match,$replace }

$Content | ConvertFrom-Csv -Delimiter "`t" -Header $Header | Format-Table
</code>```

The match string matches an alternating sequence of non-tab characters and tabs, capturing the text between the tabs. The replace string just rebuilds the line with the extra tab. (I couldn't figure out how to include tabs and replacement strings in the same powershell string literal, so I had to actually do a -replace on the replace string.)

Caution: The above may not properly handle quoted values that themselves contain delimiters.

Body:
I have inherited one ETL process and one of the new aims is try to get all the data from a text file and insert it into a SQL Server Instance. The problem is that the new format of the text file changed and my stored procedure does not work anymore so I trying to change the format of the txt file to fit to my SP.

First of all I was able to delete some data with this powershell script

$newdata=foreach($line in get-content "C:\users\user12\text_file1.txt")
{
   $line -replace 'text to delete1',' '

}
else
{
   $line

}

$newdata+=$newdata1

$newdata1=foreach($line in $newdata)
{
   $line -replace 'text to delete2',' '

}
else
{
   $line

}

$newdata1 | set-content "C:\users\user12\text_file1.txt" -force
$newdata1 | set-contect "C:\users\user12\text_file1.txt" -WorksheetName "datachanged" -AutoSize

The challenge begins when I exported to excel

Here a pseudo-example about how looks the excel and what I expect

How actual looks

Time
Action
User
Size
Data
Folder
SO
Direction
Age

10:00 PM
Delete
Admin
3KB
PDF
/pdf/system_data.pdf
WO
10.0.0.0
14

10:30 PM
Created
Admin
5KB
XLSX
UB
10.1.0.0
12

10:45 PM
Sent
User
8KB
CSV
/pdf/system_data1.csv
WO
10.0.1.0
07

10:30 PM
Created
Admin
12KB
XLSX
UB
10.1.0.0
12

What I expect

Time
Action
User
Size
Data
Folder
SO
Direction
Age

10:00 PM
Delete
Admin
3KB
PDF
/pdf/system_data.pdf
WO
10.0.0.0
14

10:30 PM
Created
Admin
5KB
XLSX

UB
10.1.0.0
12

10:45 PM
Sent
User
8KB
CSV
/pdf/system_data1.csv
WO
10.0.1.0
07

10:30 PM
Created
Admin
12KB
XLSX

UB
10.1.0.0
12

I need to create an empty field or move to the right side all the values from "folder" to be able to read the file correctly with an OPENROWSET function and insert into a table.

Body:
Assuming that your data is tab-delimited, and that you with to insert an extra tab in lines containing exactly 8 fields (7 tabs), the following may work.

$Header = "Time", "Action", "User", "Size", "Data", "Folder", "SO", "Direction", "Age"
$Content = `
"10:00 PM`tDelete`tAdmin`t3KB`tPDF`t/pdf/system_data.pdf`tWO`t10.0.0.0`t14",
"10:30 PM`tCreated`tAdmin`t5KB`tXLSX`tUB`t10.1.0.0`t12",
"10:45 PM`tSent`tUser`t8KB`tCSV`t/pdf/system_data1.csv`tWO`t10.0.1.0`t07",
"10:30 PM`tCreated`tAdmin`t12KB`tXLSX`tUB`t10.1.0.0`t12"

$Content | ConvertFrom-Csv -Delimiter "`t" -Header $Header | Format-Table

$match = '^([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)$'
$replace = '$1\t$2\t$3\t$4\t$5\t\t$6\t$7\t$8' -replace '\\t',"`t"  # Is there a better way to code this?
$Content = $Content | foreach { $_ -replace $match,$replace }

$Content | ConvertFrom-Csv -Delimiter "`t" -Header $Header | Format-Table

The match string matches an alternating sequence of non-tab characters and tabs, capturing the text between the tabs. The replace string just rebuilds the line with the extra tab. (I couldn't figure out how to include tabs and replacement strings in the same powershell string literal, so I had to actually do a -replace on the replace string.)

Caution: The above may not properly handle quoted values that themselves contain delimiters.


问:
How can I access the keys and values of the dictionary that is created by calling constructor __init__() from a function made inside a class?
I have created a class where I've passed an argument dictionary in the constructor. Now I need to make a function inside a class where I could access the information of that created dictionary and print users information. My attempt in doing so generates an error 'dict' object is not callabe.

class User:
    def __init__(self,first_name,last_name,**info):
        info['first_name']=first_name
        info['last_name']=last_name
        self.items=info

    def info_user(self):
            print(self.items)

    def users_information(self):
        print('Users Information:\n')
        for key, values in self.items():
            print(key,":",values)

user_0=User('Sarthak','Banset',address='Kathmandu',sex='Male',qualification='undergrad')
user_0.info_user()
user_0.users_information()
```

答:
To solve your problem just replace

```<code>for key, values in self.items():
</code>```

with

```<code>for key, values in self.items.items():
</code>```

However, I wouldn't do that if I were you. I would rename some variables first for avoiding confusion, and I wouldn't store the same objects received as arguments. I would make a copy of them. Here is a short refactor

```<code>class User:
    def __init__(self,first_name,last_name,**info):
        self.properties = dict()
        self.properties.update(info)
        self.properties['first_name'] = first_name
        self.properties['last_name'] = last_name

    def info_user(self):
        print(self.properties)

    def users_information(self):
        print('Users Information:\n')
        for key, values in self.properties.items():
            print(key,":",values)

user_0=User('Sarthak','Banset',address='Kathmandu',sex='Male',qualification='undergrad')
user_0.info_user()
user_0.users_information()
</code>```

Body:
To solve your problem just replace

for key, values in self.items():

with

for key, values in self.items.items():

However, I wouldn't do that if I were you. I would rename some variables first for avoiding confusion, and I wouldn't store the same objects received as arguments. I would make a copy of them. Here is a short refactor

class User:
    def __init__(self,first_name,last_name,**info):
        self.properties = dict()
        self.properties.update(info)
        self.properties['first_name'] = first_name
        self.properties['last_name'] = last_name

    def info_user(self):
        print(self.properties)

    def users_information(self):
        print('Users Information:\n')
        for key, values in self.properties.items():
            print(key,":",values)

user_0=User('Sarthak','Banset',address='Kathmandu',sex='Male',qualification='undergrad')
user_0.info_user()
user_0.users_information()