答:
Following a rather traditional approach:

str1 = 'This Python is good Good python'

words_seen = set()
output = []
for word in str1.split():
    if word.lower() not in words_seen:
        words_seen.add(word.lower())
        output.append(word)
output = ' '.join(output)

print(output) # This Python is good
```
<p>A caveat: it would not preserve word boundaries consisting of multiple spaces: <code>'python   puppy'</code> would become <code>'python puppy'</code>.</p>
<p>A very ugly short version:</p>
<pre class="lang-py prettyprint-override"><code>words_seen = set()
output = ' '.join(word for word in str1.split() if not (word.lower() in words_seen or words_seen.add(word.lower())))
</code>```

Title: How to remove duplicate words removing duplicates not case sensetive

Body:
Following a rather traditional approach:

str1 = 'This Python is good Good python'

words_seen = set()
output = []
for word in str1.split():
    if word.lower() not in words_seen:
        words_seen.add(word.lower())
        output.append(word)
output = ' '.join(output)

print(output) # This Python is good

A caveat: it would not preserve word boundaries consisting of multiple spaces: 'python   puppy' would become 'python puppy'.

A very ugly short version:

words_seen = set()
output = ' '.join(word for word in str1.split() if not (word.lower() in words_seen or words_seen.add(word.lower())))


来源: stackexchange

问:
Iterating over Map object
I'm new to javascript and I'm trying to understand how to use the Map feature.
I have an array of numbers, and if the value is 0, I want the key of the object to be false, and for any other value; true.</p>

答:
Since map key is unique, so you got only two keys. If you want to get maps for each values, you can make a pair of key and value and then insert it into an array.

```<code>const array1 = [1,0,1,0,1,-1];

let result = [];
for (values of array1 ) {
    if (values !== 0) {
        const mapExample = new Map();
        mapExample.set(true, values)
        result.push(mapExample)
    } else {
        const mapExample = new Map();
        mapExample.set(false, values)
        result.push(mapExample)
    }
}

console.log(result)
</code>```

the result would be like this

```<code>[
  Map(1) { true => 1 },
  Map(1) { false => 0 },
  Map(1) { true => 1 },
  Map(1) { false => 0 },
  Map(1) { true => 1 },
  Map(1) { true => -1 }
]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Iterating over Map object

Body:
Since map key is unique, so you got only two keys. If you want to get maps for each values, you can make a pair of key and value and then insert it into an array.

const array1 = [1,0,1,0,1,-1];

let result = [];
for (values of array1 ) {
    if (values !== 0) {
        const mapExample = new Map();
        mapExample.set(true, values)
        result.push(mapExample)
    } else {
        const mapExample = new Map();
        mapExample.set(false, values)
        result.push(mapExample)
    }
}

console.log(result)

the result would be like this

[
  Map(1) { true => 1 },
  Map(1) { false => 0 },
  Map(1) { true => 1 },
  Map(1) { false => 0 },
  Map(1) { true => 1 },
  Map(1) { true => -1 }
]


问:
A href pointed to nowhere added # to url
I have a href which pointed to #

```<code><a href="#" id="bla" >Bla<a>
</code>```

I have onclick function which displaying popup on click on that a href.

```<code>function doingClick()
{
   //display popup
   return false;
}
</code>```

But after click symbol # every time added to the url in browser.

So for example if url was like that before I click on my link http://mywebsite.com

But after click on a href the url looking like that: http://mywebsite.com#

Is there any way to avoid such behavior?

答:
A simple workaround would be set the href empty:

```<code><a href="" id="bla" onClick="alert('Hi');">Bla<a>
</code>```

Which still works.

ContentLicense: CC BY-SA 3.0

Body:
I have a href which pointed to #

Bla

I have onclick function which displaying popup on click on that a href.

function doingClick()
{
   //display popup
   return false;
}

But after click symbol # every time added to the url in browser.

So for example if url was like that before I click on my link http://mywebsite.com

But after click on a href the url looking like that: http://mywebsite.com#

Is there any way to avoid such behavior?

Body:
A simple workaround would be set the href empty:

<a href="" id="bla" onClick="alert('Hi');">Bla<a>

Which still works.


问:
How do I convert a woff2 font to ttf using fonttools in Python?
I have woff2 files that I would like to convert to ttf using Python and the fonttools library. I have seen some methods on how to convert ttf fonts to woff2 but I can't use them to do the opposite.

Thanks in advance

答:
Here's the one-line command (on Windows):

python -c "from fontTools.ttLib import woff2; import brotli; woff2.decompress('path/to/your.woff2', 'path/to/output.ttf')"

Make sure you have installed brotli. Use forward slash (/) for the file path instead of backslash (\). The output can be either TTF or OTF.


问:
How to check an IP address is within a range of two IPs in PHP?
I have an IP address and I'm given two other IP addresses which together creates an IP range. I want to check if the first IP address is within this range. How can i find that out in PHP?</p>

答:
I used this for my client:

```<code>$clientIpArray = explode(".", $clientIp);
$fromArray = explode(".", $from);
$toArray = explode(".", $to);

if( ((str_pad($clientIpArray[0], 3, "0", STR_PAD_LEFT) >= str_pad($fromArray[0], 3, "0", STR_PAD_LEFT)) && (str_pad($clientIpArray[0], 3, "0", STR_PAD_LEFT) <= str_pad($toArray[0], 3, "0", STR_PAD_LEFT)))
 &&((str_pad($clientIpArray[1], 3, "0", STR_PAD_LEFT) >= str_pad($fromArray[1], 3, "0", STR_PAD_LEFT)) && (str_pad($clientIpArray[1], 3, "0", STR_PAD_LEFT) <= str_pad($toArray[1], 3, "0", STR_PAD_LEFT)))
 &&((str_pad($clientIpArray[2], 3, "0", STR_PAD_LEFT) >= str_pad($fromArray[2], 3, "0", STR_PAD_LEFT)) && (str_pad($clientIpArray[2], 3, "0", STR_PAD_LEFT) <= str_pad($toArray[2], 3, "0", STR_PAD_LEFT)))
 &&((str_pad($clientIpArray[3], 3, "0", STR_PAD_LEFT) >= str_pad($fromArray[3], 3, "0", STR_PAD_LEFT)) && (str_pad($clientIpArray[3], 3, "0", STR_PAD_LEFT) <= str_pad($toArray[3], 3, "0", STR_PAD_LEFT)))){
  echo "IP within range";
}
</code>```

For example, let's take this example:

```<code>$clientIp = "120.02.3.112";
$from = "1.02.1.112";
$to = "120.02.20.112";
</code>```

As you can understand this IP is within the range. If you try to compare it as it is it won't work.
My solution is to divide the IP into elements, so for example the generated arrays would be:

```<code>$clientIpArray = ["120","02","3","112"];
$fromArray = ["1","02","1","112"];
$toArray = ["120","02","20","112"];
</code>```

We have 4 elements to compare, here I used str_pad function to generate a 3 characters string from each element, so instead of checking if "3" is between "1" and "20" (which is not true) we will check if "003" is between "001" and "020" (which is correct).

Body:
I used this for my client:

$clientIpArray = explode(".", $clientIp);
$fromArray = explode(".", $from);
$toArray = explode(".", $to);

if( ((str_pad($clientIpArray[0], 3, "0", STR_PAD_LEFT) >= str_pad($fromArray[0], 3, "0", STR_PAD_LEFT)) && (str_pad($clientIpArray[0], 3, "0", STR_PAD_LEFT) <= str_pad($toArray[0], 3, "0", STR_PAD_LEFT)))
 &&((str_pad($clientIpArray[1], 3, "0", STR_PAD_LEFT) >= str_pad($fromArray[1], 3, "0", STR_PAD_LEFT)) && (str_pad($clientIpArray[1], 3, "0", STR_PAD_LEFT) <= str_pad($toArray[1], 3, "0", STR_PAD_LEFT)))
 &&((str_pad($clientIpArray[2], 3, "0", STR_PAD_LEFT) >= str_pad($fromArray[2], 3, "0", STR_PAD_LEFT)) && (str_pad($clientIpArray[2], 3, "0", STR_PAD_LEFT) <= str_pad($toArray[2], 3, "0", STR_PAD_LEFT)))
 &&((str_pad($clientIpArray[3], 3, "0", STR_PAD_LEFT) >= str_pad($fromArray[3], 3, "0", STR_PAD_LEFT)) && (str_pad($clientIpArray[3], 3, "0", STR_PAD_LEFT) <= str_pad($toArray[3], 3, "0", STR_PAD_LEFT)))){
  echo "IP within range";
}

For example, let's take this example:

$clientIp = "120.02.3.112";
$from = "1.02.1.112";
$to = "120.02.20.112";

As you can understand this IP is within the range. If you try to compare it as it is it won't work.
My solution is to divide the IP into elements, so for example the generated arrays would be:

$clientIpArray = ["120","02","3","112"];
$fromArray = ["1","02","1","112"];
$toArray = ["120","02","20","112"];

We have 4 elements to compare, here I used str_pad function to generate a 3 characters string from each element, so instead of checking if "3" is between "1" and "20" (which is not true) we will check if "003" is between "001" and "020" (which is correct).


问:
How to convert SQLite Blob field to string with Python
I want to open the Chrome (Login Data) file and use its password field. But this field is stored in byte/blob mode and can not be converted to text.

I also tried codecs and pickle and bytes.encode and str.decode but it didn't work.
Please look at the code below and help :

```<code>import sqlite3

connection_obj = sqlite3.connect('C:/Users/{username}/AppData/Local/Google/Chrome/User
Data/Default/Login Data')

cursor_obj = connection_obj.cursor()

statement = '''SELECT action_url, username_value, password_value  FROM logins'''

cursor_obj.execute(statement)

output = cursor_obj.fetchmany(5)

for url,usr,psw in output:
     # convert psw blob -> ascii text
     # ....
     # ....
     # for example psw filed:
     # b'v10\x7f\xa3\x1a\xd1\x83g\x8c\xc4\x14]\xb6n\xf85\xba\xca\xf5r\x17\xb6D\xed\xf5\x11rM\xbe\xbf\xb1\xc2y\xc5Vr\xc3\xb3NB\xc7J\x14\x95'
     #
     # convert to below text :
     # zarfilm-136342

   print(url, usr, psw,sep='------')
   print('*'*10)

connection_obj.commit()
connection_obj.close()
</code>```

答:
That data is encrypted in AES, and further the key is encrypted with CryptProtectData to lock the encryption key to user data.  You can decrypt the data with something like this:</p>
```<code>import base64, json, os, sqlite3, win32crypt
from Crypto.Cipher import AES

def chrome_key():
    local_state_fn = os.path.join(os.environ["USERPROFILE"],"AppData","Local","Google","Chrome","User Data","Local State")
    with open(local_state_fn, "r") as f:
        local_state = json.load(f)
    key = base64.b64decode(local_state["os_crypt"]["encrypted_key"])
    key = key[5:]
    return win32crypt.CryptUnprotectData(key, None, None, None, 0)[1]

def decrypt_password(password, key):
    iv, password = password[3:15], password[15:]
    aes = AES.new(key, AES.MODE_GCM, iv)
    return aes.decrypt(password)[:-16].decode("utf-8")

def main():
    key = chrome_key()
    db_fn = os.path.join(os.environ["USERPROFILE"],"AppData","Local","Google","Chrome","User Data","default","Login Data")
    db = sqlite3.connect(db_fn)
    for origin_url, username, password_crypt in db.execute("SELECT origin_url, username_value, password_value FROM logins;"):
        password = decrypt_password(password_crypt, key)
        print(f"{origin_url}, {username}, {password}")
    db.close()

if __name__ == "__main__":
    main()
</code>```

Body:
I want to open the Chrome (Login Data) file and use its password field. But this field is stored in byte/blob mode and can not be converted to text.

I also tried codecs and pickle and bytes.encode and str.decode but it didn't work.
Please look at the code below and help :

import sqlite3

connection_obj = sqlite3.connect('C:/Users/{username}/AppData/Local/Google/Chrome/User
Data/Default/Login Data')

cursor_obj = connection_obj.cursor()

statement = '''SELECT action_url, username_value, password_value  FROM logins'''

cursor_obj.execute(statement)

output = cursor_obj.fetchmany(5)

for url,usr,psw in output:
     # convert psw blob -> ascii text
     # ....
     # ....
     # for example psw filed:
     # b'v10\x7f\xa3\x1a\xd1\x83g\x8c\xc4\x14]\xb6n\xf85\xba\xca\xf5r\x17\xb6D\xed\xf5\x11rM\xbe\xbf\xb1\xc2y\xc5Vr\xc3\xb3NB\xc7J\x14\x95'
     #
     # convert to below text :
     # zarfilm-136342

   print(url, usr, psw,sep='------')
   print('*'*10)

connection_obj.commit()
connection_obj.close()

Body:
That data is encrypted in AES, and further the key is encrypted with CryptProtectData to lock the encryption key to user data.  You can decrypt the data with something like this:

import base64, json, os, sqlite3, win32crypt
from Crypto.Cipher import AES

def chrome_key():
    local_state_fn = os.path.join(os.environ["USERPROFILE"],"AppData","Local","Google","Chrome","User Data","Local State")
    with open(local_state_fn, "r") as f:
        local_state = json.load(f)
    key = base64.b64decode(local_state["os_crypt"]["encrypted_key"])
    key = key[5:]
    return win32crypt.CryptUnprotectData(key, None, None, None, 0)[1]

def decrypt_password(password, key):
    iv, password = password[3:15], password[15:]
    aes = AES.new(key, AES.MODE_GCM, iv)
    return aes.decrypt(password)[:-16].decode("utf-8")

def main():
    key = chrome_key()
    db_fn = os.path.join(os.environ["USERPROFILE"],"AppData","Local","Google","Chrome","User Data","default","Login Data")
    db = sqlite3.connect(db_fn)
    for origin_url, username, password_crypt in db.execute("SELECT origin_url, username_value, password_value FROM logins;"):
        password = decrypt_password(password_crypt, key)
        print(f"{origin_url}, {username}, {password}")
    db.close()

if __name__ == "__main__":
    main()


问:
Xamarin App Tracking Transparency Dialog does not appear since iOS 15
Since I started building my App for iOS 15 in Xamarin the Dialog with the Tracking Usage Description does not disappear anymore and it does not pass Apple's review.

I tried with my iPhone 12 mini and also with various simulators. Simulators for iOS 14.5 did show the dialog, devices running iOS 15 do not

"Allow Apps to Request to Track" in the settings is activated

Happy for any help.

It was implemented according to the instructions on this page

答:
To resolve this issue On Xamarin.iOS:

Put the "RequestTrackingAuthorization" code
in AppDelegate.cs >> function: OnActivated()
instead of AppDelegate.cs >> function: FinishedLaunching().

The answer provided by "Tran Canh" is correct, where "AppDelegate's applicationDidBecomeActive method" is "AppDelegate.cs >> function: OnActivated()".


问:
Azure Release Pipeline: Can I deploy to multiple servers, each with a different web.config transform applied, with a single stage.?
I have a release pipline, with one artifact and multiple IIS website deployment stages.  I have multiple stages for the sole reason that the web.config transform uses the stage name to transform.  Everything in the stage is exactly the same.

I need to deploy the same web app to 3 different servers.  For each server I need to apply a different web.config transform.

Is there any way to do this in a single stage?

答:
Azure Release Pipeline: Can I deploy to multiple servers, each with a different web.config transform applied, with a single stage.?

Now, Both the Azure App Service Deploy task and IIS Web App Deploy task are support file transforms and variable substitution.

The File Transformation will look for and apply a *.<environment>.config transform file where <environment> matches the Azure Pipeline environment for which the task is executing.

Variable Substitution will apply the value of any pipeline variables to the corresponding connectionStrings or appSettings entries where the name matches the variable name.

Besides, there are also some other tasks can apply transform for config file, so the easy way is that you can include/add the related configure files in release artifact, then configure transform per to release environments.

XDT Transform

Replace Tokens

Tokenization task


问:
Java: Caught exception is immediately rethrown? What's the problem?
I have the following Java code (that I thought was OK) but the IDE is warning me that "IOExcpetion e is immediately rethrown."

I'm new to exception handling in Java, and I wasn't aware there was anything wrong with doing that.

From what I'm reading, it looks like my other options is to simply delete the catch block and replace it with a finally block... but then it warns that the finally block is empty.

I don't have any ideas on what I should do differently.

```<code>private InputStream getFlutterAssetAsInputStream(String fromAsset) throws IOException {
    String assetPath = binding
            .getFlutterAssets()
            .getAssetFilePathBySubpath(fromAsset, PACKAGE_NAME);

    try {
      return binding.getApplicationContext().getAssets().open(assetPath);
    } catch (IOException e) {
      throw e;
    }
  }
</code>```

答:
This

```<code>try {
  return binding.getApplicationContext().getAssets().open(assetPath);
}
catch (IOException e) {
  throw e;
}
</code>```

is functionally equivalent to this:

```<code>  return binding.getApplicationContext().getAssets().open(assetPath);
</code>```

Your IDE is telling you that your try-catch is pointless. It does nothing.

So what do you want to do?

Pass the exception on to your caller?  In which case get rid of the try-catch

Signal a different exception on to the caller - maybe one with a more appropriate error message for the specific circumstances?  Then make and throw a new exception object with a better error message.

Do something to handle the situation - at the very least, maybe display an error message?  Log the event to enable debugging? Then write code in the catch-block to do that. And then you have to decide what happens next.

Fundamentally, this is a design issue. IO errors happen. So how does this method that you're writing want to handle IO errors?

Body:
I have the following Java code (that I thought was OK) but the IDE is warning me that "IOExcpetion e is immediately rethrown."

I'm new to exception handling in Java, and I wasn't aware there was anything wrong with doing that.

From what I'm reading, it looks like my other options is to simply delete the catch block and replace it with a finally block... but then it warns that the finally block is empty.

I don't have any ideas on what I should do differently.

private InputStream getFlutterAssetAsInputStream(String fromAsset) throws IOException {
    String assetPath = binding
            .getFlutterAssets()
            .getAssetFilePathBySubpath(fromAsset, PACKAGE_NAME);

    try {
      return binding.getApplicationContext().getAssets().open(assetPath);
    } catch (IOException e) {
      throw e;
    }
  }

Body:
This

try {
  return binding.getApplicationContext().getAssets().open(assetPath);
}
catch (IOException e) {
  throw e;
}

is functionally equivalent to this:

  return binding.getApplicationContext().getAssets().open(assetPath);

Your IDE is telling you that your try-catch is pointless. It does nothing.

So what do you want to do?

Pass the exception on to your caller?  In which case get rid of the try-catch

Signal a different exception on to the caller - maybe one with a more appropriate error message for the specific circumstances?  Then make and throw a new exception object with a better error message.

Do something to handle the situation - at the very least, maybe display an error message?  Log the event to enable debugging? Then write code in the catch-block to do that. And then you have to decide what happens next.

Fundamentally, this is a design issue. IO errors happen. So how does this method that you're writing want to handle IO errors?


问:
In Scala how to access match case value in each case block
I want to access to the case value in the case block</p>
```<code> val a = "hello"
  a match {
    case "hello" | "Hi" =>
      println("hello") // how can I access the right case value? Hello or Hi?
    case _ =>
      print("NA")
  }
</code>```

答:
You can reference the matched value like so:

a match {
    case str @ ("hello" | "Hi") => println(str)
    case _ => print("NA")
}
```

Body:
I want to access to the case value in the case block

 val a = "hello"
  a match {
    case "hello" | "Hi" =>
      println("hello") // how can I access the right case value? Hello or Hi?
    case _ =>
      print("NA")
  }


问:
Can we display Count of Events in a calendar day in Full Calendar
We are using Full Calendar Js and CSS. Requirement is to display the count of events instead of the event description on the calendar day. Is there a way we can do that?</p>

答:
In full Calendar there is a method to get all events in a calendar

calendar.getEvents() -> Array

which returns an array of all events stored in client side memory.

then you simply have to iterate through the array and look for events that overlap your target day.

Here are links to the documentation for the method

https://fullcalendar.io/docs/Calendar-getEvents

https://fullcalendar.io/docs/event-parsing


问:
out border color Flutter
I'm facing the next problem, I have elements in Stack and I want iPhone users see purple color when they scroll up and white when they scroll down

I have the next structure:

```<code>  Widget build(BuildContext context) {
    return Scaffold(
      body: WillPopScope(
        child: ListView(
          children: [
            Container(
              child: Stack(
                children: [
                  ...
                ],
              ),
            ),
          ],
        ),
      ),
    );
</code>```

If I change Scaffold color directly it will change both sides, top and bottom. I want top one to be purple and bottom to be white

答:
By using SliverAppBar, I implemented what you want.

I wonder this is perfect solution for what you want.

You need to implement top layout(title, lead button, image...)

```<code>import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
  }

  List<Widget> bodyItems = [
    SizedBox(height: 50),
    Text(
      'NMR',
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 25,
      ),
    ),
    SizedBox(height: 50),
    Text(
      '+00 000 000 00 00',
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 15,
      ),
    ),
    SizedBox(height: 50),
    Text(
      'Text Text Text',
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 15,
      ),
    ),
    Padding(
      padding: EdgeInsets.symmetric(vertical: 20, horizontal: 100),
      child: LinearProgressIndicator(
        value: 50,
        semanticsLabel: 'Linear progress indicator',
      ),
    ),
    Text(
      'Text Text Text',
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 15,
      ),
    ),
    SizedBox(height: 50),
    Padding(
      padding: EdgeInsets.symmetric(horizontal: 50),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            'Text Text Text',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 12,
            ),
          ),
          Text(
            'Text Text Text',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 12,
            ),
          ),
        ],
      ),
    ),
    SizedBox(height: 400),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.yellow,
      body: CustomScrollView(
        physics: BouncingScrollPhysics(),
        slivers: [
          SliverAppBar(
            expandedHeight: 250,
            collapsedHeight: 250,
            stretch: true,
            backgroundColor: Color(0XFF7861AA),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(50),
                bottomRight: Radius.circular(50),
              ),
            ),
            flexibleSpace: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(
                  height: 20,
                ),
                Text('Title'),
                Icon(
                  Icons.home,
                  color: Colors.blue,
                  size: 160.0,
                ),
              ],
            ),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (_, int index) {
                return bodyItems[index];
              },
              childCount: bodyItems.length,
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

Title: out border color Flutter

Body:
I'm facing the next problem, I have elements in Stack and I want iPhone users see purple color when they scroll up and white when they scroll down

I have the next structure:

  Widget build(BuildContext context) {
    return Scaffold(
      body: WillPopScope(
        child: ListView(
          children: [
            Container(
              child: Stack(
                children: [
                  ...
                ],
              ),
            ),
          ],
        ),
      ),
    );

If I change Scaffold color directly it will change both sides, top and bottom. I want top one to be purple and bottom to be white

Body:
By using SliverAppBar, I implemented what you want.

I wonder this is perfect solution for what you want.

You need to implement top layout(title, lead button, image...)

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
  }

  List<Widget> bodyItems = [
    SizedBox(height: 50),
    Text(
      'NMR',
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 25,
      ),
    ),
    SizedBox(height: 50),
    Text(
      '+00 000 000 00 00',
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 15,
      ),
    ),
    SizedBox(height: 50),
    Text(
      'Text Text Text',
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 15,
      ),
    ),
    Padding(
      padding: EdgeInsets.symmetric(vertical: 20, horizontal: 100),
      child: LinearProgressIndicator(
        value: 50,
        semanticsLabel: 'Linear progress indicator',
      ),
    ),
    Text(
      'Text Text Text',
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 15,
      ),
    ),
    SizedBox(height: 50),
    Padding(
      padding: EdgeInsets.symmetric(horizontal: 50),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            'Text Text Text',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 12,
            ),
          ),
          Text(
            'Text Text Text',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 12,
            ),
          ),
        ],
      ),
    ),
    SizedBox(height: 400),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.yellow,
      body: CustomScrollView(
        physics: BouncingScrollPhysics(),
        slivers: [
          SliverAppBar(
            expandedHeight: 250,
            collapsedHeight: 250,
            stretch: true,
            backgroundColor: Color(0XFF7861AA),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(50),
                bottomRight: Radius.circular(50),
              ),
            ),
            flexibleSpace: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(
                  height: 20,
                ),
                Text('Title'),
                Icon(
                  Icons.home,
                  color: Colors.blue,
                  size: 160.0,
                ),
              ],
            ),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (_, int index) {
                return bodyItems[index];
              },
              childCount: bodyItems.length,
            ),
          ),
        ],
      ),
    );
  }
}


问:
React-Router: No Not Found Route?
Consider the following:

```<code>var AppRoutes = [
    <Route handler={App} someProp="defaultProp">
        <Route path="/" handler={Page} />
    </Route>,

    <Route  handler={App} someProp="defaultProp">
        <Route path="/" handler={Header} >
            <Route path="/withheader" handler={Page} />
        </Route>
    </Route>,

    <Route handler={App} someProp="defaultProp">
        <Route path=":area" handler={Area} />
        <Route path=":area/:city" handler={Area} />
        <Route path=":area/:city/:locale" handler={Area} />
        <Route path=":area/:city/:locale/:type" handler={Area} />
    </Route>
];
</code>```

I have an App Template, a HeaderTemplate, and Parameterized set of routes with the same handler (within App template).  I want to be able to serve 404 routes when something is not found.  For example, /CA/SanFrancisco should be found and handled by Area, whereas /SanFranciscoz should 404.

Here's how I quickly test the routes.

```<code>['', '/', '/withheader', '/SanFranciscoz', '/ca', '/CA', '/CA/SanFrancisco', '/CA/SanFrancisco/LowerHaight', '/CA/SanFrancisco/LowerHaight/condo'].forEach(function(path){
    Router.run(AppRoutes, path, function(Handler, state){
        var output = React.renderToString(<Handler/>);
        console.log(output, '\n');
    });
});
</code>```

The problem is /SanFranciscoz is always being handled by the Area page, but I want it to 404.  Also, if I add a NotFoundRoute to the first route configuration, all the Area pages 404.

```<code><Route handler={App} someProp="defaultProp">
    <Route path="/" handler={Page} />
    <NotFoundRoute handler={NotFound} />
</Route>,
</code>```

What am I doing wrong?

Here's a gist that can be downloaded and experimented on.

https://gist.github.com/adjavaherian/aa48e78279acddc25315

答:
I had similar issue, instead of using * wild identifier or Default Switch Component. We can simply just use Route Component without defining path.

example:

```<code><Switch>
      <Route path="/" component={Root} />
      <Route path="/home" component={Home} />
      <Route component={NotFoundPage} />
// Default Component To load If none  of the path matches.
</Switch>
</code>```

Title: React-Router: No Not Found Route?

Body:
Consider the following:

var AppRoutes = [
    <Route handler={App} someProp="defaultProp">
        <Route path="/" handler={Page} />
    </Route>,

    <Route  handler={App} someProp="defaultProp">
        <Route path="/" handler={Header} >
            <Route path="/withheader" handler={Page} />
        </Route>
    </Route>,

    <Route handler={App} someProp="defaultProp">
        <Route path=":area" handler={Area} />
        <Route path=":area/:city" handler={Area} />
        <Route path=":area/:city/:locale" handler={Area} />
        <Route path=":area/:city/:locale/:type" handler={Area} />
    </Route>
];

I have an App Template, a HeaderTemplate, and Parameterized set of routes with the same handler (within App template).  I want to be able to serve 404 routes when something is not found.  For example, /CA/SanFrancisco should be found and handled by Area, whereas /SanFranciscoz should 404.

Here's how I quickly test the routes.

['', '/', '/withheader', '/SanFranciscoz', '/ca', '/CA', '/CA/SanFrancisco', '/CA/SanFrancisco/LowerHaight', '/CA/SanFrancisco/LowerHaight/condo'].forEach(function(path){
    Router.run(AppRoutes, path, function(Handler, state){
        var output = React.renderToString(<Handler/>);
        console.log(output, '\n');
    });
});

The problem is /SanFranciscoz is always being handled by the Area page, but I want it to 404.  Also, if I add a NotFoundRoute to the first route configuration, all the Area pages 404.

<Route handler={App} someProp="defaultProp">
    <Route path="/" handler={Page} />
    <NotFoundRoute handler={NotFound} />
</Route>,

What am I doing wrong?

Here's a gist that can be downloaded and experimented on.

https://gist.github.com/adjavaherian/aa48e78279acddc25315

Body:
I had similar issue, instead of using * wild identifier or Default Switch Component. We can simply just use Route Component without defining path.

example:

<Switch>
      <Route path="/" component={Root} />
      <Route path="/home" component={Home} />
      <Route component={NotFoundPage} />
// Default Component To load If none  of the path matches.
</Switch>


问:
Why is item not adding to dictionary in Python
This code

```<code>def process_hero_box_annotations(post_to_boxes):
  for box in post_to_boxes:
    k = box
    a = post_to_boxes.get(box)
    new = ()
    post_to_processed_box = {}
    if len(a) != 0:
      x0 = a[0][0]
      y0 = a[0][1]
      x1 = a[0][2]
      y1 = a[0][3]
      if len(a) == 2:
        if a[0][0] < a[1][0]:
          x0 = a[0][0]
        else:
          x0 = a[1][0]
        if a[0][1] < a[1][1]:
          y0 = a[0][1]
        else:
          y0 = a[1][1]
        if a[0][2] > a[1][2]:
          x1 = a[0][2]
        else:
          x1 = a[1][2]
        if a[0][3] > a[1][3]:
          y1 = a[0][3]
        else:
          y1 = a[1][3]
      new = (x0, y0, x1, y1)
      print(new)
      post_to_processed_box[k] = new
  return post_to_processed_box
</code>```

gives me

```<code>{
    384121: (10, 20, 100, 300)
}
</code>```

when I want

```<code>{
    149321: (14, 10, 503, 545),
    384121: (10, 20, 100, 300)
}
</code>```

Why is one item not adding?

答:
@Jadon's answer definitely solves your problem.

I want to offer this as another way of thinking of the problem of getting a "hero box" (a union of two rectangles):

It uses some different logic, which I think might be easier to follow as it avoids nested if-blocks.

I chose to use the min() and max() functions to find the minimums and maximums for X and Y.

I'm also using the items() method on the dict of boxes passed in, to get both the key and value/object in one statement.

import pprint

def union(box_a, box_b):
    '''Return a box that both minimally & fully covers box_a and box_b.
    A box is a 4-part tuple: (minX, minY, maxX, maxY)
    '''

    min_x = min(box_a[0], box_b[0])
    min_y = min(box_a[1], box_b[1])
    max_x = max(box_a[2], box_b[2])
    max_y = max(box_a[3], box_b[3])

    return (min_x, min_y, max_x, max_y)

def process_hero_box_annotations(post_to_boxes):
    post_to_processed_box = {}

    for key, boxes in post_to_boxes.items():

        if len(boxes) > 2:
            raise ValueError(f'Expected 0, 1, or 2 boxes, got {len(boxes)} boxes')

        if len(boxes) == 0:
            post_to_processed_box[key] = ()
            continue  # move on to the next set of key/boxes, if there is one

        box_a = boxes[0]
        hero_box = (box_a[0], box_a[1], box_a[2], box_a[3])

        if len(boxes) == 2:
            box_b = boxes[1]
            hero_box = union(box_a, box_b)

        post_to_processed_box[key] = hero_box

    return post_to_processed_box
```
<p>I mocked up some input that should produce the expected output you shared:</p>
<pre class="lang-py prettyprint-override"><code>boxes = {
    149321: [(14, 10, 500, 500), (20, 20, 503, 545)],
    384121: [(10, 20, 100, 300), (50, 50, 90, 250)]
}
</code>```

When I run it , I get your expected result:

hero_boxes = process_hero_box_annotations(boxes)

expected = {
    149321: (14, 10, 503, 545),
    384121: (10, 20, 100, 300)
}

assert hero_boxes == expected

pprint.pprint(hero_boxes, width=30)
```
<pre class="lang-py prettyprint-override"><code>{149321: (14, 10, 503, 545),
 384121: (10, 20, 100, 300)}
</code>```

Body:
This code

def process_hero_box_annotations(post_to_boxes):
  for box in post_to_boxes:
    k = box
    a = post_to_boxes.get(box)
    new = ()
    post_to_processed_box = {}
    if len(a) != 0:
      x0 = a[0][0]
      y0 = a[0][1]
      x1 = a[0][2]
      y1 = a[0][3]
      if len(a) == 2:
        if a[0][0] < a[1][0]:
          x0 = a[0][0]
        else:
          x0 = a[1][0]
        if a[0][1]  a[1][2]:
          x1 = a[0][2]
        else:
          x1 = a[1][2]
        if a[0][3] > a[1][3]:
          y1 = a[0][3]
        else:
          y1 = a[1][3]
      new = (x0, y0, x1, y1)
      print(new)
      post_to_processed_box[k] = new
  return post_to_processed_box

gives me

{
    384121: (10, 20, 100, 300)
}

when I want

{
    149321: (14, 10, 503, 545),
    384121: (10, 20, 100, 300)
}

Why is one item not adding?

Body:
@Jadon's answer definitely solves your problem.

I want to offer this as another way of thinking of the problem of getting a "hero box" (a union of two rectangles):

It uses some different logic, which I think might be easier to follow as it avoids nested if-blocks.

I chose to use the min() and max() functions to find the minimums and maximums for X and Y.

I'm also using the items() method on the dict of boxes passed in, to get both the key and value/object in one statement.

import pprint

def union(box_a, box_b):
    '''Return a box that both minimally & fully covers box_a and box_b.
    A box is a 4-part tuple: (minX, minY, maxX, maxY)
    '''

    min_x = min(box_a[0], box_b[0])
    min_y = min(box_a[1], box_b[1])
    max_x = max(box_a[2], box_b[2])
    max_y = max(box_a[3], box_b[3])

    return (min_x, min_y, max_x, max_y)

def process_hero_box_annotations(post_to_boxes):
    post_to_processed_box = {}

    for key, boxes in post_to_boxes.items():

        if len(boxes) > 2:
            raise ValueError(f'Expected 0, 1, or 2 boxes, got {len(boxes)} boxes')

        if len(boxes) == 0:
            post_to_processed_box[key] = ()
            continue  # move on to the next set of key/boxes, if there is one

        box_a = boxes[0]
        hero_box = (box_a[0], box_a[1], box_a[2], box_a[3])

        if len(boxes) == 2:
            box_b = boxes[1]
            hero_box = union(box_a, box_b)

        post_to_processed_box[key] = hero_box

    return post_to_processed_box

I mocked up some input that should produce the expected output you shared:

boxes = {
    149321: [(14, 10, 500, 500), (20, 20, 503, 545)],
    384121: [(10, 20, 100, 300), (50, 50, 90, 250)]
}

When I run it , I get your expected result:

hero_boxes = process_hero_box_annotations(boxes)

expected = {
    149321: (14, 10, 503, 545),
    384121: (10, 20, 100, 300)
}

assert hero_boxes == expected

pprint.pprint(hero_boxes, width=30)

{149321: (14, 10, 503, 545),
 384121: (10, 20, 100, 300)}


问:
Python - How to access elements in a list of lists to get empty values
I'm reading in a csv file and need to parse it. I want to have a validation check that makes sure no cell/value in the file has any empty values. My problem is that I don't know how to check each element in a list in a list of lists

In essence, I have a sample file with headers STATE, COST, and ID

```<code>VA,2000,1
CA,1
NY,3784,1
</code>```

When parsing, I want a check that would throw an error on the second line since it's missing a value for the COST field.

Here is my code on how i'm approaching it:

```<code>with open('<hidden path url>', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    all_values = [line for line in csv_reader]
    headers = all_values[0]
    allocations = all_values[1:]

# Check for empty values
    if any(line == (None or '') for line in all_values):
        print("No column value can be empty")
    else:
        print("Success!")
</code>```

This is the result of print(all_values), aka the list of lists from which i'm trying to check each element for

```<code>[['state', 'cost', 'id'], ['VA', '2000' , '1'], ['CA', '', '1'], ['NY', '3784' , '1']]
</code>```

Going through the check should print "No column values can be empty" since there is an empty value in the row ['CA', '', '1']. I also don't want to define any extra function for the check.

Any help would be greatly appreciated!

答:
An error in your code is that line == (None or '') is not valid to check whether its none or ''. It should instead be something like this:</p>
```<code>if any(line == None or line == '' for line in all_values):
    print("No column value can be empty")
else:
    print("Success!")
</code>```

Body:
I'm reading in a csv file and need to parse it. I want to have a validation check that makes sure no cell/value in the file has any empty values. My problem is that I don't know how to check each element in a list in a list of lists

In essence, I have a sample file with headers STATE, COST, and ID

VA,2000,1
CA,1
NY,3784,1

When parsing, I want a check that would throw an error on the second line since it's missing a value for the COST field.

Here is my code on how i'm approaching it:

with open('<hidden path url>', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    all_values = [line for line in csv_reader]
    headers = all_values[0]
    allocations = all_values[1:]

# Check for empty values
    if any(line == (None or '') for line in all_values):
        print("No column value can be empty")
    else:
        print("Success!")

This is the result of print(all_values), aka the list of lists from which i'm trying to check each element for

[['state', 'cost', 'id'], ['VA', '2000' , '1'], ['CA', '', '1'], ['NY', '3784' , '1']]

Going through the check should print "No column values can be empty" since there is an empty value in the row ['CA', '', '1']. I also don't want to define any extra function for the check.

Any help would be greatly appreciated!

Body:
An error in your code is that line == (None or '') is not valid to check whether its none or ''. It should instead be something like this:

if any(line == None or line == '' for line in all_values):
    print("No column value can be empty")
else:
    print("Success!")


问:
Java -- The return type of a function is "String" but it can return both String and int data types
```<code>class Student {
    String name;
    int age;

    public void setInfo(String n, int a) {
        this.name = n;
        this.age = a;
    }

    public String getInfo() { // Notice the "String" data type in this function
        return (this.name + " " + this.age);  // "this.age" is a "int" data type but the function is supposed to be returning only "String" data type, right?
    }
}

public class OOPS {
    public static void main(String args[]) {
        Student s1 = new Student();

        s1.setInfo("John", 24);
        System.out.println(s1.getInfo());
    }
}
</code>```

Here is the output: Click me to see the output

The next thing I tried to do was replace "String" with "int" in the function.

Like this:

```<code>public int getInfo() {
     return (this.name + " " + this.age);
}
</code>```

It throws this error: Click me to see the error

The question is why is it so?

答:
The string concatenation in your code:

```<code>return ( this.name + " " + this.age );
</code>```

… implicitly generates a string from your int member field, this.age.

That is equivalent to a call to String.valueof:

```<code>return ( this.name + " " + String.valueOf( this.age ) );
</code>```

See Converting Numbers to Strings in the Java Tutorials provided by Oracle free of cost.

Body:
class Student {
    String name;
    int age;

    public void setInfo(String n, int a) {
        this.name = n;
        this.age = a;
    }

    public String getInfo() { // Notice the "String" data type in this function
        return (this.name + " " + this.age);  // "this.age" is a "int" data type but the function is supposed to be returning only "String" data type, right?
    }
}

public class OOPS {
    public static void main(String args[]) {
        Student s1 = new Student();

        s1.setInfo("John", 24);
        System.out.println(s1.getInfo());
    }
}

Here is the output: Click me to see the output

The next thing I tried to do was replace "String" with "int" in the function.

Like this:

public int getInfo() {
     return (this.name + " " + this.age);
}

It throws this error: Click me to see the error

The question is why is it so?

Body:
The string concatenation in your code:

return ( this.name + " " + this.age );

… implicitly generates a string from your int member field, this.age.

That is equivalent to a call to String.valueof:

return ( this.name + " " + String.valueOf( this.age ) );

See Converting Numbers to Strings in the Java Tutorials provided by Oracle free of cost.


问:
Pytorch mixed precision causing discriminator loss to go to NaN in WGAN-GP
I'm going to preface this by saying I don't have a lot of experience with neural networks - less so with Pytorch in general. I'm trying to implement mixed precision in a WGAN-GP implementation (not mine) so that I can save GPU memory and train a bit faster.

I got the code from here, but I made my own Generator/Discriminator models, which I will put at the bottom.

The training loop looks as follows:

scaler1 = torch.cuda.amp.GradScaler()
scaler2 = torch.cuda.amp.GradScaler()

for epoch in range(EPOCHS):
    # Target labels not needed! <3 unsupervised
    for batch_idx, (real, _) in enumerate(loader):
        real = real.to(device)
        cur_batch_size = real.shape[0]

        with torch.cuda.amp.autocast():
            noise = torch.randn(cur_batch_size, LATENT_SIZE, 1, 1).to(device)
            fake = gen(noise)
            critic_real = critic(real).reshape(-1)
            critic_fake = critic(fake).reshape(-1)
            gp = gradient_penalty(critic, real, fake, device=device, scaler = scaler1)
            loss_critic = (
                -(torch.mean(critic_real) - torch.mean(critic_fake)) + LAMBDA_GP * gp
            )
        critic.zero_grad()
        #loss_critic.backward(retain_graph=True)
        #opt_critic.step()
        scaler1.scale(loss_critic).backward(retain_graph = True)
        scaler1.unscale_(opt_critic)
        scaler1.step(opt_critic)

        # Train Generator: max E[critic(gen_fake)] <-> min -E[critic(gen_fake)]

        with torch.cuda.amp.autocast():
            gen_fake = critic(fake).reshape(-1)
            loss_gen = -torch.mean(gen_fake)

        gen.zero_grad()
        #loss_gen.backward()
        #opt_gen.step()

        scaler2.scale(loss_gen).backward(retain_graph = True)
        scaler2.unscale_(opt_gen)
        scaler2.step(opt_gen)

        scaler1.update()
        scaler2.update()

```
<p>And the gradient penalty function:</p>
<pre class="lang-py prettyprint-override"><code>
def gradient_penalty(critic, real, fake, device="cpu", scaler = None):
    BATCH_SIZE, C, H, W = real.shape
    alpha = torch.rand((BATCH_SIZE, 1, 1, 1)).repeat(1, C, H, W).to(device)
    interpolated_images = real * alpha + fake * (1 - alpha)

    # Calculate critic scores
    mixed_scores = critic(interpolated_images)

    # Take the gradient of the scores with respect to the images
    gradient = torch.autograd.grad(
        inputs=interpolated_images,
        outputs=mixed_scores if scaler is None else scaler.scale(mixed_scores),
        grad_outputs=torch.ones_like(mixed_scores),
        create_graph=True,
        retain_graph=True,
    )[0]

    gradient = gradient / scaler.get_scale() if scaler is not None else gradient

    gradient = gradient.view(gradient.shape[0], -1)
    gradient_norm = gradient.norm(2, dim=1)
    gradient_penalty = torch.mean((gradient_norm - 1) ** 2)
    return gradient_penalty
</code>```

I've tested this without mixed precision, and it seems to do well enough, but after I tried to implement mixed precision, the discriminator loss becomes NaN after a few batches. The generator loss appears to be normal (however it starts out negative, which I'm not sure is OK but it becomes positive later when not using mixed precision).

The following are my Generator and Discriminator models:

class Generator(nn.Module):
    def __init__(self, targetSize, channels, features, latentSize):
        super(Generator, self).__init__()

        mult = int(np.log(targetSize)/np.log(2) - 3)
        startFactor = 2**mult

        self.network = nn.Sequential(
            nn.ConvTranspose2d(latentSize, features * startFactor, 4, 1, 0, bias = False),
            nn.BatchNorm2d(features * startFactor),
            nn.LeakyReLU(0.2),
            *sum([self.__block(int(features * startFactor / (2**i)), int(features * startFactor / (2**(i+1)))) for i in range(mult)], []),
            nn.ConvTranspose2d(features, channels, 4, 2, 1, bias = False),
            nn.Tanh(),
            )

    def __block(self, in_features, out_features):
        layers = [nn.ConvTranspose2d(in_features, out_features, 4, 2, 1, bias = False)]
        layers.append(nn.BatchNorm2d(out_features))
        layers.append(nn.LeakyReLU(0.2))
        return layers

    def forward(self, inp):
        return self.network(inp)

class Discriminator(nn.Module):
    def __init__(self, targetSize, channels, features):
        super(Discriminator, self).__init__()

        mult = int(np.log(targetSize)/np.log(2) - 3)
        startFactor = 2**mult

        self.network = nn.Sequential(

            nn.Conv2d(channels, features, 4, 2, 1, bias = False),
            nn.LeakyReLU(0.2),
            *sum([self.__block(int(features * (2**i)), int(features * (2**(i+1)))) for i in range(mult)],[]),
            nn.Conv2d(features * startFactor, 1, 4, 2, 0, bias = False),
            )

    def __block(self, in_features, out_features):
        layers = [nn.Conv2d(in_features, out_features, 4, 2, 1, bias = False)]
        layers.append(nn.InstanceNorm2d(out_features, affine=True))
        layers.append(nn.LeakyReLU(0.2))
        return layers

    def forward(self, inp):
        return self.network(inp)

```

NOTE: The FP16 chart ends on step ~140 because it becomes NaN from that point onwards.

I've also created pastebins for the raw data: FP32 and FP16

答:
I've been struggling with this for a week and am not sure whether I've fully solved it yet, but at least it's running stable now.

Move the gradient_penalty() function outside of with autocast. Only the normalization portion should be within the with autocast. These gradients should be manually scaled.

Here is an example from pytorch: https://pytorch.org/docs/stable/notes/amp_examples.html#gradient-penalty

Body:
I'm going to preface this by saying I don't have a lot of experience with neural networks - less so with Pytorch in general. I'm trying to implement mixed precision in a WGAN-GP implementation (not mine) so that I can save GPU memory and train a bit faster.

I got the code from here, but I made my own Generator/Discriminator models, which I will put at the bottom.

The training loop looks as follows:

scaler1 = torch.cuda.amp.GradScaler()
scaler2 = torch.cuda.amp.GradScaler()

for epoch in range(EPOCHS):
    # Target labels not needed! <3 unsupervised
    for batch_idx, (real, _) in enumerate(loader):
        real = real.to(device)
        cur_batch_size = real.shape[0]

        with torch.cuda.amp.autocast():
            noise = torch.randn(cur_batch_size, LATENT_SIZE, 1, 1).to(device)
            fake = gen(noise)
            critic_real = critic(real).reshape(-1)
            critic_fake = critic(fake).reshape(-1)
            gp = gradient_penalty(critic, real, fake, device=device, scaler = scaler1)
            loss_critic = (
                -(torch.mean(critic_real) - torch.mean(critic_fake)) + LAMBDA_GP * gp
            )
        critic.zero_grad()
        #loss_critic.backward(retain_graph=True)
        #opt_critic.step()
        scaler1.scale(loss_critic).backward(retain_graph = True)
        scaler1.unscale_(opt_critic)
        scaler1.step(opt_critic)

        # Train Generator: max E[critic(gen_fake)] <-> min -E[critic(gen_fake)]

        with torch.cuda.amp.autocast():
            gen_fake = critic(fake).reshape(-1)
            loss_gen = -torch.mean(gen_fake)

        gen.zero_grad()
        #loss_gen.backward()
        #opt_gen.step()

        scaler2.scale(loss_gen).backward(retain_graph = True)
        scaler2.unscale_(opt_gen)
        scaler2.step(opt_gen)

        scaler1.update()
        scaler2.update()

And the gradient penalty function:

def gradient_penalty(critic, real, fake, device="cpu", scaler = None):
    BATCH_SIZE, C, H, W = real.shape
    alpha = torch.rand((BATCH_SIZE, 1, 1, 1)).repeat(1, C, H, W).to(device)
    interpolated_images = real * alpha + fake * (1 - alpha)

    # Calculate critic scores
    mixed_scores = critic(interpolated_images)

    # Take the gradient of the scores with respect to the images
    gradient = torch.autograd.grad(
        inputs=interpolated_images,
        outputs=mixed_scores if scaler is None else scaler.scale(mixed_scores),
        grad_outputs=torch.ones_like(mixed_scores),
        create_graph=True,
        retain_graph=True,
    )[0]

    gradient = gradient / scaler.get_scale() if scaler is not None else gradient

    gradient = gradient.view(gradient.shape[0], -1)
    gradient_norm = gradient.norm(2, dim=1)
    gradient_penalty = torch.mean((gradient_norm - 1) ** 2)
    return gradient_penalty

I've tested this without mixed precision, and it seems to do well enough, but after I tried to implement mixed precision, the discriminator loss becomes NaN after a few batches. The generator loss appears to be normal (however it starts out negative, which I'm not sure is OK but it becomes positive later when not using mixed precision).

The following are my Generator and Discriminator models:

class Generator(nn.Module):
    def __init__(self, targetSize, channels, features, latentSize):
        super(Generator, self).__init__()

        mult = int(np.log(targetSize)/np.log(2) - 3)
        startFactor = 2**mult

        self.network = nn.Sequential(
            nn.ConvTranspose2d(latentSize, features * startFactor, 4, 1, 0, bias = False),
            nn.BatchNorm2d(features * startFactor),
            nn.LeakyReLU(0.2),
            *sum([self.__block(int(features * startFactor / (2**i)), int(features * startFactor / (2**(i+1)))) for i in range(mult)], []),
            nn.ConvTranspose2d(features, channels, 4, 2, 1, bias = False),
            nn.Tanh(),
            )

    def __block(self, in_features, out_features):
        layers = [nn.ConvTranspose2d(in_features, out_features, 4, 2, 1, bias = False)]
        layers.append(nn.BatchNorm2d(out_features))
        layers.append(nn.LeakyReLU(0.2))
        return layers

    def forward(self, inp):
        return self.network(inp)

class Discriminator(nn.Module):
    def __init__(self, targetSize, channels, features):
        super(Discriminator, self).__init__()

        mult = int(np.log(targetSize)/np.log(2) - 3)
        startFactor = 2**mult

        self.network = nn.Sequential(

            nn.Conv2d(channels, features, 4, 2, 1, bias = False),
            nn.LeakyReLU(0.2),
            *sum([self.__block(int(features * (2**i)), int(features * (2**(i+1)))) for i in range(mult)],[]),
            nn.Conv2d(features * startFactor, 1, 4, 2, 0, bias = False),
            )

    def __block(self, in_features, out_features):
        layers = [nn.Conv2d(in_features, out_features, 4, 2, 1, bias = False)]
        layers.append(nn.InstanceNorm2d(out_features, affine=True))
        layers.append(nn.LeakyReLU(0.2))
        return layers

    def forward(self, inp):
        return self.network(inp)

NOTE: The FP16 chart ends on step ~140 because it becomes NaN from that point onwards.

I've also created pastebins for the raw data: FP32 and FP16


问:
Android Emulator issues in new versions - The emulator process has terminated
After updating to Android Studio 2020.3.1 canary 15, when I try to run an emulator, it gets killed with this error:

The emulator process for AVD Pixel_4_API_30 has terminated.

It was working correctly in the previous version (4.1.3), but now after installing the new one, it shows the same error.

I've tried some solutions had suggested in almost similar cases; however, It still doesn't work.

I deleted my emulator (also I cleared inside of directory: /.android/avd/) and created a new one again

I updated the HAXM installer to version 7.6.5

I tried to run an emulator with lower APIs but...

Image of the error:

答:
I had this issue, running Android Studio Bumblebee 2021.1.1 on Ubuntu 20.04.3 LTS.

Issue in my case was a mismatch between NVideo kernel module and NVideo client libraries, as noted from dmesg output (these log entries appeared each time an AVD was restarted and failed):

```<code>NVRM: API mismatch: the client has the version 470.103.01, but
NVRM: this kernel module has the version 470.86.  Please
NVRM: make sure that this kernel module and all NVIDIA driver
NVRM: components have the same version.
</code>```

Solution in my case was to upgrade the NVidia drivers to package nvidia-driver-510 using the Additional Drivers dialog of Ubuntu.  Then reboot.

Body:
I had this issue, running Android Studio Bumblebee 2021.1.1 on Ubuntu 20.04.3 LTS.

Issue in my case was a mismatch between NVideo kernel module and NVideo client libraries, as noted from dmesg output (these log entries appeared each time an AVD was restarted and failed):

NVRM: API mismatch: the client has the version 470.103.01, but
NVRM: this kernel module has the version 470.86.  Please
NVRM: make sure that this kernel module and all NVIDIA driver
NVRM: components have the same version.

Solution in my case was to upgrade the NVidia drivers to package nvidia-driver-510 using the Additional Drivers dialog of Ubuntu.  Then reboot.


问:
How to install .NET 4 Framework in Windows 10
How can I install the .NET 4.0 Framework in Windows 10? .NET 4.6 is already installed but I want to have .NET 4 Framework (without modifying the registry).

Turning on and off Windows features in control panel does not have any effect.

答:
I have experienced, I have to open and work with an old project that is required .Net 4.0 to build (they're related to some old libraries) and can not be updated to new .Net version.

I did try to uninstall the current .Net version (4.6, 4.8) and to install .Net 4.0 standalone (dotNetFx40_Full_x86_x64.exe) but it doesn't work.
And I finally decided to install the old Visual Studio (2019) with only some basic features that I manually checked to be lightweight, it works well now.


问:
MVVM ListView not updating despite Itemsource modification | XAMARIN FORMS, ANDROID
I would like to create an android Bluetooth scanner. But I can't manage to display anything using a listview. I've tried debugging it for an extended amount of time without success. It seems like the problem doesn't come from the Bluetooth segments. But rather comes from a refreshing/binding issue.

I'm debugging on a physical Android device, the permissions stuff should be ok since the devices list is updating but the linked list view isn't.

It might be worth mentioning that I've started from the visual studio 2019 Xamarin flyout template. Which, uses an app shell to navigate between the pages. I feel like the problem could also come from this since the app shell might mess with the view models links.

P.S: I am relatively new to MVVM.

Any help would be appreciated !!

I have the following code :

ItemPage (.XAML)

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="clavier.Views.ItemsPage"
                 Title="Devices"
                 x:Name="BrowseItemsPage">

        <ContentPage.Content>
            <StackLayout>
                <Button Text="Search" Command="{Binding SearchDeviceCommand}"/>
                <ListView x:Name="DevicesList"
                          ItemsSource="{Binding list, Mode=OneWay}"
                          IsPullToRefreshEnabled="True"
                          CachingStrategy="RecycleElement">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <StackLayout>
                                    <Label Text="{Binding NativeDevice.Name}"></Label>
                                    <Label Text="{Binding NativeDevice.Address}" ></Label>
                                </StackLayout>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
                <Button Text="End"/>
            </StackLayout>
        </ContentPage.Content>
    </ContentPage>

</code>```

ItemPage code (.XAML.CS)

```<code>namespace clavier.Views
    {
        public partial class ItemsPage : ContentPage
        {
            public ItemsPage()
            {
                BindingContext = new ItemsViewModel();
                InitializeComponent();
            }
        }
    }
</code>```

ViewModel (.CS)

```<code>    ```
    namespace clavier.ViewModels
    {
        public class ItemsViewModel : BaseViewModel
        {
            public IAdapter adapter;
            public IBluetoothLE bluetoothBLE;
            public IDevice SelectedDevice { get; set; }
            public string Title { get; set; }
            public ObservableCollection<IDevice> list { get; set; }
            public Command SearchDeviceCommand { get; }

            public ItemsViewModel()
            {
                bluetoothBLE = CrossBluetoothLE.Current;
                adapter = CrossBluetoothLE.Current.Adapter;
                SearchDeviceCommand = new Command(SearchDevice);
                list = new ObservableCollection<IDevice>();
            }

            public async void SearchDevice()
            {
                if (bluetoothBLE.State == BluetoothState.Off)
                {
                    await Shell.Current.DisplayAlert("Attention", "le bluetooth n'est pas activé.", "OK");
                }
                else
                {
                    list.Clear();
                    adapter.ScanTimeout = 10000;
                    adapter.ScanMode = ScanMode.Balanced;
                    adapter.DeviceDiscovered += (obj, a) =>
                    {
                        if (!list.Contains(a.Device))
                        {
                            list.Add(a.Device);
                        }
                    };
                    await adapter.StartScanningForDevicesAsync();
                }
            }

            public async void DevicesList_OnItemSelected()
            {
                var resullt = await Shell.Current.DisplayAlert("Alerte", "Vous êtes sur le point de vous connecter à cet appareil. Etes vosu sur de vouloir vous connecter ?","Se connecter", "Annuler");

                if (!resullt)
                {
                    return;
                }
                await adapter.StopScanningForDevicesAsync();

                try
                {
                    await adapter.ConnectToDeviceAsync(SelectedDevice);
                    await Shell.Current.DisplayAlert("Connection ...", "Status : " + SelectedDevice.State, "Ok");
                }
                catch (DeviceConnectionException ex)
                {
                    await Shell.Current.DisplayAlert("Erreur !", ex.Message, "Ok");
                }
            }
        }
    }
```
</code>```

My app shell (.XAML)

```<code>```
<?xml version="1.0" encoding="UTF-8"?>
<Shell xmlns="http://xamarin.com/schemas/2014/forms"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       xmlns:local="clr-namespace:clavier.Views"
       Title="clavier"
       x:Class="clavier.AppShell">

    <Shell.Resources>
        <ResourceDictionary>

        </ResourceDictionary>
    </Shell.Resources>

    <FlyoutItem Title="Clavier bluetooth" Icon="icon_about.png">
        <ShellContent Route="AboutPage" ContentTemplate="{DataTemplate local:AboutPage}" />
    </FlyoutItem>
    <FlyoutItem Title="Information" Icon="icon_feed.png">
        <ShellContent Route="ItemsPage" ContentTemplate="{DataTemplate local:ItemsPage}" />
    </FlyoutItem>

    <MenuItem Text="Logout" StyleClass="MenuItemLayoutStyle" Clicked="OnMenuItemClicked">
    </MenuItem>

    <TabBar>
        <ShellContent Route="LoginPage" ContentTemplate="{DataTemplate local:LoginPage}" />
    </TabBar>
</Shell>
```
</code>```

During debugging, I've checked the XAML linker errors but I don't have anything. I've also tried step-by-step debugging and the list is correctly updating with the devices.

I've also tried to add the INotifyProprietyChanged as it was suggested in other answers but nothing changed. (I might have incorrectly used it)

Note: I'm using the plugin BLE nuget, and I've followed the instructions from the Git and from tutorials I've found on the web (this one, and this one).

答:
From source code I see IDevice.NativeDevice is just an object, so maybe it can't recognize NativeDevice.Name in the binding with the Label.Text.

Can you try this code first ?

```<code><ViewCell>
   <StackLayout>
      <Label Text="{Binding Name}"></Label>
      <Label Text="{Binding NativeDevice}" ></Label>
   </StackLayout>
</ViewCell>
</code>```

Body:
I would like to create an android Bluetooth scanner. But I can't manage to display anything using a listview. I've tried debugging it for an extended amount of time without success. It seems like the problem doesn't come from the Bluetooth segments. But rather comes from a refreshing/binding issue.

I'm debugging on a physical Android device, the permissions stuff should be ok since the devices list is updating but the linked list view isn't.

It might be worth mentioning that I've started from the visual studio 2019 Xamarin flyout template. Which, uses an app shell to navigate between the pages. I feel like the problem could also come from this since the app shell might mess with the view models links.

P.S: I am relatively new to MVVM.

Any help would be appreciated !!

I have the following code :

ItemPage (.XAML)

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="clavier.Views.ItemsPage"
                 Title="Devices"
                 x:Name="BrowseItemsPage">

        <ContentPage.Content>
            <StackLayout>
                <Button Text="Search" Command="{Binding SearchDeviceCommand}"/>
                <ListView x:Name="DevicesList"
                          ItemsSource="{Binding list, Mode=OneWay}"
                          IsPullToRefreshEnabled="True"
                          CachingStrategy="RecycleElement">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <StackLayout>

                                </StackLayout>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
                <Button Text="End"/>
            </StackLayout>
        </ContentPage.Content>
    </ContentPage>

ItemPage code (.XAML.CS)

namespace clavier.Views
    {
        public partial class ItemsPage : ContentPage
        {
            public ItemsPage()
            {
                BindingContext = new ItemsViewModel();
                InitializeComponent();
            }
        }
    }

ViewModel (.CS)

    ```
    namespace clavier.ViewModels
    {
        public class ItemsViewModel : BaseViewModel
        {
            public IAdapter adapter;
            public IBluetoothLE bluetoothBLE;
            public IDevice SelectedDevice { get; set; }
            public string Title { get; set; }
            public ObservableCollection<IDevice> list { get; set; }
            public Command SearchDeviceCommand { get; }

            public ItemsViewModel()
            {
                bluetoothBLE = CrossBluetoothLE.Current;
                adapter = CrossBluetoothLE.Current.Adapter;
                SearchDeviceCommand = new Command(SearchDevice);
                list = new ObservableCollection<IDevice>();
            }

            public async void SearchDevice()
            {
                if (bluetoothBLE.State == BluetoothState.Off)
                {
                    await Shell.Current.DisplayAlert("Attention", "le bluetooth n'est pas activé.", "OK");
                }
                else
                {
                    list.Clear();
                    adapter.ScanTimeout = 10000;
                    adapter.ScanMode = ScanMode.Balanced;
                    adapter.DeviceDiscovered += (obj, a) =>
                    {
                        if (!list.Contains(a.Device))
                        {
                            list.Add(a.Device);
                        }
                    };
                    await adapter.StartScanningForDevicesAsync();
                }
            }

            public async void DevicesList_OnItemSelected()
            {
                var resullt = await Shell.Current.DisplayAlert("Alerte", "Vous êtes sur le point de vous connecter à cet appareil. Etes vosu sur de vouloir vous connecter ?","Se connecter", "Annuler");

                if (!resullt)
                {
                    return;
                }
                await adapter.StopScanningForDevicesAsync();

                try
                {
                    await adapter.ConnectToDeviceAsync(SelectedDevice);
                    await Shell.Current.DisplayAlert("Connection ...", "Status : " + SelectedDevice.State, "Ok");
                }
                catch (DeviceConnectionException ex)
                {
                    await Shell.Current.DisplayAlert("Erreur !", ex.Message, "Ok");
                }
            }
        }
    }
```

My app shell (.XAML)

```
<?xml version="1.0" encoding="UTF-8"?>
<Shell xmlns="http://xamarin.com/schemas/2014/forms"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       xmlns:local="clr-namespace:clavier.Views"
       Title="clavier"
       x:Class="clavier.AppShell">

    <Shell.Resources>
        <ResourceDictionary>
            <Style x:Key="BaseStyle" TargetType="Element">
                <Setter Property="Shell.BackgroundColor" Value="{StaticResource Primary}" />
                <Setter Property="Shell.ForegroundColor" Value="White" />
                <Setter Property="Shell.TitleColor" Value="White" />
                <Setter Property="Shell.DisabledColor" Value="#B4FFFFFF" />
                <Setter Property="Shell.UnselectedColor" Value="#95FFFFFF" />
                <Setter Property="Shell.TabBarBackgroundColor" Value="{StaticResource Primary}" />
                <Setter Property="Shell.TabBarForegroundColor" Value="White"/>
                <Setter Property="Shell.TabBarUnselectedColor" Value="#95FFFFFF"/>
                <Setter Property="Shell.TabBarTitleColor" Value="White"/>
            </Style>
            <Style TargetType="TabBar" BasedOn="{StaticResource BaseStyle}" />
            <Style TargetType="FlyoutItem" BasedOn="{StaticResource BaseStyle}" />

            <Style Class="FlyoutItemLabelStyle" TargetType="Label">
                <Setter Property="TextColor" Value="White"></Setter>
            </Style>
            <Style Class="FlyoutItemLayoutStyle" TargetType="Layout" ApplyToDerivedTypes="True">
                <Setter Property="VisualStateManager.VisualStateGroups">
                    <VisualStateGroupList>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal">
                                <VisualState.Setters>
                                    <Setter Property="BackgroundColor" Value="{x:OnPlatform UWP=Transparent, iOS=White}" />
                                    <Setter TargetName="FlyoutItemLabel" Property="Label.TextColor" Value="{StaticResource Primary}" />
                                </VisualState.Setters>
                            </VisualState>
                            <VisualState x:Name="Selected">
                                <VisualState.Setters>
                                    <Setter Property="BackgroundColor" Value="{StaticResource Primary}" />
                                </VisualState.Setters>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateGroupList>
                </Setter>
            </Style>

            <Style Class="MenuItemLayoutStyle" TargetType="Layout" ApplyToDerivedTypes="True">
                <Setter Property="VisualStateManager.VisualStateGroups">
                    <VisualStateGroupList>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal">
                                <VisualState.Setters>
                                    <Setter TargetName="FlyoutItemLabel" Property="Label.TextColor" Value="{StaticResource Primary}" />
                                </VisualState.Setters>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateGroupList>
                </Setter>
            </Style>
        </ResourceDictionary>
    </Shell.Resources>

    <FlyoutItem Title="Clavier bluetooth" Icon="icon_about.png">
        <ShellContent Route="AboutPage" ContentTemplate="{DataTemplate local:AboutPage}" />
    </FlyoutItem>
    <FlyoutItem Title="Information" Icon="icon_feed.png">
        <ShellContent Route="ItemsPage" ContentTemplate="{DataTemplate local:ItemsPage}" />
    </FlyoutItem>

    <MenuItem Text="Logout" StyleClass="MenuItemLayoutStyle" Clicked="OnMenuItemClicked">
    </MenuItem>

    <TabBar>
        <ShellContent Route="LoginPage" ContentTemplate="{DataTemplate local:LoginPage}" />
    </TabBar>
</Shell>
```

During debugging, I've checked the XAML linker errors but I don't have anything. I've also tried step-by-step debugging and the list is correctly updating with the devices.

I've also tried to add the INotifyProprietyChanged as it was suggested in other answers but nothing changed. (I might have incorrectly used it)

Note: I'm using the plugin BLE nuget, and I've followed the instructions from the Git and from tutorials I've found on the web (this one, and this one).

Body:
From source code I see IDevice.NativeDevice is just an object, so maybe it can't recognize NativeDevice.Name in the binding with the Label.Text.

Can you try this code first ?

<ViewCell>
   <StackLayout>
      <Label Text="{Binding Name}"></Label>
      <Label Text="{Binding NativeDevice}" ></Label>
   </StackLayout>
</ViewCell>


问:
Remove Consecutive Duplicates From a Sequence
I am trying to run some code to remove duplicates from a sequence that is within a dataframe. I have approximately 3,000 rows of various sequences. An example of what I am trying to do is have A,B,B,A,D,D,E converted to A,B,A,D,E. I still need to keep the same sequence, just remove the consecutive duplicates.

I have tried zip_longest, and itertools groupby function.

The problem that I have is that there are so many rows, how would I create a for loop for this dataframe so that these functions can iterate through each 'sequence'.

Thanks so much for the help!

答:
Can you try this</p>
```<code>import pandas as pd
df = pd.DataFrame(['A','B','B','A','D','D','E'])

current =''
previous = ''
for index,row in df.iterrows():
    current = row[0]
    if current == previous:
        df.drop(index, inplace=True)
    previous = current

print (df)
</code>```

Body:
Can you try this

import pandas as pd
df = pd.DataFrame(['A','B','B','A','D','D','E'])

current =''
previous = ''
for index,row in df.iterrows():
    current = row[0]
    if current == previous:
        df.drop(index, inplace=True)
    previous = current

print (df)


问:
How to make a button with the name of a file and also call that file?
So I am trying to make a sort of journal program where you can create an entry that is then saved as a text file. I currently have it set up so you can recall an entry by typing in the file name and clicking load, but I want to make a list of buttons on the right side that has all of the file names and then will load the respective file when clicked, any suggestions?

Here is my code:

```<code>from cProfile import label
from cgitb import text
from email.quoprimime import quote
import tkinter as tk
from tkinter import *
from tkinter import ttk
import tkinter
from traceback import print_tb
import os

from pip import main

def open_main():

    #instantiate main screen
    mainscreen = tk.Tk()
    mainscreen.state("zoomed")
    mainscreen.title("Welcome")

    #file name text box
    filename = tk.Entry(mainscreen)
    filename.place(relx=.5, rely=.1, anchor=CENTER)

    #save entry function
    def save_entry():
        savefile = open("%s .txt" % filename.get(), "w+")
        savefile.write(T.get("1.0","end"))
        savefile.close
        refresh()

    #load entry function
    def loadentry():
        loadentry = open("%s .txt" % filename.get(), "r")
        quote = loadentry.readlines()
        T.delete("1.0", END)
        T.insert(END, quote)

    #create frame to place main text box
    mainframe = tkinter.Frame(mainscreen)
    mainframe.place(relwidth=.65, relheight=.75, relx=.05, rely=.5, anchor=W)

    #label the file name text box
    tk.Label(mainscreen, text="Make an Entry:").place(relx=.5, rely=.035, anchor=CENTER)
    tk.Label(mainscreen, text="Date: MMDDYYYY").place(relx=.5, rely=.07, anchor=CENTER)

    #create main text box within the main frame
    S = Scrollbar(mainframe)
    T = Text(mainframe)
    S.pack(side=RIGHT, fill=Y)
    T.pack(side=LEFT, expand=True, fill=BOTH)
    S.config(command=T.yview)
    T.config(yscrollcommand=S.set)

    #create second frame next to main frame to hold buttons
    sideframe = tkinter.Frame(mainscreen)
    sideframe.place(relwidth=.2, relheight=.75, relx=.7, rely=.5, anchor=W)
    side_bar = Scrollbar(sideframe)
    side_box = Text(sideframe)
    side_bar.pack(side=RIGHT, fill=Y)
    side_box.pack(side=LEFT, expand=True, fill=BOTH)

    #create and load buttons
    def loadbutton(item):
        bfilename = item
        bfileentry = open(bfilename, "r")
        bquote = bfileentry.readlines()
        T.delete("1.0",END)
        T.insert(END,bquote)

    #add buttons to box initially
    entry_initate = [f for f in os.listdir(os.getcwd()) if f.endswith('.txt')]

    for item in entry_initate:
        mybutton = Button(side_box, text=item, command = lambda m = item: loadbutton(item))
        mybutton.pack(fill=BOTH)

    #refresh buttons when a new entry is saved
    def refresh():

        entry_raw = [f for f in os.listdir(os.getcwd()) if f.endswith('.txt')]

    for item in entry_raw:
            mybutton = Button(side_box, text=item, command = lambda m = item: loadbutton(item))
            mybutton.pack(fill=BOTH)

    list = side_box.slaves()
    for l in list:
        l.destroy()

    for item in entry_raw:
        mybutton = Button(side_box, text=item, command = lambda m = item: loadbutton(item))
        mybutton.pack(fill=BOTH)

    #Save and load entry buttons
    Button(mainscreen, text="Save Entry", command=save_entry).place(relx=.5, rely=.9, anchor=CENTER)
    Button(mainscreen, text="Load Entry", command=loadentry).place(relx=.5, rely=.95, anchor=CENTER)

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

I currently just have the side box just commented out, it was originally just a text box that had the file names listed in it.

Sorry if its a little messy, im still pretty new to python.

答:
You should use variable loadfileb instead of button_press on .readlines() inside loadbutton().  Also use read() instead of readlines() and you need to insert the read content into text box.

    def loadbutton(button_press):
        with open(button_press, "r") as loadfileb:
            quote = loadfileb.read()
        T.delete('1.0', 'end')
        T.insert('end', quote)

    for item in entry_raw:
        tk.Button(sideframe, text=item, command=lambda m=item: loadbutton(m)).pack()
```
<p>Note that there are different way to initiate widgets, like <code>tk.Entry(...)</code>, <code>tkinter.Frame(...)</code> and <code>Button(...)</code> in your code. So I think you have imported <code>tkinter</code> like below:</p>
```import tkinter
from tkinter import *
import tkinter as tk
```

Recommend to use import tkinter as tk only.

Body:
So I am trying to make a sort of journal program where you can create an entry that is then saved as a text file. I currently have it set up so you can recall an entry by typing in the file name and clicking load, but I want to make a list of buttons on the right side that has all of the file names and then will load the respective file when clicked, any suggestions?

Here is my code:

from cProfile import label
from cgitb import text
from email.quoprimime import quote
import tkinter as tk
from tkinter import *
from tkinter import ttk
import tkinter
from traceback import print_tb
import os

from pip import main

def open_main():

    #instantiate main screen
    mainscreen = tk.Tk()
    mainscreen.state("zoomed")
    mainscreen.title("Welcome")

    #file name text box
    filename = tk.Entry(mainscreen)
    filename.place(relx=.5, rely=.1, anchor=CENTER)

    #save entry function
    def save_entry():
        savefile = open("%s .txt" % filename.get(), "w+")
        savefile.write(T.get("1.0","end"))
        savefile.close
        refresh()

    #load entry function
    def loadentry():
        loadentry = open("%s .txt" % filename.get(), "r")
        quote = loadentry.readlines()
        T.delete("1.0", END)
        T.insert(END, quote)

    #create frame to place main text box
    mainframe = tkinter.Frame(mainscreen)
    mainframe.place(relwidth=.65, relheight=.75, relx=.05, rely=.5, anchor=W)

    #label the file name text box
    tk.Label(mainscreen, text="Make an Entry:").place(relx=.5, rely=.035, anchor=CENTER)
    tk.Label(mainscreen, text="Date: MMDDYYYY").place(relx=.5, rely=.07, anchor=CENTER)

    #create main text box within the main frame
    S = Scrollbar(mainframe)
    T = Text(mainframe)
    S.pack(side=RIGHT, fill=Y)
    T.pack(side=LEFT, expand=True, fill=BOTH)
    S.config(command=T.yview)
    T.config(yscrollcommand=S.set)

    #create second frame next to main frame to hold buttons
    sideframe = tkinter.Frame(mainscreen)
    sideframe.place(relwidth=.2, relheight=.75, relx=.7, rely=.5, anchor=W)
    side_bar = Scrollbar(sideframe)
    side_box = Text(sideframe)
    side_bar.pack(side=RIGHT, fill=Y)
    side_box.pack(side=LEFT, expand=True, fill=BOTH)

    #create and load buttons
    def loadbutton(item):
        bfilename = item
        bfileentry = open(bfilename, "r")
        bquote = bfileentry.readlines()
        T.delete("1.0",END)
        T.insert(END,bquote)

    #add buttons to box initially
    entry_initate = [f for f in os.listdir(os.getcwd()) if f.endswith('.txt')]

    for item in entry_initate:
        mybutton = Button(side_box, text=item, command = lambda m = item: loadbutton(item))
        mybutton.pack(fill=BOTH)

    #refresh buttons when a new entry is saved
    def refresh():

        entry_raw = [f for f in os.listdir(os.getcwd()) if f.endswith('.txt')]

    for item in entry_raw:
            mybutton = Button(side_box, text=item, command = lambda m = item: loadbutton(item))
            mybutton.pack(fill=BOTH)

    list = side_box.slaves()
    for l in list:
        l.destroy()

    for item in entry_raw:
        mybutton = Button(side_box, text=item, command = lambda m = item: loadbutton(item))
        mybutton.pack(fill=BOTH)

    #Save and load entry buttons
    Button(mainscreen, text="Save Entry", command=save_entry).place(relx=.5, rely=.9, anchor=CENTER)
    Button(mainscreen, text="Load Entry", command=loadentry).place(relx=.5, rely=.95, anchor=CENTER)

mainscreen.mainloop()

I currently just have the side box just commented out, it was originally just a text box that had the file names listed in it.

Sorry if its a little messy, im still pretty new to python.

Body:
You should use variable loadfileb instead of button_press on .readlines() inside loadbutton().  Also use read() instead of readlines() and you need to insert the read content into text box.

    def loadbutton(button_press):
        with open(button_press, "r") as loadfileb:
            quote = loadfileb.read()
        T.delete('1.0', 'end')
        T.insert('end', quote)

    for item in entry_raw:
        tk.Button(sideframe, text=item, command=lambda m=item: loadbutton(m)).pack()

Note that there are different way to initiate widgets, like tk.Entry(...), tkinter.Frame(...) and Button(...) in your code. So I think you have imported tkinter like below:

import tkinter
from tkinter import *
import tkinter as tk

Recommend to use import tkinter as tk only.


问:
Printf Problem with While Loop
I'm creating a temperature converter in C. Basically, you input a minimum and maximum value in degrees Celsius, along with a step, and it displays that information in a list, along with the Fahrenheit equivalent. On some occasions, I have noticed the last Fahrenheit entry not being displayed when it should. For example, when you input a lower limit of 10, a higher limit of 30, and a step of 4, it cuts off the last Fahrenheit temperature. I know it's something to do with the last while loop, but I just can't figure it out.</p>

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

int main (int argc, const char * argv[]) {
double l, h, s;
double lf, hf, sf;
/* Number rows in tables */
int num1, num2;
num1 = 1;
num2 = 1;

/* Lower limit input */
printf("Please give a lower limit: ");
scanf("%4lf", &l);
while (l < 0) {
        printf("Lower limit must be greater than 0: ");
        scanf("%4lf", &l);
}

/* Stores value for Fahrenheit conversion */
lf = l;

/* Higher limit input */
printf("Please give a higher limit: ");
scanf("%4lf", &h);
while (h <= l) {
        printf("Higher limit must be greater than lower limit: ");
        scanf("%4lf", &h);
}

while (h >= 50000) {
        printf("Higher limit must be less than 50000: ");
        scanf("%4lf", &h);
}

hf = h;

/* Step input */
printf("Please input step: ");
scanf("%4lf", &s);
while (s <= 0) {
        printf("Step must be greater than 0: ");
        scanf("%4lf", &s);
}

while (s >= h - l) {
        printf("Step must be less than the difference in temperatures: ");
        scanf("%4lf", &s);
}

sf = s;

/* Celsius table */
printf("\nCelsius\n-------\n");
while (l <= h) {
    printf("%i. %4lf\n", num1, l);
    num1++;
    l = l + s;
}

/* Fahrenheit table */
printf("\nFahrenheit\n----------\n");
/* Converts Celsius to Fahrenheit */
lf = (lf * 1.8) + 32;
hf = (hf * 1.8) + 32;
sf = sf * 1.8;
printf("Lower input: %4lf\n", lf);
printf("Higher input: %4lf\n", hf);
printf("Step: %4lf\n----------\n", sf);
/* This while loop sometimes cuts off the last entry */
while (lf <= hf) {
    printf("%i. %4lf\n", num2, lf);
    num2++;
    lf = lf + sf;
}

return 0;

}
</code>```

答:
```<code>while (lf <= hf)
</code>```

You are comparing Double values, You will face problems of Precison & Rounding Errors, Most likely that causes the last iteration to not execute at all.

This answer of mine, should be a good read.

Title: Printf Problem with While Loop

Body:
I'm creating a temperature converter in C. Basically, you input a minimum and maximum value in degrees Celsius, along with a step, and it displays that information in a list, along with the Fahrenheit equivalent. On some occasions, I have noticed the last Fahrenheit entry not being displayed when it should. For example, when you input a lower limit of 10, a higher limit of 30, and a step of 4, it cuts off the last Fahrenheit temperature. I know it's something to do with the last while loop, but I just can't figure it out.

#include <stdio.h>

int main (int argc, const char * argv[]) {
double l, h, s;
double lf, hf, sf;
/* Number rows in tables */
int num1, num2;
num1 = 1;
num2 = 1;

/* Lower limit input */
printf("Please give a lower limit: ");
scanf("%4lf", &l);
while (l < 0) {
        printf("Lower limit must be greater than 0: ");
        scanf("%4lf", &l);
}

/* Stores value for Fahrenheit conversion */
lf = l;

/* Higher limit input */
printf("Please give a higher limit: ");
scanf("%4lf", &h);
while (h <= l) {
        printf("Higher limit must be greater than lower limit: ");
        scanf("%4lf", &h);
}

while (h >= 50000) {
        printf("Higher limit must be less than 50000: ");
        scanf("%4lf", &h);
}

hf = h;

/* Step input */
printf("Please input step: ");
scanf("%4lf", &s);
while (s <= 0) {
        printf("Step must be greater than 0: ");
        scanf("%4lf", &s);
}

while (s >= h - l) {
        printf("Step must be less than the difference in temperatures: ");
        scanf("%4lf", &s);
}

sf = s;

/* Celsius table */
printf("\nCelsius\n-------\n");
while (l <= h) {
    printf("%i. %4lf\n", num1, l);
    num1++;
    l = l + s;
}

/* Fahrenheit table */
printf("\nFahrenheit\n----------\n");
/* Converts Celsius to Fahrenheit */
lf = (lf * 1.8) + 32;
hf = (hf * 1.8) + 32;
sf = sf * 1.8;
printf("Lower input: %4lf\n", lf);
printf("Higher input: %4lf\n", hf);
printf("Step: %4lf\n----------\n", sf);
/* This while loop sometimes cuts off the last entry */
while (lf <= hf) {
    printf("%i. %4lf\n", num2, lf);
    num2++;
    lf = lf + sf;
}

return 0;

}

Body:
while (lf <= hf)

You are comparing Double values, You will face problems of Precison & Rounding Errors, Most likely that causes the last iteration to not execute at all.

This answer of mine, should be a good read.


问:
'utf-8' codec can't decode byte 0xa0 in position 4276: invalid start byte
I try to read and print the following file: txt.tsv (https://www.sec.gov/files/dera/data/financial-statement-and-notes-data-sets/2017q3_notes.zip)

According to the SEC the data set is provided in a single encoding, as follows:

Tab Delimited Value (.txt): utf-8, tab-delimited, \n- terminated lines, with the first line containing the field names in lowercase.

My current code:

```<code>import csv

with open('txt.tsv') as tsvfile:
    reader = csv.DictReader(tsvfile, dialect='excel-tab')
    for row in reader:
        print(row)
</code>```

All attempts ended with the following error message:

'utf-8' codec can't decode byte 0xa0 in position 4276: invalid start byte

I am a bit lost. Can anyone help me?

答:
I also encountered the same issue and worked while using latin1 encoding, refer to the sample code to apply in your codebase. Give a try if above resolution doesn't work.</p>
```<code>df=pd.read_csv("../CSV_FILE.csv",na_values=missing, encoding='latin1')
</code>```

Body:
I try to read and print the following file: txt.tsv (https://www.sec.gov/files/dera/data/financial-statement-and-notes-data-sets/2017q3_notes.zip)

According to the SEC the data set is provided in a single encoding, as follows:

Tab Delimited Value (.txt): utf-8, tab-delimited, \n- terminated lines, with the first line containing the field names in lowercase.

My current code:

import csv

with open('txt.tsv') as tsvfile:
    reader = csv.DictReader(tsvfile, dialect='excel-tab')
    for row in reader:
        print(row)

All attempts ended with the following error message:

'utf-8' codec can't decode byte 0xa0 in position 4276: invalid start byte

I am a bit lost. Can anyone help me?

Body:
I also encountered the same issue and worked while using latin1 encoding, refer to the sample code to apply in your codebase. Give a try if above resolution doesn't work.

df=pd.read_csv("../CSV_FILE.csv",na_values=missing, encoding='latin1')


问:
TXT Import Add Field Using Partial Filename
I am trying to import multiple .txt files from a directory into an Access table using VBA.

I have code that currently works that imports the data and moves the files to an archive directory.

What I need to do is add the first part of the filename as field in the table, namely the date.

The file format is MMDDYYYY_LbxReport.txt (ex 02082022_LbxReport.txt)

Here is the code that I have working, and I commented out what I tried to add to fix my problem:

```<code>Private Sub Command9_Click()

On Error GoTo bImportFiles_Click_Err

    Dim objFS As Object, objFolder As Object
    Dim objFiles As Object, objF1 As Object
    'Dim dteEntry As Variant             'added this variant for use in UPDATE cmd
    Dim strFolderPath As String

    Set objFS = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFS.GetFolder("\\*****************\upload\SSDTestLBXa\")
    Set objFiles = objFolder.files

    For Each objF1 In objFiles
        If Right(objF1.Name, 11) = "xReport.txt" Then  'LBX level report capture
                'dteEntry = Left(objF1.Name, 8)
                'dteEntry = Left(dteEntry, 2) & "/" & Mid(dteEntry, 3, 2) & "/" & Right(dteEntry, 4)  'added to reformat into standard date format
            DoCmd.TransferText acImportDelim, "lbxlevelspecs", "lbxlevel", strFolderPath & objF1.Name, False
            'CurrentDb.Execute "Update lbxlevel" & "Set EntryDate=" & dteEntry & "", [] 'getting syntax errors here
            Name strFolderPath & objF1.Name As "\\**************\upload\SSDTestLBXa\Archive\" & objF1.Name 'Move the files to the archive folder

        End If

    Next

    Set objF1 = Nothing
    Set objFiles = Nothing
    Set objFolder = Nothing
    Set objFS = Nothing

'Call Site_level

MsgBox ctr & "All volumes imported", , "Volume Import"

bImportFiles_Click_Exit:
    Exit Sub

bImportFiles_Click_Err:
    MsgBox Err.Number & " " & Err.Description
    Resume bImportFiles_Click_Exit

End Sub
</code>```

I saw a similar thread for this question, but I can't get the syntax right, and the OP's code was very different from what I have that's working so far.

Any help would be greatly appreciated!

答:
This is how you would construct the update statement:

```<code>Public Sub doit()

   Dim dteEntry As Variant
   dteEntry = Left("02142024_SomeName.txt", 8)
   dteEntry = Left(dteEntry, 2) & "/" & Mid(dteEntry, 3, 2) & "/" & Right(dteEntry, 4)  'added to reformat into standard date format
   CurrentDb.Execute "ALTER TABLE lbxlevel ADD EntryDate DATETIME"
   CurrentDb.Execute "Update lbxlevel " & "Set EntryDate='" & dteEntry & "'"
End Sub
</code>```

Because it needs apace before 'SET', and quotation marks around the date.

EDIT: I added the ALTER TABLE, this tests successfully on my side.

Body:
I am trying to import multiple .txt files from a directory into an Access table using VBA.

I have code that currently works that imports the data and moves the files to an archive directory.

What I need to do is add the first part of the filename as field in the table, namely the date.

The file format is MMDDYYYY_LbxReport.txt (ex 02082022_LbxReport.txt)

Here is the code that I have working, and I commented out what I tried to add to fix my problem:

Private Sub Command9_Click()

On Error GoTo bImportFiles_Click_Err

    Dim objFS As Object, objFolder As Object
    Dim objFiles As Object, objF1 As Object
    'Dim dteEntry As Variant             'added this variant for use in UPDATE cmd
    Dim strFolderPath As String

    Set objFS = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFS.GetFolder("\\*****************\upload\SSDTestLBXa\")
    Set objFiles = objFolder.files

    For Each objF1 In objFiles
        If Right(objF1.Name, 11) = "xReport.txt" Then  'LBX level report capture
                'dteEntry = Left(objF1.Name, 8)
                'dteEntry = Left(dteEntry, 2) & "/" & Mid(dteEntry, 3, 2) & "/" & Right(dteEntry, 4)  'added to reformat into standard date format
            DoCmd.TransferText acImportDelim, "lbxlevelspecs", "lbxlevel", strFolderPath & objF1.Name, False
            'CurrentDb.Execute "Update lbxlevel" & "Set EntryDate=" & dteEntry & "", [] 'getting syntax errors here
            Name strFolderPath & objF1.Name As "\\**************\upload\SSDTestLBXa\Archive\" & objF1.Name 'Move the files to the archive folder

        End If

    Next

    Set objF1 = Nothing
    Set objFiles = Nothing
    Set objFolder = Nothing
    Set objFS = Nothing

'Call Site_level

MsgBox ctr & "All volumes imported", , "Volume Import"

bImportFiles_Click_Exit:
    Exit Sub

bImportFiles_Click_Err:
    MsgBox Err.Number & " " & Err.Description
    Resume bImportFiles_Click_Exit

End Sub

I saw a similar thread for this question, but I can't get the syntax right, and the OP's code was very different from what I have that's working so far.

Any help would be greatly appreciated!

Body:
This is how you would construct the update statement:

Public Sub doit()

   Dim dteEntry As Variant
   dteEntry = Left("02142024_SomeName.txt", 8)
   dteEntry = Left(dteEntry, 2) & "/" & Mid(dteEntry, 3, 2) & "/" & Right(dteEntry, 4)  'added to reformat into standard date format
   CurrentDb.Execute "ALTER TABLE lbxlevel ADD EntryDate DATETIME"
   CurrentDb.Execute "Update lbxlevel " & "Set EntryDate='" & dteEntry & "'"
End Sub

Because it needs apace before 'SET', and quotation marks around the date.

EDIT: I added the ALTER TABLE, this tests successfully on my side.