问:
Getting an error when accessing the tabbar controller swift
I am using a UITabBarController in my application. I want to access the variables I defined in my tabbar from a child view of one of the tabs :

```<code>let tabBar = tabBarController as! baseTabBarController
</code>```

I have already done it for an another tab and it works fine. But this time, I am getting an error :

```<code>Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/ms/Desktop/invoice/invoice/PreviewViewController.swift, line 36
2020-05-30 18:46:26.511904+0200 Invo[9455:2542848] Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/ms/Desktop/invoice/invoice/PreviewViewController.swift, line 36
</code>```

Please help ! Thanks.

Here is the view controller class :

```<code>import UIKit
import WebKit

class PreviewViewController: UIViewController {

    @IBOutlet var webPreview: UIWebView!

    var invoiceComposer: InvoiceComposer!
    var HTMLContent: String!

    var invoiceNumber = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        print(invoiceNumber)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        createInvoiceAsHTML()
    }

    func createInvoiceAsHTML() {
        invoiceComposer = InvoiceComposer()

        if let tabBar = tabBarController as? baseTabBarController {
            if let invoiceHTML = invoiceComposer.renderInvoice(invoiceNumber: String(invoiceNumber), invoiceDate: "", recipientInfo: tabBar.customerData[invoiceNumber][0].input, items: tabBar.itemsData[invoiceNumber], totalAmount: tabBar.totalData[invoiceNumber].total) {

                   webPreview.loadHTMLString(invoiceHTML, baseURL: NSURL(string: invoiceComposer.pathToInvoiceHTMLTemplate!)! as URL)
                   HTMLContent = invoiceHTML
            }
            print("works")
        }
        else {
            print("tabBarController is not of type baseTabBarController or either nil ")
        }

    }

}
</code>```

Here is a view of the storyboard :

Storyboard

Here is tabbar controller's implementation :

import UIKit

```<code>class baseTabBarController: UITabBarController {

     var customerData: [[customerInformation]] = []
     var itemsData: [[Item]] = []
     var totalData: [TotalInformation] = []

     override func viewDidLoad() {
         super.viewDidLoad()
}
</code>```

答:
tabBarController is not of type baseTabBarController or either nil
You can check that </p>

```<code>if let tabBar = tabBarController as? baseTabBarController {
print("tabBarController exists and of type baseTabBarController")
} else {
print("tabBarController is not of type baseTabBarController or either nil ")
}
</code>```

Body:
I am using a UITabBarController in my application. I want to access the variables I defined in my tabbar from a child view of one of the tabs :

let tabBar = tabBarController as! baseTabBarController

I have already done it for an another tab and it works fine. But this time, I am getting an error :

Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/ms/Desktop/invoice/invoice/PreviewViewController.swift, line 36
2020-05-30 18:46:26.511904+0200 Invo[9455:2542848] Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/ms/Desktop/invoice/invoice/PreviewViewController.swift, line 36

Please help ! Thanks.

Here is the view controller class :

import UIKit
import WebKit

class PreviewViewController: UIViewController {

    @IBOutlet var webPreview: UIWebView!

    var invoiceComposer: InvoiceComposer!
    var HTMLContent: String!

    var invoiceNumber = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        print(invoiceNumber)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        createInvoiceAsHTML()
    }

    func createInvoiceAsHTML() {
        invoiceComposer = InvoiceComposer()

        if let tabBar = tabBarController as? baseTabBarController {
            if let invoiceHTML = invoiceComposer.renderInvoice(invoiceNumber: String(invoiceNumber), invoiceDate: "", recipientInfo: tabBar.customerData[invoiceNumber][0].input, items: tabBar.itemsData[invoiceNumber], totalAmount: tabBar.totalData[invoiceNumber].total) {

                   webPreview.loadHTMLString(invoiceHTML, baseURL: NSURL(string: invoiceComposer.pathToInvoiceHTMLTemplate!)! as URL)
                   HTMLContent = invoiceHTML
            }
            print("works")
        }
        else {
            print("tabBarController is not of type baseTabBarController or either nil ")
        }

    }

}

Here is a view of the storyboard :

Storyboard

Here is tabbar controller's implementation :

import UIKit

class baseTabBarController: UITabBarController {

     var customerData: [[customerInformation]] = []
     var itemsData: [[Item]] = []
     var totalData: [TotalInformation] = []

     override func viewDidLoad() {
         super.viewDidLoad()
}

Body:
tabBarController is not of type baseTabBarController or either nil
You can check that

if let tabBar = tabBarController as? baseTabBarController {
print("tabBarController exists and of type baseTabBarController")
} else {
print("tabBarController is not of type baseTabBarController or either nil ")
}


来源: stackexchange

问:
Get multiple columns with null values
I want to get all the columns with NULL values. That's what I'm using:

```<code>SELECT Customers_Name, Customers_LastName
FROM customers
WHERE (SELECT * FROM customers) IS NULL;
</code>```

I get this error:

Operand should contains 1 columns(s)

Whats the right way to do it ?

That's the question I'm asked to do :

Any Blanks. For each row retrieved, show all customers that have a blank in at least one of its columns. Sort from Z to A on last name then Z to A on first name.

Thank you to help, I'm new to coding.

答:
You need to list each column explicitly:</p>

```<code>SELECT Customers_Name, Customers_LastName
FROM customers
WHERE Customers_Name IS NULL OR Customers_LastName IS NULL;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get multiple columns with null values

Body:
I want to get all the columns with NULL values. That's what I'm using:

SELECT Customers_Name, Customers_LastName
FROM customers
WHERE (SELECT * FROM customers) IS NULL;

I get this error:

Operand should contains 1 columns(s)

Whats the right way to do it ?

That's the question I'm asked to do :

Any Blanks. For each row retrieved, show all customers that have a blank in at least one of its columns. Sort from Z to A on last name then Z to A on first name.

Thank you to help, I'm new to coding.

Body:
You need to list each column explicitly:

SELECT Customers_Name, Customers_LastName
FROM customers
WHERE Customers_Name IS NULL OR Customers_LastName IS NULL;


问:
Can't replace string content in pandas DataFrame
I have values from submission that I appended into a data frame that look like the following:

```<code>df['SalePrice'] = submission

0       [381659.34]
1       [639894.75]
2       [189159.39]
3       [203588.45]
4       [609621.25]
</code>```

I tried to remove the brackets from each side of the float with this code:

```<code>df['SalePrice'] = df.SalePrice.replace("[","").replace("]","")
print(df['SalePrice'])
</code>```

I am not able to remove the brackets.  Is there any way to clean-up this float in Python?

答:
Try str and strip:</p>

```<code>df.SalePrice.str.strip('[]')
</code>```

Body:
I have values from submission that I appended into a data frame that look like the following:

df['SalePrice'] = submission

0       [381659.34]
1       [639894.75]
2       [189159.39]
3       [203588.45]
4       [609621.25]

I tried to remove the brackets from each side of the float with this code:

df['SalePrice'] = df.SalePrice.replace("[","").replace("]","")
print(df['SalePrice'])

I am not able to remove the brackets.  Is there any way to clean-up this float in Python?

Body:
Try str and strip:

df.SalePrice.str.strip('[]')


问:
How to add element of a list to list of dictionary in python
Am trying to add element of a list to a list dictionary, I have tried all my possible best but could not get it done.

list of dict

```<code>fortunne_500=[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion'},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion'},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion'}]
</code>```

list

```<code>rev_per_emp = [217391.30434782608,376142.84374767606,911953.2812190612]
</code>```

Desired output

```<code>[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion',
  'rev per emp': 217391.30434782608},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion',
  'rev per emp': 376142.84374767606},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion',
  'rev per emp': 911953.2812190612}]
</code>```

I will appreciate any help in getting this done.
Thank you

答:
using a enumerator like this</p>

```<code>    for i, item in enumerate(fortunne_500):
        item["rev per emp"] = rev_per_emp[i]
</code>```

Body:
Am trying to add element of a list to a list dictionary, I have tried all my possible best but could not get it done.

list of dict

fortunne_500=[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion'},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion'},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion'}]

list

rev_per_emp = [217391.30434782608,376142.84374767606,911953.2812190612]

Desired output

[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion',
  'rev per emp': 217391.30434782608},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion',
  'rev per emp': 376142.84374767606},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion',
  'rev per emp': 911953.2812190612}]

I will appreciate any help in getting this done.
Thank you

Body:
using a enumerator like this

    for i, item in enumerate(fortunne_500):
        item["rev per emp"] = rev_per_emp[i]


问:
Are swift classes inside struct passed by copy during assignment?
If I have a struct in swift with inside a class attribute and I copy the struct object, is the class attribute copied or passed by reference?</p>

答:
I tested the above experiment in swift 5:
Let's see the result:

```<code>class A {
    var id: Int
    init(id: Int) {
        self.id = id
    }
}

struct B {
    var grade: Int
    var a: A
}
</code>```

Experiment based on the result:

```<code>var a = A(id: 1)
var a_copy = a

var b1 = B(grade: 2, a: a)
var copy_b1 = b1

print(b1.a.id)
b1.a.id = 5
print(copy_b1.a.id)

print(b1.grade)
b1.grade = 3
print(copy_b1.grade)
</code>```

Output:

```<code>1
5 // call by reference, same result
2
2 // call by value, no change in result
</code>```

Conclusion:

struct does copy when we create another object of it. It copies its struct property (call by value) but refer the same instance of class property (call by reference)

Do experiment via address:

Do an Experiment on Class:

```<code>var a = A(id: 1)
var a_copy = a

withUnsafePointer(to: &a) { (address) in
    print("address of a (class) = \(address)")
}
withUnsafePointer(to: &a_copy) { (address) in
    print("address of a_copy (class) = \(address)")
}
withUnsafePointer(to: &a.id) { (address) in
    print("address of a.id (struct) = \(address)")
}
withUnsafePointer(to: &a_copy.id) { (address) in
    print("address of a_copy.id (struct) = \(address)")
}
</code>```

Output

```<code>address of a (class) = 0x0000000114747f80
address of a_copy (class) = 0x0000000114747f88
address of a.id (struct) = 0x000060000285a390
address of a_copy.id (struct) = 0x000060000285a390
</code>```

Observation 1:

Both instances of the class are referring to same location of its property.

Let's do the Experiment on struct:

```<code>print("\n\n\n")
withUnsafePointer(to: &b1) { (address) in
    print("address of b1 (struct) = \(address)")
}
withUnsafePointer(to: &b1.grade) { (address) in
    print("address of b1.grade (struct) = \(address)")
}
withUnsafePointer(to: &b1.a) { (address) in
    print("address of b1.a (class) = \(address)")
}
withUnsafePointer(to: &b1.a.id) { (address) in
    print("address of b1.a.id (class) = \(address)")
}
</code>```

Output:

```<code>address of b1 (struct) = 0x0000000109382770
address of b1.grade (struct) = 0x0000000109382770
address of b1.a (class) = 0x0000000109382778
address of b1.a.id (class) = 0x0000600001e5cfd0
</code>```

```<code>print("\n\n\n")
withUnsafePointer(to: &copy_b1) { (address) in
    print("address of copy_b1 (struct) = \(address)")
}
withUnsafePointer(to: &copy_b1.grade) { (address) in
    print("address of copy_b1.grade (struct) = \(address)")
}
withUnsafePointer(to: &copy_b1.a) { (address) in
    print("address of copy_b1.a (class) = \(address)")
}
withUnsafePointer(to: &copy_b1.a.id) { (address) in
    print("address of copy_b1.a.id (class) = \(address)")
}
</code>```

Output:

```<code>address of copy_b1 (struct) = 0x0000000109382780
address of copy_b1.grade (struct) = 0x0000000109382780
address of copy_b1.a (class) = 0x0000000109382788
address of copy_b1.a.id (class) = 0x0000600001e5cfd0
</code>```

conclusion: both &b1.a.id and &copy_b1.a.id are referring the same address.

ContentLicense: CC BY-SA 3.0

Body:
I tested the above experiment in swift 5:
Let's see the result:

class A {
    var id: Int
    init(id: Int) {
        self.id = id
    }
}

struct B {
    var grade: Int
    var a: A
}

Experiment based on the result:

var a = A(id: 1)
var a_copy = a

var b1 = B(grade: 2, a: a)
var copy_b1 = b1

print(b1.a.id)
b1.a.id = 5
print(copy_b1.a.id)

print(b1.grade)
b1.grade = 3
print(copy_b1.grade)

Output:

1
5 // call by reference, same result
2
2 // call by value, no change in result

Conclusion:

struct does copy when we create another object of it. It copies its struct property (call by value) but refer the same instance of class property (call by reference)

Do experiment via address:

Do an Experiment on Class:

var a = A(id: 1)
var a_copy = a

withUnsafePointer(to: &a) { (address) in
    print("address of a (class) = \(address)")
}
withUnsafePointer(to: &a_copy) { (address) in
    print("address of a_copy (class) = \(address)")
}
withUnsafePointer(to: &a.id) { (address) in
    print("address of a.id (struct) = \(address)")
}
withUnsafePointer(to: &a_copy.id) { (address) in
    print("address of a_copy.id (struct) = \(address)")
}

Output

address of a (class) = 0x0000000114747f80
address of a_copy (class) = 0x0000000114747f88
address of a.id (struct) = 0x000060000285a390
address of a_copy.id (struct) = 0x000060000285a390

Observation 1:

Both instances of the class are referring to same location of its property.

Let's do the Experiment on struct:

print("\n\n\n")
withUnsafePointer(to: &b1) { (address) in
    print("address of b1 (struct) = \(address)")
}
withUnsafePointer(to: &b1.grade) { (address) in
    print("address of b1.grade (struct) = \(address)")
}
withUnsafePointer(to: &b1.a) { (address) in
    print("address of b1.a (class) = \(address)")
}
withUnsafePointer(to: &b1.a.id) { (address) in
    print("address of b1.a.id (class) = \(address)")
}

Output:

address of b1 (struct) = 0x0000000109382770
address of b1.grade (struct) = 0x0000000109382770
address of b1.a (class) = 0x0000000109382778
address of b1.a.id (class) = 0x0000600001e5cfd0

print("\n\n\n")
withUnsafePointer(to: &copy_b1) { (address) in
    print("address of copy_b1 (struct) = \(address)")
}
withUnsafePointer(to: &copy_b1.grade) { (address) in
    print("address of copy_b1.grade (struct) = \(address)")
}
withUnsafePointer(to: &copy_b1.a) { (address) in
    print("address of copy_b1.a (class) = \(address)")
}
withUnsafePointer(to: &copy_b1.a.id) { (address) in
    print("address of copy_b1.a.id (class) = \(address)")
}

Output:

address of copy_b1 (struct) = 0x0000000109382780
address of copy_b1.grade (struct) = 0x0000000109382780
address of copy_b1.a (class) = 0x0000000109382788
address of copy_b1.a.id (class) = 0x0000600001e5cfd0

conclusion: both &b1.a.id and &copy_b1.a.id are referring the same address.


问:
gameobject is instantiated in the wrong place in game view Unity
difference between game view and scene view

as you can see from the picture it seems like my game object is being instantiated in the wrong place in my game view while in my scene view it instantiates in the right position anyone can help with this problem ?

Edit: i forgot to say that this only happens to my triple shot
my regular shot works fine

my code for instantiation:

```<code> void FireLaser()
    {
         _canFire = Time.time + _fireRate;

        if (_tripleShotEnabled == true)
        {

            Instantiate(_tripleShotPrefab, transform.position , Quaternion.identity);
        }
        else
        {
            Instantiate(_laserPrefab, transform.position + new Vector3(0,1.05F,0), Quaternion.identity);
        }
    }
</code>```

答: open the prefab where the bullets are located and and set their position to 0 if you instantiate them</p>

Body:
difference between game view and scene view

as you can see from the picture it seems like my game object is being instantiated in the wrong place in my game view while in my scene view it instantiates in the right position anyone can help with this problem ?

Edit: i forgot to say that this only happens to my triple shot
my regular shot works fine

my code for instantiation:

 void FireLaser()
    {
         _canFire = Time.time + _fireRate;

        if (_tripleShotEnabled == true)
        {

            Instantiate(_tripleShotPrefab, transform.position , Quaternion.identity);
        }
        else
        {
            Instantiate(_laserPrefab, transform.position + new Vector3(0,1.05F,0), Quaternion.identity);
        }
    }


问:
Confusion about `const` in compound assignment
The canonical implementation of operator+= passes the RHS as a const reference:

```<code>X& operator+=(const X& rhs)
</code>```

However, in

```<code>x += x;
</code>```

the RHS is modified. Does this invoke the UB?

答:
The const means that the reference is a reference to const and a reference to const can bind to a non-const object. Binding a reference to const to a non-const object doesn't make the object itself const. It just means that you can't modify the object through the reference to const, and if the object isn't const it can be modified in another way.

In this case, the reference is a reference to const, but the object referenced is not const, so modifying the object is fine.

Body:
The canonical implementation of operator+= passes the RHS as a const reference:

X& operator+=(const X& rhs)

However, in

x += x;

the RHS is modified. Does this invoke the UB?


问:
PHP string help
Hey, so I am trying to learn some string functions in PHP and came across a senario I cannot figure out. I want to take a string like such: /var/www/html and remove everything after the last forward slash (including the forward slash) so I end up with /var/www

What would be the best way to go about this? Many thanks.

答: Try using dirname. It may handle special cases for you that you may not have anticipated if you went with a string manipulation route.

Title: PHP string help


问:
Can you help me solve this node js error? "Module_Not_Found"
Image of code, execution and error

When I try to run node fordongu.js in the terminal, I get this error. Would you suggest an idea of how to solve this error?

答: The error states that there's no file fordungo.js in the directory you're trying to execute from. So it seems you're in the wrong folder and need to cd into javascript tekrar\for döngüleri and execute the script from there.


问:
incompatible types in assignment of 'char[10]' to 'char [50]'
I am always taking these "incompatible types in the assignment of 'const char [5]' to 'char [50]'" or like that problem.

```<code>#include <stdio.h>
#include <stdlib.h>
struct Lessons{
    char name[50];
    float note;
    int credit;
}lesson1,lesson2;

int main(){
lesson1.name = "Math";

printf("%s",lesson1.name);

return 0;
}
</code>```

The problem in lesson1.name = "Math";.But i can't solving.

答:
You cannot assign a string to a buffer using the = operator.  You’ll need to use the strcpy library function:

```<code>#include <string.h>
...
strcpy( lesson1.name, “Math” );
</code>```

Body:
I am always taking these "incompatible types in the assignment of 'const char [5]' to 'char [50]'" or like that problem.

#include <stdio.h>
#include <stdlib.h>
struct Lessons{
    char name[50];
    float note;
    int credit;
}lesson1,lesson2;

int main(){
lesson1.name = "Math";

printf("%s",lesson1.name);

return 0;
}

The problem in lesson1.name = "Math";.But i can't solving.

Body:
You cannot assign a string to a buffer using the = operator.  You’ll need to use the strcpy library function:

#include <string.h>
...
strcpy( lesson1.name, “Math” );


问:
CodingBat sum67: why is this solution wrong?
I'm working on the following codingbat problem:

Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.

```<code>sum67([1, 2, 2]) → 5
sum67([1, 2, 2, 6, 99, 99, 7]) → 5
sum67([1, 1, 6, 7, 2]) → 4
</code>```

My solution is:

```<code>def sum67(nums):
    sum = 0
    throwaway = 0
    for i in range(len(nums)):
        if throwaway == 0:
            if nums[i] == 6:
                throwaway = 1
        elif throwaway == 1 and i > 0 and nums[i-1] == 7:
            throwaway = 0
        if throwaway == 0:
            sum += nums[i]
    return sum
</code>```

I totally know this is not the best solution, but I'm just curious to know why this is wrong.  Could you please explain me why this is wrong and in which particular case it gives a wrong result?

答:
```<code>def sum67(nums):
    c=0
    state=True
    for i in nums:
        if state:
            if i==6:
                state=False
            else:
                c+=i

        else:
            if i==7:
                state=True
    return c
</code>```

Body:
I'm working on the following codingbat problem:

Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.

sum67([1, 2, 2]) → 5
sum67([1, 2, 2, 6, 99, 99, 7]) → 5
sum67([1, 1, 6, 7, 2]) → 4

My solution is:

def sum67(nums):
    sum = 0
    throwaway = 0
    for i in range(len(nums)):
        if throwaway == 0:
            if nums[i] == 6:
                throwaway = 1
        elif throwaway == 1 and i > 0 and nums[i-1] == 7:
            throwaway = 0
        if throwaway == 0:
            sum += nums[i]
    return sum

I totally know this is not the best solution, but I'm just curious to know why this is wrong.  Could you please explain me why this is wrong and in which particular case it gives a wrong result?


问:
How to 'fix' selected item in tkinter.Listbox?
Here's is an extract from my code:

```<code>import tkinter as tk

def evaluate(event):
    print(list_box.curselection())

root = tk.Tk()
var = tk.StringVar()
var.set(0)

entry = tk.Entry(root, textvariable = var)
entry.place(x = 150, y = 0, width = 20)
entry.bind("<Return>", evaluate)

list_box = tk.Listbox(root, selectmode = 'single')
list_box.place(x = 0, y = 0)
lst = [1, 2, 3]

for elem in lst:
    list_box.insert('end', elem)

list_box.selection_set(first = 0)
list_box.bind("<<ListboxSelect>>", evaluate)

root.mainloop()
</code>```

The problem is that I want to 'fix' somehow the last selected value in the tkinter.Listbox. I mean, if in the window we type something to the entry, then in some cases (probably, it depends on how you click the entry box) the value chosen in the list will be lost. Is it possible to save, for example, the last selected value?

I'm new to Python and, in particular, to tkinter package, so any help would be appreciated.

答:
the problem is as soon as you select something else like the input of the entry, your listbox lose the shown selection. I removed the default binding for double click, but if you still want to use it to write input, I can't remove the single click (B1-Motion dosent works either). At least I dont know how. I recommand to use the entry just as display or vise versa.</p>

```<code>import tkinter as tk

def evaluate(event):
  print(list_box.curselection())

root = tk.Tk()
var = tk.StringVar()
var.set(0)

entry = tk.Entry(root, textvariable = var)
entry.place(x = 150, y = 0, width = 20)
entry.bind("<Return>", evaluate)
entry.bind('<Double-Button-1>', lambda e: "break")

list_box = tk.Listbox(root, selectmode = 'single')
list_box.place(x = 0, y = 0)
lst = [1, 2, 3]

for elem in lst:
    list_box.insert('end', elem)

list_box.selection_set(first = 0)
list_box.bind("<<ListboxSelect>>", evaluate)

root.mainloop()
</code>```

Body:
Here's is an extract from my code:

import tkinter as tk

def evaluate(event):
    print(list_box.curselection())

root = tk.Tk()
var = tk.StringVar()
var.set(0)

entry = tk.Entry(root, textvariable = var)
entry.place(x = 150, y = 0, width = 20)
entry.bind("<Return>", evaluate)

list_box = tk.Listbox(root, selectmode = 'single')
list_box.place(x = 0, y = 0)
lst = [1, 2, 3]

for elem in lst:
    list_box.insert('end', elem)

list_box.selection_set(first = 0)
list_box.bind("<<ListboxSelect>>", evaluate)

root.mainloop()

The problem is that I want to 'fix' somehow the last selected value in the tkinter.Listbox. I mean, if in the window we type something to the entry, then in some cases (probably, it depends on how you click the entry box) the value chosen in the list will be lost. Is it possible to save, for example, the last selected value?

I'm new to Python and, in particular, to tkinter package, so any help would be appreciated.

Body:
the problem is as soon as you select something else like the input of the entry, your listbox lose the shown selection. I removed the default binding for double click, but if you still want to use it to write input, I can't remove the single click (B1-Motion dosent works either). At least I dont know how. I recommand to use the entry just as display or vise versa.

import tkinter as tk

def evaluate(event):
  print(list_box.curselection())

root = tk.Tk()
var = tk.StringVar()
var.set(0)

entry = tk.Entry(root, textvariable = var)
entry.place(x = 150, y = 0, width = 20)
entry.bind("<Return>", evaluate)
entry.bind('<Double-Button-1>', lambda e: "break")

list_box = tk.Listbox(root, selectmode = 'single')
list_box.place(x = 0, y = 0)
lst = [1, 2, 3]

for elem in lst:
    list_box.insert('end', elem)

list_box.selection_set(first = 0)
list_box.bind("<<ListboxSelect>>", evaluate)

root.mainloop()


问:
Do objects have a copy of their class methods?
I wanted to know whether an object has a copy of all its class methods. So I created a class person, defined a method getName and created an object Harry. I used dir function to check whether both the class and the object have getName method stored inside them and both of them returned true. I then printed out the getName method of both the class and the object and they returned different addresses, but I noticed that harry.getName method is bounded to person.getName. So does that mean that harry.getName is not a copy of its class method rather just a reference to its class method. To check this used delattr method to delete the getName attribute of the person class and again used dir to check it. And as expected it deleted it from both the class person and object Harry.

So please review my code and tell whether my thoughts are correct.

Note:

The dir() function returns all properties and methods of the specified object, without the values.

The delattr() method is used to delete the named attribute from the object, with the prior permission of the object.

答:
Without going into too much detail, what you are observing is the on-the-fly creation of a function that acts like person.getName but the first argument (self) is already bound to an instance.

So no, objects do not have a copy of the methods in their class. Every time you access Harry.getName a new callable object (the "method") is built from scratch. It behaves like person.getName with self=Harry.

On the other hand, no new callable is constructed when you access getName on the class level.


答:
This would make it:</p>

```<code>for ix, val in enumerate(rev_per_emp):
    fortunne_500[ix].update({"rev per emp": val})

print(fortunne_500)
</code>```

Title: How to add element of a list to list of dictionary in python

Body:
This would make it:

for ix, val in enumerate(rev_per_emp):
    fortunne_500[ix].update({"rev per emp": val})

print(fortunne_500)


问:
Reading a file in a table format and print it
So, what I'm trying to do is, at first create a file in a table format then read that file and put that file in 4 different dynamic arrays using struct and print them in order

So, here is the struct I'm using: I used capacity = 5 to change the size of dynamic array later but still don't know how to change it

```<code>struct score{
    char *str1;
    char *str2;
    int *num1;
    int *num2;
};

int main(){
    int capacity = 5;
    struct score table;
    table.str1=(char *)malloc(sizeof(int)*capacity);
    table.str2=(char *)malloc(sizeof(int)*capacity);
    table.num1=(int *)malloc(sizeof(int)*capacity);
    table.num2=(int *)malloc(sizeof(int)*capacity);
</code>```

After I created a File to write:

```<code>    inFile = fopen("Subject.txt", "w");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }

    char names[] = {"Joe Math 52 85\nBilly Phy 65 70\nSophia Chem 86 71"};

    fprintf(inFile,"%s",names);
    fclose(inFile);
</code>```

At the end reading a File and putting them in arrays:

```<code>    inFile = fopen("Subject.txt", "r");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }
    fscanf(inFile, "%s %s %d %d",table.str1, table.str2, table.num1, table.num2);
    fclose(inFile);

    for(i=0;i<6;i++){
        printf("%s %s %d %d\n",table.str1, table.str2, table.num1, table.num2);
    }
</code>```

So, I need this code to print like this, and I couldn't do it:

```<code>Name   Subj.  Test1  Test2
------------------------
Joe    Math   52     85
Billy  Phy    65     70
Sophia Chem   86     71
</code>```

Here is my full Code just in case:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct score{
    char *str1;
    char *str2;
    int *num1;
    int *num2;
};

int main(){
    FILE *inFile;
    int num, capacity = 5, i;
    struct score table;
    table.str1=(char *)malloc(sizeof(int)*capacity);
    table.str2=(char *)malloc(sizeof(int)*capacity);
    table.num1=(int *)malloc(sizeof(int)*capacity);
    table.num2=(int *)malloc(sizeof(int)*capacity);
    inFile = fopen("Subject.txt", "w");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }

    char names[] = {"Joe Math 52 85\nBilly Phy 65 70\nSophia Chem 86 71"};

    fprintf(inFile,"%s",names);
    fclose(inFile);

    inFile = fopen("Subject.txt", "r");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }
    fscanf(inFile, "%s %s %d %d",table.str1, table.str2, table.num1, table.num2);
    fclose(inFile);

    for(i=0;i<6;i++){
        printf("%s %s %d %d\n",table.str1, table.str2, table.num1, table.num2);
    }
}
</code>```

答:
I think you want an array of structs with one array element for each student. Now you are using one struct to hold arrays of the individual pieces of information.

The array would look like:

```<code>#define MAX_NAME 30
#define MAX_STUDENTS 10

struct score{
    char str1[MAX_NAME];
    char str2[MAX_NAME];
    int num1;
    int num2;
};

struct score table[MAX_STUDENTS];
</code>```

With this definition you don't need to malloc memory (it is simpler, but not flexible).

You read the information into the array as:

```<code>int i=0;
while (fscanf(inFile, "%30s %30s %d %d",table[i].str1, table[i].str2,
  &table[i].num1, &table[i].num2) == 4) {
    i++;
}
</code>```

Body:
So, what I'm trying to do is, at first create a file in a table format then read that file and put that file in 4 different dynamic arrays using struct and print them in order

So, here is the struct I'm using: I used capacity = 5 to change the size of dynamic array later but still don't know how to change it

struct score{
    char *str1;
    char *str2;
    int *num1;
    int *num2;
};

int main(){
    int capacity = 5;
    struct score table;
    table.str1=(char *)malloc(sizeof(int)*capacity);
    table.str2=(char *)malloc(sizeof(int)*capacity);
    table.num1=(int *)malloc(sizeof(int)*capacity);
    table.num2=(int *)malloc(sizeof(int)*capacity);

After I created a File to write:

    inFile = fopen("Subject.txt", "w");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }

    char names[] = {"Joe Math 52 85\nBilly Phy 65 70\nSophia Chem 86 71"};

    fprintf(inFile,"%s",names);
    fclose(inFile);

At the end reading a File and putting them in arrays:

    inFile = fopen("Subject.txt", "r");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }
    fscanf(inFile, "%s %s %d %d",table.str1, table.str2, table.num1, table.num2);
    fclose(inFile);

    for(i=0;i<6;i++){
        printf("%s %s %d %d\n",table.str1, table.str2, table.num1, table.num2);
    }

So, I need this code to print like this, and I couldn't do it:

Name   Subj.  Test1  Test2
------------------------
Joe    Math   52     85
Billy  Phy    65     70
Sophia Chem   86     71

Here is my full Code just in case:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct score{
    char *str1;
    char *str2;
    int *num1;
    int *num2;
};

int main(){
    FILE *inFile;
    int num, capacity = 5, i;
    struct score table;
    table.str1=(char *)malloc(sizeof(int)*capacity);
    table.str2=(char *)malloc(sizeof(int)*capacity);
    table.num1=(int *)malloc(sizeof(int)*capacity);
    table.num2=(int *)malloc(sizeof(int)*capacity);
    inFile = fopen("Subject.txt", "w");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }

    char names[] = {"Joe Math 52 85\nBilly Phy 65 70\nSophia Chem 86 71"};

    fprintf(inFile,"%s",names);
    fclose(inFile);

    inFile = fopen("Subject.txt", "r");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }
    fscanf(inFile, "%s %s %d %d",table.str1, table.str2, table.num1, table.num2);
    fclose(inFile);

    for(i=0;i<6;i++){
        printf("%s %s %d %d\n",table.str1, table.str2, table.num1, table.num2);
    }
}

Body:
I think you want an array of structs with one array element for each student. Now you are using one struct to hold arrays of the individual pieces of information.

The array would look like:

#define MAX_NAME 30
#define MAX_STUDENTS 10

struct score{
    char str1[MAX_NAME];
    char str2[MAX_NAME];
    int num1;
    int num2;
};

struct score table[MAX_STUDENTS];

With this definition you don't need to malloc memory (it is simpler, but not flexible).

You read the information into the array as:

int i=0;
while (fscanf(inFile, "%30s %30s %d %d",table[i].str1, table[i].str2,
  &table[i].num1, &table[i].num2) == 4) {
    i++;
}


问:
Validate Regex: min/max characters, one hypen and start/finish conditions
I am trying to create a validation function for usernames.  It must be:

Min six characters / Max 16 characters

Only letters, numbers and, at the most, one hyphen

It must start with a letter and no end with a hyphen

I came up with this regular expression:

```<code>^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$
</code>```

Which does everything but the maximum number of characters.  What am I missing?

You may wonder why I am using 4 to 14: it is because the first and last characters are already defined by the other conditions, so I need the rest to be at least 4 (to make it to six) and at most 14 characters (to make it to 16).

This is a simple validation function in Python:

```<code># Username validation
import re

def validate(username):
    regex = re.compile('^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$', re.I)
    match = regex.match(str(username))
    return bool(match)

print(validate("PeterParker")) #Valid username
print(validate("Peter-Parker")) #Valid username
print(validate("Peter-P-arker")) #Invalid username
print(validate("Peter")) #Invalid username
print(validate("PeterParker-")) #Invalid username
print(validate("-PeterParker")) #Invalid username
print(validate("1PeterParker")) #Invalid username
print(validate("Peter Parker")) #Invalid username
print(validate("PeterParkerSpiderMan")) #Invalid username
</code>```

Thanks very much for any suggestion.

Body:
I am trying to create a validation function for usernames.  It must be:

Min six characters / Max 16 characters

Only letters, numbers and, at the most, one hyphen

It must start with a letter and no end with a hyphen

I came up with this regular expression:

^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$

Which does everything but the maximum number of characters.  What am I missing?

You may wonder why I am using 4 to 14: it is because the first and last characters are already defined by the other conditions, so I need the rest to be at least 4 (to make it to six) and at most 14 characters (to make it to 16).

This is a simple validation function in Python:

# Username validation
import re

def validate(username):
    regex = re.compile('^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$', re.I)
    match = regex.match(str(username))
    return bool(match)

print(validate("PeterParker")) #Valid username
print(validate("Peter-Parker")) #Valid username
print(validate("Peter-P-arker")) #Invalid username
print(validate("Peter")) #Invalid username
print(validate("PeterParker-")) #Invalid username
print(validate("-PeterParker")) #Invalid username
print(validate("1PeterParker")) #Invalid username
print(validate("Peter Parker")) #Invalid username
print(validate("PeterParkerSpiderMan")) #Invalid username

Thanks very much for any suggestion.

Body: ^(?=.{6,16}$)[A-Za-z][A-Za-z0-9]*-?[A-Za-z0-9]+$


问:
Still getting KeyError: 'SECRET_KEY' in my Django Project having set up environment variables
I created environment variables for my django project within my pipenv virtual envronment bin/activate (linux) or scripts\activate(windows) file , i made necessary changes in settings file as well as exiting and re activating the virtual environment but im still getting a keyerror (I'm working on a windows machine)

variables in settings.py

```<code>SECRET_KEY = os.environ['SECRET_KEY']

EMAIL_HOST_PASSWORD = os.environ['EMAIL_HOST_PASSWORD']
</code>```

evnvironment variables in virtualenv\scripts\activate file

```<code>export SECRET_KEY= "mysecretkey"

export EMAIL_HOST_PASSWORD= "mypassword"
</code>```

error

```<code>File "C:\Users\Dell\.virtualenvs\team-272-SMES-Server-dSgdZ4Ig\lib\os.py", line 673, in __getitem__
    raise KeyError(key) from None
KeyError: 'SECRET_KEY'
</code>```

答:
On a Windows server, I recommend creating a JSON (or YAML) file with all your database and app secrets. I personally prefer JSON, so an example of one is

```<code>{
"SECRET_KEY": "...",
"MYSQL_DBUSER": "jon"
"MYSQL_PW": "..."
...
}
</code>```

Then in your settings.py you should add something like

```<code>import json

with open("config.json") as config:
    config = json.load(config)
</code>```

Then to simply load in your project's secrets, index them by the variable name like

```<code>SECRET_KEY = config['SECRET_KEY']
</code>```

Body:
I created environment variables for my django project within my pipenv virtual envronment bin/activate (linux) or scripts\activate(windows) file , i made necessary changes in settings file as well as exiting and re activating the virtual environment but im still getting a keyerror (I'm working on a windows machine)

variables in settings.py

SECRET_KEY = os.environ['SECRET_KEY']

EMAIL_HOST_PASSWORD = os.environ['EMAIL_HOST_PASSWORD']

evnvironment variables in virtualenv\scripts\activate file

export SECRET_KEY= "mysecretkey"

export EMAIL_HOST_PASSWORD= "mypassword"

error

File "C:\Users\Dell\.virtualenvs\team-272-SMES-Server-dSgdZ4Ig\lib\os.py", line 673, in __getitem__
    raise KeyError(key) from None
KeyError: 'SECRET_KEY'

Body:
On a Windows server, I recommend creating a JSON (or YAML) file with all your database and app secrets. I personally prefer JSON, so an example of one is

{
"SECRET_KEY": "...",
"MYSQL_DBUSER": "jon"
"MYSQL_PW": "..."
...
}

Then in your settings.py you should add something like

import json

with open("config.json") as config:
    config = json.load(config)

Then to simply load in your project's secrets, index them by the variable name like

SECRET_KEY = config['SECRET_KEY']


问:
Why does my simple name change function in React not work?

import React, { Component } from "react";
import LogIn from "./LogIn.js"
import User from "./components/User.js"

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            projectList: [],
            myProjects: [],
            userList: [],
            currentUser: "Guest"
        };

        this.logIn = this.logIn.bind(this);
        }

    logIn(name) {
        this.setState({
            currentUser : name
        })
    }

    render() {
        return(

                <User name = {this.state.currentUser}/>
                <LogIn logIn = {this.logIn} />

        );
    }
}

export default App;```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from "react";

class LogIn extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        name: ""
      };

      this.handleSubmit = this.handleSubmit.bind(this);
      this.handleInputChange = this.handleInputChange.bind(this);
    }

    handleSubmit(event) {

      event.preventDefault();

      this.props.logIn(
        this.state.name
      )

    }

    handleInputChange(event) {
      const target = event.target;
      const value = target.value;
      const name = target.name;

      this.setState({
        [name]: value
      });
    }

    render() {
      return (
        <div>
            <h2> Login: </h2>
            <form onSubmit={this.handleSubmit}>
            <label>
                Name:
                <input
                name="name"
                type="textbox"
                checked={this.state.name}
                onChange={this.handleInputChange} />
            </label>
            <br />
            <input type="submit" value="Login" />
            </form>
        </div>
      );
    }
  }

export default LogIn;</code>```

import React, { Component } from "react";

class User extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name : props.name,
        }
    }

    render() {
        return (

 Current User: {this.state.name}

        )
      }
}

export default User;```

Here, I have a simple App, which gives users a login form, that allows them to change their name. The User class stores the name that App passes it and renders it. However, when I submit a name in the login form, no name change is rendered. Guest is shown throughout the entire process. This leads me to believe that currentUser is not changing. Can anyone tell me why the currentUser is unchanged after logIn is called?

答:
In User the constructor run only one time when the component re-render. When component re-render constructor is not called, so this.state.name will not updated when component re-render.
You do not need to set state for name, just render with this.props.name, the name in UI will be updated.

import React, { Component } from "react";

class User extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (

 Current User: {this.props.name}

        )
      }
}

export default User;```
</div>
</div>
</p>

<p>If you really want to have state for name, you need to update the state in <code>componentDidUpdate</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { Component } from "react";

class User extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name : props.name,
        }
    }

    componentDidUpdate(prevProps){
      if(prevProps.name !== this.props.name){
      this.setState({name: this.props.name})
    }

    render() {
        return (
          <div>
            <p> Current User: {this.state.name}</p>
          </div>
        )
      }
}

export default User;</code>```

Body:
import React, { Component } from "react";
import LogIn from "./LogIn.js"
import User from "./components/User.js"

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            projectList: [],
            myProjects: [],
            userList: [],
            currentUser: "Guest"
        };

        this.logIn = this.logIn.bind(this);
        }

    logIn(name) {
        this.setState({
            currentUser : name
        })
    }

    render() {
        return(

                <User name = {this.state.currentUser}/>
                <LogIn logIn = {this.logIn} />

        );
    }
}

export default App;

import React from "react";

class LogIn extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        name: ""
      };

      this.handleSubmit = this.handleSubmit.bind(this);
      this.handleInputChange = this.handleInputChange.bind(this);
    }

    handleSubmit(event) {

      event.preventDefault();

      this.props.logIn(
        this.state.name
      )

    }

    handleInputChange(event) {
      const target = event.target;
      const value = target.value;
      const name = target.name;

      this.setState({
        [name]: value
      });
    }

    render() {
      return (

 Login:

            <form onSubmit={this.handleSubmit}>

                Name:
                <input
                name="name"
                type="textbox"
                checked={this.state.name}
                onChange={this.handleInputChange} />

            <input type="submit" value="Login" />
            </form>

      );
    }
  }

export default LogIn;

import React, { Component } from "react";

class User extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name : props.name,
        }
    }

    render() {
        return (

 Current User: {this.state.name}

        )
      }
}

export default User;

Here, I have a simple App, which gives users a login form, that allows them to change their name. The User class stores the name that App passes it and renders it. However, when I submit a name in the login form, no name change is rendered. Guest is shown throughout the entire process. This leads me to believe that currentUser is not changing. Can anyone tell me why the currentUser is unchanged after logIn is called?

Body:
In User the constructor run only one time when the component re-render. When component re-render constructor is not called, so this.state.name will not updated when component re-render.
You do not need to set state for name, just render with this.props.name, the name in UI will be updated.

import React, { Component } from "react";

class User extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
          <div>
            <p> Current User: {this.props.name}</p>
          </div>
        )
      }
}

export default User;

If you really want to have state for name, you need to update the state in componentDidUpdate

import React, { Component } from "react";

class User extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name : props.name,
        }
    }

    componentDidUpdate(prevProps){
      if(prevProps.name !== this.props.name){
      this.setState({name: this.props.name})
    }

    render() {
        return (
          <div>
            <p> Current User: {this.state.name}</p>
          </div>
        )
      }
}

export default User;


问:
NLTK tokens - creating a single list of words from a pandas series
I'm looking for some help with NLTK, or anything other library that could help me solve the problem I'm facing.

I'm no Python expert (I actually only started learning Python 4 months ago), but I've made quite some research before asking for help:

Tokenizing words into a new column in a pandas dataframe

Passing a pandas dataframe column to an NLTK tokenizer
etc...

Here's what I have: a dataframe that contains quite a bit of information about what our students look for (it's the website for a campus) when they're searching for information on our website.

It looks a bit like this:

```<code>session             | student_query
2020-05-15 09:34:21 | exams session june 2020
2020-05-15 09:41:12 | when are the exams?
2020-05-15 09:59:51 | exams.
2020-05-15 10:02:18 | what's my teacher's email address
</code>```

What I would like to have, is one big list that looks like:
['query', 'exams', 'session', 'june', '2020', 'when', 'are', 'the', exams', 'exams', 'what', 's', 'my', 'teacher', 's', 'email', 'address]
===> one string, all the words (no sentences), no punctuation.

I have tried:

```<code>tokens = df['query'].apply(word_tokenize)
text = nltk.Text(tokens)
</code>```

===> that gives me an individual string for each row

```<code>sentences = pd.Series(df.Name)
sentences = sentences.str.replace('[^A-z ]','').str.replace(' +',' ').str.strip()
splitwords = [ nltk.word_tokenize( str(sentence) ) for sentence in sentences ]
print(splitwords)
</code>```

===> a bit better, but not what I want either

答:
You can just do this:</p>

```<code>df['student_query'] = df['student_query'].str.replace(r'\?|\.|\'', ' ')
list_of_words = ' '.join(df['student_query']).split()
print(list_of_words)

['exams', 'session', 'june', '2020', 'when', 'are', 'the', 'exams', 'exams', 'what', 's', 'my', 'teacher', 's', 'email', 'address']
</code>```

Body:
I'm looking for some help with NLTK, or anything other library that could help me solve the problem I'm facing.

I'm no Python expert (I actually only started learning Python 4 months ago), but I've made quite some research before asking for help:

Tokenizing words into a new column in a pandas dataframe

Passing a pandas dataframe column to an NLTK tokenizer
etc...

Here's what I have: a dataframe that contains quite a bit of information about what our students look for (it's the website for a campus) when they're searching for information on our website.

It looks a bit like this:

session             | student_query
2020-05-15 09:34:21 | exams session june 2020
2020-05-15 09:41:12 | when are the exams?
2020-05-15 09:59:51 | exams.
2020-05-15 10:02:18 | what's my teacher's email address

What I would like to have, is one big list that looks like:
['query', 'exams', 'session', 'june', '2020', 'when', 'are', 'the', exams', 'exams', 'what', 's', 'my', 'teacher', 's', 'email', 'address]
===> one string, all the words (no sentences), no punctuation.

I have tried:

tokens = df['query'].apply(word_tokenize)
text = nltk.Text(tokens)

===> that gives me an individual string for each row

sentences = pd.Series(df.Name)
sentences = sentences.str.replace('[^A-z ]','').str.replace(' +',' ').str.strip()
splitwords = [ nltk.word_tokenize( str(sentence) ) for sentence in sentences ]
print(splitwords)

===> a bit better, but not what I want either

Body:
You can just do this:

df['student_query'] = df['student_query'].str.replace(r'\?|\.|\'', ' ')
list_of_words = ' '.join(df['student_query']).split()
print(list_of_words)

['exams', 'session', 'june', '2020', 'when', 'are', 'the', 'exams', 'exams', 'what', 's', 'my', 'teacher', 's', 'email', 'address']


问:
Send parallel requests but only one per host with HttpClient and Polly to gracefully handle 429 responses
Intro:

I am building a single-node web crawler to simply validate URLs are 200 OK in a .NET Core console application. I have a collection of URLs at different hosts to which I am sending requests with HttpClient. I am fairly new to using Polly and TPL Dataflow.

Requirements:

I want to support sending multiple HTTP requests in parallel with a
configurable MaxDegreeOfParallelism.

I want to limit the number of parallel requests to any given host to 1 (or configurable). This is in order to gracefully handle per-host 429 TooManyRequests responses with a Polly policy. Alternatively, I could maybe use a Circuit Breaker to cancel concurrent requests to the same host on receipt of one 429 response and then proceed one-at-a-time to that specific host?

I am perfectly fine with not using TPL Dataflow at all in favor of maybe using a Polly Bulkhead or some other mechanism for throttled parallel requests, but I am not sure what that configuration would look like in order to implement requirement #2.

Current Implementation:

My current implementation works, except that I often see that I'll have x parallel requests to the same host return 429 at about the same time... Then, they all pause for the retry policy... Then, they all slam the same host again at the same time often still receiving 429s. Even if I distribute multiple instances of the same host evenly throughout the queue, my URL collection is overweighted with a few specific hosts that still start generating 429s eventually.

After receiving a 429, I think I only want to send one concurrent request to that host going forward to respect the remote host and pursue 200s.

Validator Method:

```<code>public async Task<int> GetValidCount(IEnumerable<Uri> urls, CancellationToken cancellationToken)
{
    var validator = new TransformBlock<Uri, bool>(
        async u => (await _httpClient.GetAsync(u, HttpCompletionOption.ResponseHeadersRead, cancellationToken)).IsSuccessStatusCode,
        new ExecutionDataflowBlockOptions {MaxDegreeOfParallelism = MaxDegreeOfParallelism}
    );
    foreach (var url in urls)
        await validator.SendAsync(url, cancellationToken);
    validator.Complete();
    var validUrlCount = 0;
    while (await validator.OutputAvailableAsync(cancellationToken))
    {
        if(await validator.ReceiveAsync(cancellationToken))
            validUrlCount++;
    }
    await validator.Completion;
    return validUrlCount;
}
</code>```

The Polly policy applied to the HttpClient instance used in GetValidCount() above.

```<code>IAsyncPolicy<HttpResponseMessage> waitAndRetryTooManyRequests = Policy
    .HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.TooManyRequests)
    .WaitAndRetryAsync(3,
        (retryCount, response, context) =>
            response.Result?.Headers.RetryAfter.Delta ?? TimeSpan.FromMilliseconds(120),
        async (response, timespan, retryCount, context) =>
        {
            // log stuff
        });
</code>```

Question:

How can I modify or replace this solution to add satisfaction of requirement #2?

答:
I'd try to introduce some sort of a flag LimitedMode  to detect that this particular client is entered in limited mode. Below I declare two policies - one simple retry policy just to catch TooManyRequests and set the flag. The second policy is a out-of-the-box BulkHead policy.

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        /* other configuration */

        var registry = services.AddPolicyRegistry();

        var catchPolicy = Policy.HandleResult<HttpResponseMessage>(r =>
            {
                LimitedMode = r.StatusCode == HttpStatusCode.TooManyRequests;
                return false;
            })
            .WaitAndRetryAsync(1, i => TimeSpan.FromSeconds(3));

        var bulkHead = Policy.BulkheadAsync<HttpResponseMessage>(1, 10, OnBulkheadRejectedAsync);

        registry.Add("catchPolicy", catchPolicy);
        registry.Add("bulkHead", bulkHead);

        services.AddHttpClient<CrapyWeatherApiClient>((client) =>
        {
            client.BaseAddress = new Uri("hosturl");
        }).AddPolicyHandlerFromRegistry(PolicySelector);
    }
</code>```

Then you may want to dynamically decide on which policy to apply using the PolicySelector mechanism: in case the limited mode is active - wrap bulk head policy with catch 429 policy. If the success status code received - switch back to regular mode without a bulkhead.

```<code>    private IAsyncPolicy<HttpResponseMessage> PolicySelector(IReadOnlyPolicyRegistry<string> registry, HttpRequestMessage request)
    {
        var catchPolicy = registry.Get<IAsyncPolicy<HttpResponseMessage>>("catchPolicy");
        var bulkHead = registry.Get<IAsyncPolicy<HttpResponseMessage>>("bulkHead");
        if (LimitedMode)
        {
            return catchPolicy.WrapAsync(bulkHead);
        }

        return catchPolicy;
    }
</code>```

Body:
Intro:

I am building a single-node web crawler to simply validate URLs are 200 OK in a .NET Core console application. I have a collection of URLs at different hosts to which I am sending requests with HttpClient. I am fairly new to using Polly and TPL Dataflow.

Requirements:

I want to support sending multiple HTTP requests in parallel with a
configurable MaxDegreeOfParallelism.

I want to limit the number of parallel requests to any given host to 1 (or configurable). This is in order to gracefully handle per-host 429 TooManyRequests responses with a Polly policy. Alternatively, I could maybe use a Circuit Breaker to cancel concurrent requests to the same host on receipt of one 429 response and then proceed one-at-a-time to that specific host?

I am perfectly fine with not using TPL Dataflow at all in favor of maybe using a Polly Bulkhead or some other mechanism for throttled parallel requests, but I am not sure what that configuration would look like in order to implement requirement #2.

Current Implementation:

My current implementation works, except that I often see that I'll have x parallel requests to the same host return 429 at about the same time... Then, they all pause for the retry policy... Then, they all slam the same host again at the same time often still receiving 429s. Even if I distribute multiple instances of the same host evenly throughout the queue, my URL collection is overweighted with a few specific hosts that still start generating 429s eventually.

After receiving a 429, I think I only want to send one concurrent request to that host going forward to respect the remote host and pursue 200s.

Validator Method:

public async Task<int> GetValidCount(IEnumerable<Uri> urls, CancellationToken cancellationToken)
{
    var validator = new TransformBlock<Uri, bool>(
        async u => (await _httpClient.GetAsync(u, HttpCompletionOption.ResponseHeadersRead, cancellationToken)).IsSuccessStatusCode,
        new ExecutionDataflowBlockOptions {MaxDegreeOfParallelism = MaxDegreeOfParallelism}
    );
    foreach (var url in urls)
        await validator.SendAsync(url, cancellationToken);
    validator.Complete();
    var validUrlCount = 0;
    while (await validator.OutputAvailableAsync(cancellationToken))
    {
        if(await validator.ReceiveAsync(cancellationToken))
            validUrlCount++;
    }
    await validator.Completion;
    return validUrlCount;
}

The Polly policy applied to the HttpClient instance used in GetValidCount() above.

IAsyncPolicy<HttpResponseMessage> waitAndRetryTooManyRequests = Policy
    .HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.TooManyRequests)
    .WaitAndRetryAsync(3,
        (retryCount, response, context) =>
            response.Result?.Headers.RetryAfter.Delta ?? TimeSpan.FromMilliseconds(120),
        async (response, timespan, retryCount, context) =>
        {
            // log stuff
        });

Question:

How can I modify or replace this solution to add satisfaction of requirement #2?

Body:
I'd try to introduce some sort of a flag LimitedMode  to detect that this particular client is entered in limited mode. Below I declare two policies - one simple retry policy just to catch TooManyRequests and set the flag. The second policy is a out-of-the-box BulkHead policy.

    public void ConfigureServices(IServiceCollection services)
    {
        /* other configuration */

        var registry = services.AddPolicyRegistry();

        var catchPolicy = Policy.HandleResult<HttpResponseMessage>(r =>
            {
                LimitedMode = r.StatusCode == HttpStatusCode.TooManyRequests;
                return false;
            })
            .WaitAndRetryAsync(1, i => TimeSpan.FromSeconds(3));

        var bulkHead = Policy.BulkheadAsync<HttpResponseMessage>(1, 10, OnBulkheadRejectedAsync);

        registry.Add("catchPolicy", catchPolicy);
        registry.Add("bulkHead", bulkHead);

        services.AddHttpClient<CrapyWeatherApiClient>((client) =>
        {
            client.BaseAddress = new Uri("hosturl");
        }).AddPolicyHandlerFromRegistry(PolicySelector);
    }

Then you may want to dynamically decide on which policy to apply using the PolicySelector mechanism: in case the limited mode is active - wrap bulk head policy with catch 429 policy. If the success status code received - switch back to regular mode without a bulkhead.

    private IAsyncPolicy<HttpResponseMessage> PolicySelector(IReadOnlyPolicyRegistry<string> registry, HttpRequestMessage request)
    {
        var catchPolicy = registry.Get<IAsyncPolicy<HttpResponseMessage>>("catchPolicy");
        var bulkHead = registry.Get<IAsyncPolicy<HttpResponseMessage>>("bulkHead");
        if (LimitedMode)
        {
            return catchPolicy.WrapAsync(bulkHead);
        }

        return catchPolicy;
    }


问:
Align image in div & give div space from card
So I am trying to make a little "card", to show information about products. Now I want a little picture of each product at the top, but I need to center it verticle and horizontally.

I also need to give the image/div a little space, tried doing margin-top: 1em; but didn't do anything at all.

Here is my HTML code:

```<code><div class="container">
  <div class="row">
    {% for auction in auctions%}
    <div class="col-sm-4">
      <div class="auction-item">
        <div class="img-container">
          <img
            src="/static/img/grass.png"
            alt="Grass Block"
            class="item-icon"
          />
        </div>
        <h2>{{ auction.name }}</h2>
        <div class="average-price">
          <h3>Average Price: {{ auction.start_bid }}</h3>
        </div>
        <div class="time-left">
          <h3>Time Left: time</h3>
        </div>
        <div class="graph-div">
          <a class="graph-tag" href="#">Show Graph</a>
        </div>
      </div>
    </div>
    {% endfor %}
  </div>
</div>
</code>```

CSS can be found here:

```<code>.img-container {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background-color: #333;
  margin-top: 1em;
  margin: auto;
  text-align: center;
}

.item-icon {
  width: 80%;
}

.auction-item {
  width: 275px;
  height: 320px;
  background-color: blue;
  border-radius: 25px;
  margin: 3em;
}

.auction-item h2 {
  color: white;
  font-size: 24px;
  text-align: center;
  padding-top: 1em;
}

.auction-item h3 {
  color: white;
  font-size: 20px;
  text-align: center;
  padding-top: 1em;
}

.graph-div {
  text-align: center;
  padding-top: 1em;
}

.graph-tag {
  color: white;
  font-size: 20px;
}
</code>```

And here is how it looks right now:

答:
When you want some content to be placed exactly at the center then always remember to use positions(relative & absolute) this will help the data to sit within the element.

Use flex and use vertical-align(optional) to center.

Use top:5%; to bring the image tag down on .img-container{...}

.auction-item {
  width: 275px;
  height: 320px;
  background-color: blue;
  border-radius: 25px;
  margin: 3em;
}

.img-container {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background-color: #333;
  margin: auto;
  text-align: center;
  display: flex;
  vertical-align: middle;
  position: relative;
  top: 5%;
}

.item-icon {
  border-radius: 50%;
  width: 100%;
  height: 100%;
  position: absolute;
}

.auction-item h2 {
  color: white;
  font-size: 24px;
  text-align: center;
  padding-top: 1em;
}

.auction-item h3 {
  color: white;
  font-size: 20px;
  text-align: center;
  padding-top: 1em;
}

.graph-div {
  text-align: center;
  padding-top: 1em;
}

.graph-tag {
  color: white;
  font-size: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    {% for auction in auctions%}
    <div class="col-sm-4">
      <div class="auction-item">
        <div class="img-container">
          <img src="http://placekitten.com/301/301" alt="Grass Block" class="item-icon" />
        </div>
        <h2>{{ auction.name }}</h2>
        <div class="average-price">
          <h3>Average Price: {{ auction.start_bid }}</h3>
        </div>
        <div class="time-left">
          <h3>Time Left: time</h3>
        </div>
        <div class="graph-div">
          Show Graph
        </div>
      </div>
    </div>
    {% endfor %}
  </div>
</div></code>```

Body:
So I am trying to make a little "card", to show information about products. Now I want a little picture of each product at the top, but I need to center it verticle and horizontally.

I also need to give the image/div a little space, tried doing margin-top: 1em; but didn't do anything at all.

Here is my HTML code:

    {% for auction in auctions%}

{{ auction.name }}

Average Price: {{ auction.start_bid }}

Time Left: time

          Show Graph

    {% endfor %}

CSS can be found here:

.img-container {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background-color: #333;
  margin-top: 1em;
  margin: auto;
  text-align: center;
}

.item-icon {
  width: 80%;
}

.auction-item {
  width: 275px;
  height: 320px;
  background-color: blue;
  border-radius: 25px;
  margin: 3em;
}

.auction-item h2 {
  color: white;
  font-size: 24px;
  text-align: center;
  padding-top: 1em;
}

.auction-item h3 {
  color: white;
  font-size: 20px;
  text-align: center;
  padding-top: 1em;
}

.graph-div {
  text-align: center;
  padding-top: 1em;
}

.graph-tag {
  color: white;
  font-size: 20px;
}

And here is how it looks right now:

Body:
When you want some content to be placed exactly at the center then always remember to use positions(relative & absolute) this will help the data to sit within the element.

Use flex and use vertical-align(optional) to center.

Use top:5%; to bring the image tag down on .img-container{...}

.auction-item {
  width: 275px;
  height: 320px;
  background-color: blue;
  border-radius: 25px;
  margin: 3em;
}

.img-container {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background-color: #333;
  margin: auto;
  text-align: center;
  display: flex;
  vertical-align: middle;
  position: relative;
  top: 5%;
}

.item-icon {
  border-radius: 50%;
  width: 100%;
  height: 100%;
  position: absolute;
}

.auction-item h2 {
  color: white;
  font-size: 24px;
  text-align: center;
  padding-top: 1em;
}

.auction-item h3 {
  color: white;
  font-size: 20px;
  text-align: center;
  padding-top: 1em;
}

.graph-div {
  text-align: center;
  padding-top: 1em;
}

.graph-tag {
  color: white;
  font-size: 20px;
}

<div class="container">
  <div class="row">
    {% for auction in auctions%}
    <div class="col-sm-4">
      <div class="auction-item">
        <div class="img-container">
          <img src="http://placekitten.com/301/301" alt="Grass Block" class="item-icon" />
        </div>
        <h2>{{ auction.name }}</h2>
        <div class="average-price">
          <h3>Average Price: {{ auction.start_bid }}</h3>
        </div>
        <div class="time-left">
          <h3>Time Left: time</h3>
        </div>
        <div class="graph-div">
          <a class="graph-tag" href="#">Show Graph</a>
        </div>
      </div>
    </div>
    {% endfor %}
  </div>
</div>


答:
This should work:

```<code>$str = substr($str, 0, strrpos($str, '/') - 1);
</code>```

...but see icktoofay's solution if you're only planning on using this to handle file paths.

Title: PHP string help

Body:
Hey, so I am trying to learn some string functions in PHP and came across a senario I cannot figure out. I want to take a string like such: /var/www/html and remove everything after the last forward slash (including the forward slash) so I end up with /var/www

What would be the best way to go about this? Many thanks.

Body:
This should work:

$str = substr($str, 0, strrpos($str, '/') - 1);

...but see icktoofay's solution if you're only planning on using this to handle file paths.


问:
Read part files from hdfs into data frame using pySpark
I have multiple files stored in a hdfs location as follows

/user/project/202005/part-01798

/user/project/202005/part-01799

There are 2000 such part files. Each file is of the format

```<code>{'Name':'abc','Age':28,'Marks':[20,25,30]}
{'Name':...}
</code>```

and so on . I have 2 questions

```<code>1) How to check whether these are multiple files or multiple partitions of the same file
2) How to read these in a data frame using pyspark
</code>```

答:
As these files are in one directory, and these are named as part-xxxxx files, so you can safely assume these are multiple part files of the same dataset. If these are partitions, they should be saved like this /user/project/date=202005/*

You can specify the dir "/user/project/202005" as input for spark like below assuming these are csv files

```<code>df = spark.read.csv('/user/project/202005/*',header=True, inferSchema=True)
</code>```

Body:
I have multiple files stored in a hdfs location as follows

/user/project/202005/part-01798

/user/project/202005/part-01799

There are 2000 such part files. Each file is of the format

{'Name':'abc','Age':28,'Marks':[20,25,30]}
{'Name':...}

and so on . I have 2 questions

1) How to check whether these are multiple files or multiple partitions of the same file
2) How to read these in a data frame using pyspark

Body:
As these files are in one directory, and these are named as part-xxxxx files, so you can safely assume these are multiple part files of the same dataset. If these are partitions, they should be saved like this /user/project/date=202005/*

You can specify the dir "/user/project/202005" as input for spark like below assuming these are csv files

df = spark.read.csv('/user/project/202005/*',header=True, inferSchema=True)


问:
regex for splitting a string while ignoring the brackets
I want to split a string with space-character but ignoring the space between two brackets.

The code i used is:

```<code>String s = "hello (split this) string";
String reg = "(?<=([^\\(].*))( )(?=(.*[^\\)]))";
System.out.println(Arrays.toString(s.split(reg));
</code>```

My expected output is:

```<code>[hello , (split this) , string]
</code>```

but i get this error

Exception in thread "main" java.util.regex.PatternSyntaxException: Look-behind group does not have an obvious maximum length near index 12
  (?<=([^(].))z(?=(.*[^)]))  *

I need a regex to get the expected output.

So, somebody please help.

答:
You can use the below regex to achieve your requirement:

```<code>[ ](?=[^\)]*?(?:\(|$))
</code>```

Explanation of the above regex:

[ ] - Represents a space character.

(?=[^\)]*?(?:\(|$)) - Represents a positive look-ahead asserting everything inside of ().

(?:) - Represents a non-capturing group.

| - Represents alternation.

$ - Represents the end of the test String.

You can find the demo of the above regex in here.

IMPLEMENTATION IN JAVA

```<code>import java.util.Arrays;
public class Main
{
    public static void main(String[] args) {
        String s = "hello (split this) string";
        String reg = "[ ](?=[^\\)]*?(?:\\(|$))";
        System.out.println(Arrays.toString(s.split(reg)));
    }
}

// output: [hello, (split this), string]
</code>```

You can find the above implementation here.

Body:
I want to split a string with space-character but ignoring the space between two brackets.

The code i used is:

String s = "hello (split this) string";
String reg = "(?<=([^\\(].*))( )(?=(.*[^\\)]))";
System.out.println(Arrays.toString(s.split(reg));

My expected output is:

[hello , (split this) , string]

but i get this error

Exception in thread "main" java.util.regex.PatternSyntaxException: Look-behind group does not have an obvious maximum length near index 12
  (?<=([^(].))z(?=(.*[^)]))  *

I need a regex to get the expected output.

So, somebody please help.

Body:
You can use the below regex to achieve your requirement:

[ ](?=[^\)]*?(?:\(|$))

Explanation of the above regex:

[ ] - Represents a space character.

(?=[^\)]*?(?:\(|$)) - Represents a positive look-ahead asserting everything inside of ().

(?:) - Represents a non-capturing group.

| - Represents alternation.

$ - Represents the end of the test String.

You can find the demo of the above regex in here.

IMPLEMENTATION IN JAVA

import java.util.Arrays;
public class Main
{
    public static void main(String[] args) {
        String s = "hello (split this) string";
        String reg = "[ ](?=[^\\)]*?(?:\\(|$))";
        System.out.println(Arrays.toString(s.split(reg)));
    }
}

// output: [hello, (split this), string]

You can find the above implementation here.


问:
Support with the Return Function
I am having a bit of trouble with the return function on VBA and was hoping someone would be able to help me troubleshoot the issue.

Here is the function:

```<code>Function Hypotenuse(side1 As Double, side2 As Double) As Double
Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2))
End Function
</code>```

Summary of the Issue:

The return function is highlighted in 'red' and I am unable to run any sub-routine that calls the function (see attached picture)

Pretty sure the code is code is correct, but i simply do not understand why I keep getting an error

Any idea why this may be happening?

Any help will be much appreciated :)

答:
Use Sqr function .. and no Return keyword in VBA</p>

```<code>Sub Test()
    Debug.Print Hypotenuse(5, 3)
End Sub

Function Hypotenuse(side1 As Double, side2 As Double) As Double
    Hypotenuse = Sqr((side1 ^ 2) + (side2 ^ 2))
End Function
</code>```

Title: Support with the Return Function

Body:
I am having a bit of trouble with the return function on VBA and was hoping someone would be able to help me troubleshoot the issue.

Here is the function:

Function Hypotenuse(side1 As Double, side2 As Double) As Double
Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2))
End Function

Summary of the Issue:

The return function is highlighted in 'red' and I am unable to run any sub-routine that calls the function (see attached picture)

Pretty sure the code is code is correct, but i simply do not understand why I keep getting an error

Any idea why this may be happening?

Any help will be much appreciated :)

Body:
Use Sqr function .. and no Return keyword in VBA

Sub Test()
    Debug.Print Hypotenuse(5, 3)
End Sub

Function Hypotenuse(side1 As Double, side2 As Double) As Double
    Hypotenuse = Sqr((side1 ^ 2) + (side2 ^ 2))
End Function


答:
The -r in jq -r removed quotes, this is what's needed :

```<code>declare VERSIONS=($(curl -s https://api.github.com/repos/humhub/humhub/releases | jq '.[].name'))
</code>```

Title: json jq array to string with double quotes

Body:
I am trying to convert an array to string and would like to be:

declare -r LOCAL_VERSIONS=(
    "1.3.17"
    "1.3.18"
    "1.3.19"
    "1.3.20"
    "1.4.0-beta.1"
    "1.4.0-beta.1"
    "1.4.0-beta.2"
    "1.4.0"
    "1.4.1"
    "1.4.2"
    "1.4.3"
    "1.4.4"
    "1.5.0-beta.1"
    "1.5.0"
    "1.5.1"
    "1.5.2"
)

The best I got so far is:

declare -r VERSIONS=(=${VERSIONS:-$(curl -s https://api.github.com/repos/humhub/humhub/releases | jq -r '.[] | [.name] | join(" ")')})

which outputs:

1.5.1
1.5.0
1.5.0-beta.1
1.4.4
1.4.3
1.4.2
1.4.1
1.4.0
1.3.20
1.3.19
1.4.0-beta.2
1.3.18
1.4.0-beta.1
1.3.17
1.3.9
1.3.8
1.3.7
1.3.6
1.3.5
1.3.4
1.3.3
1.3.2

How I can achieve as LOCAL_VERSIONS using curl (meaning getting versions from GitHub) ?

Body:
The -r in jq -r removed quotes, this is what's needed :

declare VERSIONS=($(curl -s https://api.github.com/repos/humhub/humhub/releases | jq '.[].name'))


问:
Convert to binary and keep leading zeros
I'm trying to convert an integer to binary using the bin() function in Python. However, it always removes the leading zeros, which I actually need, such that the result is always 8-bit:

Example:

```<code>bin(1) -> 0b1

# What I would like:
bin(1) -> 0b00000001
</code>```

Is there a way of doing this?

答:
You can use string.rjust method:

```<code>string.rjust(length, fillchar)
</code>```

fillchar is optional

and for your Question you can write like this

```<code>'0b'+ '1'.rjust(8,'0)
</code>```

so it will be '0b00000001'

Body:
I'm trying to convert an integer to binary using the bin() function in Python. However, it always removes the leading zeros, which I actually need, such that the result is always 8-bit:

Example:

bin(1) -> 0b1

# What I would like:
bin(1) -> 0b00000001

Is there a way of doing this?

Body:
You can use string.rjust method:

string.rjust(length, fillchar)

fillchar is optional

and for your Question you can write like this

'0b'+ '1'.rjust(8,'0)

so it will be '0b00000001'


问:
How to play intro, that it's only played when app is installed, when a button is clicked?
Before the user uses the app there is an intro that explains how the app is used. However I want to add a button to the homepage that ables the user to see the intro again. How should I do that?
I already tried to call the class Intro in the class Homepage but nothing happens
Here is the code of my Intro: </p>

```<code>    class Intro : AppCompatActivity() {

private val introSliderAdapter = IntroSliderAdapter(
    listOf(
        IntroSlide("Capture a ignição",
            "Tire uma fotografia á ignição que avista. Por favor mantanha o telemóvel na vertical",
            R.drawable.image1),
        IntroSlide("Localização",
            "É necessário que tenha o GPS ligado do seu telémovel. Ao capturar a fotografia serão automáticamente gravados a sua localização e o ângulo a que o fogo se encontra",
            R.drawable.image2),
        IntroSlide("Envio para os operacionais ",
            "Após os passos anteriores devidamente cumpridos, a informação fornecida será  avaliada por operacionais responsáveis.",
            R.drawable.image3)
    )
)

private var PRIVATE_MODE = 0
private val PREF_NAME = "mindorks-welcome"

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //setContentView(R.layout.activity_main)
    val sharedPref: SharedPreferences = getSharedPreferences(PREF_NAME, PRIVATE_MODE)
    if (sharedPref.getBoolean(PREF_NAME, false)) {
        val homeIntent = Intent(this, HomePage::class.java)
        startActivity(homeIntent)
        finish()
    } else {
        setContentView(R.layout.activity_intro)
        playIntro()
        val editor = sharedPref.edit()
        editor.putBoolean(PREF_NAME, true)
        editor.apply()
    }
}

fun playIntro()
{
    introSliderViewPager.adapter=introSliderAdapter
    setupIndicators()
    setCurrentIndicator(0)
    introSliderViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){
        override fun onPageSelected(position: Int) {
            setCurrentIndicator(position)

        }
    })

    buttonNext.setOnClickListener {
        if(introSliderViewPager.currentItem+1 < introSliderAdapter.itemCount){
            introSliderViewPager.currentItem+=1
        }else{

            Intent(applicationContext, HomePage::class.java).also {
                startActivity(it)
                finish()
            }

        }

    }
    buttonSkip.setOnClickListener {
        Intent(applicationContext, HomePage::class.java).also {
            startActivity(it)
            finish()
        }
    }

}
private fun setupIndicators(){
    val indicators = arrayOfNulls<ImageView>(introSliderAdapter.itemCount)
    val layoutParams : LinearLayout.LayoutParams = LinearLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT
    )
    layoutParams.setMargins(8,0,8,0)
    for (i in indicators.indices){
        indicators[i]  = ImageView(applicationContext)
        indicators[i].apply {
            this?.setImageDrawable(
                ContextCompat.getDrawable(
                    applicationContext,
                    R.drawable.indicator_inactive
                )
            )
            this?.layoutParams = layoutParams
        }
        indicatorsContainer.addView(indicators[i])
    }
}
private fun setCurrentIndicator(index:Int ){
    val childCount = indicatorsContainer.childCount
    for(i in 0 until childCount){
        val imageView = indicatorsContainer[i] as ImageView
        if(i==index){
            imageView.setImageDrawable(
                ContextCompat.getDrawable(
                    applicationContext,
                    R.drawable.indicator_active
                )
            )
            buttonNext.text ="PRÓXIMO"
        }else{
            imageView.setImageDrawable(
                ContextCompat.getDrawable(
                    applicationContext,
                    R.drawable.indicator_inactive
                )
            )
            buttonNext.text ="PRÓXIMO"

        }

    }
    if(index == introSliderAdapter.itemCount -1)
    {
        buttonNext.text ="FIM"
    }
}
 }
</code>```

答: You could try to just reset the SharedPreference to false and then call the Intro-Page again.

Body:
Before the user uses the app there is an intro that explains how the app is used. However I want to add a button to the homepage that ables the user to see the intro again. How should I do that?
I already tried to call the class Intro in the class Homepage but nothing happens
Here is the code of my Intro:

    class Intro : AppCompatActivity() {

private val introSliderAdapter = IntroSliderAdapter(
    listOf(
        IntroSlide("Capture a ignição",
            "Tire uma fotografia á ignição que avista. Por favor mantanha o telemóvel na vertical",
            R.drawable.image1),
        IntroSlide("Localização",
            "É necessário que tenha o GPS ligado do seu telémovel. Ao capturar a fotografia serão automáticamente gravados a sua localização e o ângulo a que o fogo se encontra",
            R.drawable.image2),
        IntroSlide("Envio para os operacionais ",
            "Após os passos anteriores devidamente cumpridos, a informação fornecida será  avaliada por operacionais responsáveis.",
            R.drawable.image3)
    )
)

private var PRIVATE_MODE = 0
private val PREF_NAME = "mindorks-welcome"

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //setContentView(R.layout.activity_main)
    val sharedPref: SharedPreferences = getSharedPreferences(PREF_NAME, PRIVATE_MODE)
    if (sharedPref.getBoolean(PREF_NAME, false)) {
        val homeIntent = Intent(this, HomePage::class.java)
        startActivity(homeIntent)
        finish()
    } else {
        setContentView(R.layout.activity_intro)
        playIntro()
        val editor = sharedPref.edit()
        editor.putBoolean(PREF_NAME, true)
        editor.apply()
    }
}

fun playIntro()
{
    introSliderViewPager.adapter=introSliderAdapter
    setupIndicators()
    setCurrentIndicator(0)
    introSliderViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){
        override fun onPageSelected(position: Int) {
            setCurrentIndicator(position)

        }
    })

    buttonNext.setOnClickListener {
        if(introSliderViewPager.currentItem+1 < introSliderAdapter.itemCount){
            introSliderViewPager.currentItem+=1
        }else{

            Intent(applicationContext, HomePage::class.java).also {
                startActivity(it)
                finish()
            }

        }

    }
    buttonSkip.setOnClickListener {
        Intent(applicationContext, HomePage::class.java).also {
            startActivity(it)
            finish()
        }
    }

}
private fun setupIndicators(){
    val indicators = arrayOfNulls<ImageView>(introSliderAdapter.itemCount)
    val layoutParams : LinearLayout.LayoutParams = LinearLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT
    )
    layoutParams.setMargins(8,0,8,0)
    for (i in indicators.indices){
        indicators[i]  = ImageView(applicationContext)
        indicators[i].apply {
            this?.setImageDrawable(
                ContextCompat.getDrawable(
                    applicationContext,
                    R.drawable.indicator_inactive
                )
            )
            this?.layoutParams = layoutParams
        }
        indicatorsContainer.addView(indicators[i])
    }
}
private fun setCurrentIndicator(index:Int ){
    val childCount = indicatorsContainer.childCount
    for(i in 0 until childCount){
        val imageView = indicatorsContainer[i] as ImageView
        if(i==index){
            imageView.setImageDrawable(
                ContextCompat.getDrawable(
                    applicationContext,
                    R.drawable.indicator_active
                )
            )
            buttonNext.text ="PRÓXIMO"
        }else{
            imageView.setImageDrawable(
                ContextCompat.getDrawable(
                    applicationContext,
                    R.drawable.indicator_inactive
                )
            )
            buttonNext.text ="PRÓXIMO"

        }

    }
    if(index == introSliderAdapter.itemCount -1)
    {
        buttonNext.text ="FIM"
    }
}
 }