问:
xml parsing with jquery in IE problem
I have below example made in jsfiddle which works perfectly in Firefox 6 and chrome but not in IE8. How can I resolve this issue?</p>

```<code>var xml = "<Response>  <isSuccess>true</isSuccess>  <operation>viewall</operation> <message>No configurations were found for this project</message></Response>";

alert($(xml).find('message').text());
</code>```

答:
you need to use .parseXML

```<code>var xml = "<Response>  <isSuccess>true</isSuccess>  <operation>viewall</operation> <message>No configurations were found for this project</message></Response>";

    xmlDoc = $.parseXML( xml ),
    $xml = $( xmlDoc ),
    $title = $xml.find( "message" ).text();

alert($title);
</code>```

here is the fiddle http://jsfiddle.net/szVKD/1/

jquery parse xml

Title: xml parsing with jquery in IE problem

Body:
I have below example made in jsfiddle which works perfectly in Firefox 6 and chrome but not in IE8. How can I resolve this issue?

var xml = "<Response>  <isSuccess>true</isSuccess>  <operation>viewall</operation> <message>No configurations were found for this project</message></Response>";

alert($(xml).find('message').text());

Body:
you need to use .parseXML

var xml = "<Response>  <isSuccess>true</isSuccess>  <operation>viewall</operation> <message>No configurations were found for this project</message></Response>";

    xmlDoc = $.parseXML( xml ),
    $xml = $( xmlDoc ),
    $title = $xml.find( "message" ).text();

alert($title);

here is the fiddle http://jsfiddle.net/szVKD/1/

jquery parse xml


来源: stackexchange

问:
IDFA iOS14 returns denied without displaying auth popup
I am doing a research on getting the IDFA on iOS 14. I am using iPhone 8 Plus.

I have added

<key>NSUserTrackingUsageDescription</key>
<string>App would like to access IDFA for tracking purpose</string>
```
<p>in the <code>.plist</code> file.</p>
<p>Then added</p>
<pre class="lang-swift prettyprint-override"><code>let type = ATTrackingManager.trackingAuthorizationStatus;
</code>```

which returns .denied, having

func requestPermission() {
        ATTrackingManager.requestTrackingAuthorization { status in
            switch status {
            case .authorized:
                // Tracking authorization dialog was shown
                // and we are authorized
                print("Authorized")

                // Now that we are authorized we can get the IDFA
            print(ASIdentifierManager.shared().advertisingIdentifier)
            case .denied:
               // Tracking authorization dialog was
               // shown and permission is denied
                 print("Denied")
            case .notDetermined:
                    // Tracking authorization dialog has not been shown
                    print("Not Determined")
            case .restricted:
                    print("Restricted")
            @unknown default:
                    print("Unknown")
            }
        }
    }
```

But I'm getting .denied without any popup.

Do you know what is happening?

答: The call to the authorization method ATTrackingManager.requestTrackingAuthorization must be placed in the viewDidAppear(_:) method of the main controller or even further (run later), i.e. can be tied to a button</p>

ContentLicense: CC BY-SA 4.0

Body:
I am doing a research on getting the IDFA on iOS 14. I am using iPhone 8 Plus.

I have added

<key>NSUserTrackingUsageDescription</key>
<string>App would like to access IDFA for tracking purpose</string>

in the .plist file.

Then added

let type = ATTrackingManager.trackingAuthorizationStatus;

which returns .denied, having

func requestPermission() {
        ATTrackingManager.requestTrackingAuthorization { status in
            switch status {
            case .authorized:
                // Tracking authorization dialog was shown
                // and we are authorized
                print("Authorized")

                // Now that we are authorized we can get the IDFA
            print(ASIdentifierManager.shared().advertisingIdentifier)
            case .denied:
               // Tracking authorization dialog was
               // shown and permission is denied
                 print("Denied")
            case .notDetermined:
                    // Tracking authorization dialog has not been shown
                    print("Not Determined")
            case .restricted:
                    print("Restricted")
            @unknown default:
                    print("Unknown")
            }
        }
    }

But I'm getting .denied without any popup.

Do you know what is happening?


问:
Do something every x minutes in Swift
How can I run a function every minute?
In JavaScript I can do something like setInterval, does something similar exist in Swift?

Wanted output:

Hello World once a minute...

答:
```<code>timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true, block: myMethod)

func myMethod(_:Timer) {
...
}
</code>```

or

```<code>timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { _ in
...
}
</code>```

make sure to invalid the timer at some point like your time is no longer visible, or you object is deist

ContentLicense: CC BY-SA 3.0

Title: Do something every x minutes in Swift

Body:
timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true, block: myMethod)

func myMethod(_:Timer) {
...
}

or

timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { _ in
...
}

make sure to invalid the timer at some point like your time is no longer visible, or you object is deist


问:
Merge an array with a specific key
How can I merge arrays witch have the same key 'email'. Like this exemple [4] and [6] have the same email adress.

```<code>Array
(
    [0] => Array
        (
            [email] => test01@laposte.net
            [gender] => m
            [lastname] => Canvas
            [firstname] => Peter
            [birthdate] => 1987-09-13
            [country] => DE
            [xgfx3r] =>
            [language] => fr_FR
            [newsletter] => 0
            [newsletter_partner] => 0
            [facebook_login] => yes
            [date] => 2011-08-11 15:41:54
            [vol6t3] => L'homme de bernadette
            [uwwpma] =>
            [bhqgzn] =>
            [nb_email_shared] =>
            [period] => 1
        )

    [1] => Array
        (
            [email] => test@laposte.net
            [gender] => m
            [lastname] => Canvas
            [firstname] => Peter
            [birthdate] => 1987-09-13
            [country] => DZ
            [xgfx3r] =>
            [language] => fr_FR
            [newsletter] => 0
            [newsletter_partner] => 0
            [facebook_login] => yes
            [date] => 2011-08-11 15:42:50
            [vol6t3] => L'homme de bernadette
            [uwwpma] =>
            [bhqgzn] =>
            [nb_email_shared] =>
            [period] => 1
        )

    [2] => Array
        (
            [email] => sqd@test.com
            [gender] => m
            [lastname] => qsd
            [firstname] => qsd
            [birthdate] => 1981-01-17
            [country] => AT
            [xgfx3r] =>
            [language] => fr_FR
            [newsletter] => 0
            [newsletter_partner] => 0
            [facebook_login] =>
            [date] => 2011-08-11 15:43:22
            [vol6t3] => Un militant de gauche
            [uwwpma] =>
            [bhqgzn] =>
            [nb_email_shared] =>
            [period] => 1
        )

    [3] => Array
        (
            [email] => qsd@laposte.net
            [gender] => m
            [lastname] => qsd
            [firstname] => qsdqsd
            [birthdate] => 1982-02-19
            [country] => BS
            [xgfx3r] =>
            [language] => fr_FR
            [newsletter] => 0
            [newsletter_partner] => 0
            [facebook_login] =>
            [date] => 2011-08-11 15:45:13
            [vol6t3] => Un militant de gauche
            [uwwpma] =>
            [bhqgzn] =>
            [nb_email_shared] =>
            [period] => 1
        )

    [4] => Array
        (
            [email] => qsdqs@laposte.net
            [gender] => m
            [lastname] => qds
            [firstname] => dqs
            [birthdate] => 1980-11-19
            [country] => BS
            [xgfx3r] =>
            [language] => fr_FR
            [newsletter] => 0
            [newsletter_partner] => 0
            [facebook_login] =>
            [date] => 2011-08-11 15:46:14
            [vol6t3] => Un militant de gauche
            [uwwpma] =>
            [bhqgzn] =>
            [nb_email_shared] =>
            [period] => 1
        )

    [5] => Array
        (
            [email] => lol@laposte.net
            [gender] => m
            [lastname] => Canvas
            [firstname] => Peter
            [birthdate] => 1987-09-13
            [country] => DE
            [xgfx3r] =>
            [language] => fr_FR
            [newsletter] => 0
            [newsletter_partner] => 0
            [facebook_login] => yes
            [date] => 2011-08-11 15:47:11
            [vol6t3] => L'homme de bernadette
            [uwwpma] =>
            [bhqgzn] =>
            [nb_email_shared] =>
            [period] => 1
        )

    [6] => Array
        (
            [email] => qsdqs@laposte.net
            [gender] => m
            [lastname] => Canvas
            [firstname] => Peter
            [birthdate] => 1987-09-13
            [country] => DE
            [xgfx3r] =>
            [language] => fr_FR
            [newsletter] => 0
            [newsletter_partner] => 0
            [facebook_login] => yes
            [date] => 2011-08-11 15:48:35
            [vol6t3] =>
            [uwwpma] => Toi
            [bhqgzn] =>
            [nb_email_shared] =>
            [period] => 2
        )

)
</code>```

into

```<code>Array
    (
        [0] => Array
            (
                [email] => test01@laposte.net
                [gender] => m
                [lastname] => Canvas
                [firstname] => Peter
                [birthdate] => 1987-09-13
                [country] => DE
                [xgfx3r] =>
                [language] => fr_FR
                [newsletter] => 0
                [newsletter_partner] => 0
                [facebook_login] => yes
                [date] => 2011-08-11 15:41:54
                [vol6t3] => L'homme de bernadette
                [uwwpma] =>
                [bhqgzn] =>
                [nb_email_shared] =>
                [period] => 1
            )

        [1] => Array
            (
                [email] => test@laposte.net
                [gender] => m
                [lastname] => Canvas
                [firstname] => Peter
                [birthdate] => 1987-09-13
                [country] => DZ
                [xgfx3r] =>
                [language] => fr_FR
                [newsletter] => 0
                [newsletter_partner] => 0
                [facebook_login] => yes
                [date] => 2011-08-11 15:42:50
                [vol6t3] => L'homme de bernadette
                [uwwpma] =>
                [bhqgzn] =>
                [nb_email_shared] =>
                [period] => 1
            )

        [2] => Array
            (
                [email] => sqd@test.com
                [gender] => m
                [lastname] => qsd
                [firstname] => qsd
                [birthdate] => 1981-01-17
                [country] => AT
                [xgfx3r] =>
                [language] => fr_FR
                [newsletter] => 0
                [newsletter_partner] => 0
                [facebook_login] =>
                [date] => 2011-08-11 15:43:22
                [vol6t3] => Un militant de gauche
                [uwwpma] =>
                [bhqgzn] =>
                [nb_email_shared] =>
                [period] => 1
            )

        [3] => Array
            (
                [email] => qsd@laposte.net
                [gender] => m
                [lastname] => qsd
                [firstname] => qsdqsd
                [birthdate] => 1982-02-19
                [country] => BS
                [xgfx3r] =>
                [language] => fr_FR
                [newsletter] => 0
                [newsletter_partner] => 0
                [facebook_login] =>
                [date] => 2011-08-11 15:45:13
                [vol6t3] => Un militant de gauche
                [uwwpma] =>
                [bhqgzn] =>
                [nb_email_shared] =>
                [period] => 1
            )

        [4] => Array
            (
                [email] => qsdqs@laposte.net
                [gender] => m
                [lastname] => qds
                [firstname] => dqs
                [birthdate] => 1980-11-19
                [country] => BS
                [xgfx3r] =>
                [language] => fr_FR
                [newsletter] => 0
                [newsletter_partner] => 0
                [facebook_login] =>
                [date] => 2011-08-11 15:46:14
                [vol6t3] => Un militant de gauche
                [uwwpma] => Toi
                [bhqgzn] =>
                [nb_email_shared] =>
                [period] => 2
            )

        [5] => Array
            (
                [email] => lol@laposte.net
                [gender] => m
                [lastname] => Canvas
                [firstname] => Peter
                [birthdate] => 1987-09-13
                [country] => DE
                [xgfx3r] =>
                [language] => fr_FR
                [newsletter] => 0
                [newsletter_partner] => 0
                [facebook_login] => yes
                [date] => 2011-08-11 15:47:11
                [vol6t3] => L'homme de bernadette
                [uwwpma] =>
                [bhqgzn] =>
                [nb_email_shared] =>
                [period] => 1
            )
    )
</code>```

Many thanks before !

regard, Peter

答:
Thanks all and special thank to Stanislav Shabalin who really help me.

I write my function which run successfully :) bellow :

```

    /**
       * Get a distinct multi dimensional array
       *
       * @param array $array
       *  array to distinct
       * @param string $keySearch
       *  string key to search double array
       * @param boolean $overwrite = false
       *  boolean to allow values to be overwritten
       * @param array $exception = array()
       *  array of keys to not overwrite if overwrite is true
       *
       * @return array $result
       *  Return a multi dimensional array witch has been distinct.
       */
    public static function distinctMultiDimensionalArray($array, $keySearch, $overwrite = false, $exception = array())
    {

      // Check if it's an array
      if( !is_array($array) )
        return false;

      $result = array();

      foreach ( $array as $entry )
      {
        // If email doesn't exist
        if ( !isset($result[$entry[$keySearch]]) )
          $result[$entry[$keySearch]] = $entry;
        else
        {
          // If email exist
          foreach ( $entry as $key => $value )
          {
            if( !empty($value) )
            {
              // If not empty value and this value is different from before and you don't want to overwrite values
              // Or you want to overwrite values except some keys
              if( ( !empty( $result[$entry[$keySearch]][$key] )
                    && $result[$entry[$keySearch]][$key] != $value
                    && $overwrite == false )
                ||
                  ( $overwrite == true
                    && in_array($key, $exception) ) )
                $result[$entry[$keySearch]][$key] = $result[$entry[$keySearch]][$key] . ', ' . $value;
              else
                $result[$entry[$keySearch]][$key] = $value;
            }

          }
        }
      }
      $result = array_values($result);

      return $result;
    }

```

Thanks a lot !

Title: Merge an array with a specific key

Body:
How can I merge arrays witch have the same key 'email'. Like this exemple [4] and [6] have the same email adress.

Array
(
    [0] => Array
        (
            [email] => test01@laposte.net
            [gender] => m
            [lastname] => Canvas
            [firstname] => Peter
            [birthdate] => 1987-09-13
            [country] => DE
            [xgfx3r] =>
            [language] => fr_FR
            [newsletter] => 0
            [newsletter_partner] => 0
            [facebook_login] => yes
            [date] => 2011-08-11 15:41:54
            [vol6t3] => L'homme de bernadette
            [uwwpma] =>
            [bhqgzn] =>
            [nb_email_shared] =>
            [period] => 1
        )

    [1] => Array
        (
            [email] => test@laposte.net
            [gender] => m
            [lastname] => Canvas
            [firstname] => Peter
            [birthdate] => 1987-09-13
            [country] => DZ
            [xgfx3r] =>
            [language] => fr_FR
            [newsletter] => 0
            [newsletter_partner] => 0
            [facebook_login] => yes
            [date] => 2011-08-11 15:42:50
            [vol6t3] => L'homme de bernadette
            [uwwpma] =>
            [bhqgzn] =>
            [nb_email_shared] =>
            [period] => 1
        )

    [2] => Array
        (
            [email] => sqd@test.com
            [gender] => m
            [lastname] => qsd
            [firstname] => qsd
            [birthdate] => 1981-01-17
            [country] => AT
            [xgfx3r] =>
            [language] => fr_FR
            [newsletter] => 0
            [newsletter_partner] => 0
            [facebook_login] =>
            [date] => 2011-08-11 15:43:22
            [vol6t3] => Un militant de gauche
            [uwwpma] =>
            [bhqgzn] =>
            [nb_email_shared] =>
            [period] => 1
        )

    [3] => Array
        (
            [email] => qsd@laposte.net
            [gender] => m
            [lastname] => qsd
            [firstname] => qsdqsd
            [birthdate] => 1982-02-19
            [country] => BS
            [xgfx3r] =>
            [language] => fr_FR
            [newsletter] => 0
            [newsletter_partner] => 0
            [facebook_login] =>
            [date] => 2011-08-11 15:45:13
            [vol6t3] => Un militant de gauche
            [uwwpma] =>
            [bhqgzn] =>
            [nb_email_shared] =>
            [period] => 1
        )

    [4] => Array
        (
            [email] => qsdqs@laposte.net
            [gender] => m
            [lastname] => qds
            [firstname] => dqs
            [birthdate] => 1980-11-19
            [country] => BS
            [xgfx3r] =>
            [language] => fr_FR
            [newsletter] => 0
            [newsletter_partner] => 0
            [facebook_login] =>
            [date] => 2011-08-11 15:46:14
            [vol6t3] => Un militant de gauche
            [uwwpma] =>
            [bhqgzn] =>
            [nb_email_shared] =>
            [period] => 1
        )

    [5] => Array
        (
            [email] => lol@laposte.net
            [gender] => m
            [lastname] => Canvas
            [firstname] => Peter
            [birthdate] => 1987-09-13
            [country] => DE
            [xgfx3r] =>
            [language] => fr_FR
            [newsletter] => 0
            [newsletter_partner] => 0
            [facebook_login] => yes
            [date] => 2011-08-11 15:47:11
            [vol6t3] => L'homme de bernadette
            [uwwpma] =>
            [bhqgzn] =>
            [nb_email_shared] =>
            [period] => 1
        )

    [6] => Array
        (
            [email] => qsdqs@laposte.net
            [gender] => m
            [lastname] => Canvas
            [firstname] => Peter
            [birthdate] => 1987-09-13
            [country] => DE
            [xgfx3r] =>
            [language] => fr_FR
            [newsletter] => 0
            [newsletter_partner] => 0
            [facebook_login] => yes
            [date] => 2011-08-11 15:48:35
            [vol6t3] =>
            [uwwpma] => Toi
            [bhqgzn] =>
            [nb_email_shared] =>
            [period] => 2
        )

)

into

Array
    (
        [0] => Array
            (
                [email] => test01@laposte.net
                [gender] => m
                [lastname] => Canvas
                [firstname] => Peter
                [birthdate] => 1987-09-13
                [country] => DE
                [xgfx3r] =>
                [language] => fr_FR
                [newsletter] => 0
                [newsletter_partner] => 0
                [facebook_login] => yes
                [date] => 2011-08-11 15:41:54
                [vol6t3] => L'homme de bernadette
                [uwwpma] =>
                [bhqgzn] =>
                [nb_email_shared] =>
                [period] => 1
            )

        [1] => Array
            (
                [email] => test@laposte.net
                [gender] => m
                [lastname] => Canvas
                [firstname] => Peter
                [birthdate] => 1987-09-13
                [country] => DZ
                [xgfx3r] =>
                [language] => fr_FR
                [newsletter] => 0
                [newsletter_partner] => 0
                [facebook_login] => yes
                [date] => 2011-08-11 15:42:50
                [vol6t3] => L'homme de bernadette
                [uwwpma] =>
                [bhqgzn] =>
                [nb_email_shared] =>
                [period] => 1
            )

        [2] => Array
            (
                [email] => sqd@test.com
                [gender] => m
                [lastname] => qsd
                [firstname] => qsd
                [birthdate] => 1981-01-17
                [country] => AT
                [xgfx3r] =>
                [language] => fr_FR
                [newsletter] => 0
                [newsletter_partner] => 0
                [facebook_login] =>
                [date] => 2011-08-11 15:43:22
                [vol6t3] => Un militant de gauche
                [uwwpma] =>
                [bhqgzn] =>
                [nb_email_shared] =>
                [period] => 1
            )

        [3] => Array
            (
                [email] => qsd@laposte.net
                [gender] => m
                [lastname] => qsd
                [firstname] => qsdqsd
                [birthdate] => 1982-02-19
                [country] => BS
                [xgfx3r] =>
                [language] => fr_FR
                [newsletter] => 0
                [newsletter_partner] => 0
                [facebook_login] =>
                [date] => 2011-08-11 15:45:13
                [vol6t3] => Un militant de gauche
                [uwwpma] =>
                [bhqgzn] =>
                [nb_email_shared] =>
                [period] => 1
            )

        [4] => Array
            (
                [email] => qsdqs@laposte.net
                [gender] => m
                [lastname] => qds
                [firstname] => dqs
                [birthdate] => 1980-11-19
                [country] => BS
                [xgfx3r] =>
                [language] => fr_FR
                [newsletter] => 0
                [newsletter_partner] => 0
                [facebook_login] =>
                [date] => 2011-08-11 15:46:14
                [vol6t3] => Un militant de gauche
                [uwwpma] => Toi
                [bhqgzn] =>
                [nb_email_shared] =>
                [period] => 2
            )

        [5] => Array
            (
                [email] => lol@laposte.net
                [gender] => m
                [lastname] => Canvas
                [firstname] => Peter
                [birthdate] => 1987-09-13
                [country] => DE
                [xgfx3r] =>
                [language] => fr_FR
                [newsletter] => 0
                [newsletter_partner] => 0
                [facebook_login] => yes
                [date] => 2011-08-11 15:47:11
                [vol6t3] => L'homme de bernadette
                [uwwpma] =>
                [bhqgzn] =>
                [nb_email_shared] =>
                [period] => 1
            )
    )

Many thanks before !

regard, Peter

Body:
Thanks all and special thank to Stanislav Shabalin who really help me.

I write my function which run successfully :) bellow :

    /**
       * Get a distinct multi dimensional array
       *
       * @param array $array
       *  array to distinct
       * @param string $keySearch
       *  string key to search double array
       * @param boolean $overwrite = false
       *  boolean to allow values to be overwritten
       * @param array $exception = array()
       *  array of keys to not overwrite if overwrite is true
       *
       * @return array $result
       *  Return a multi dimensional array witch has been distinct.
       */
    public static function distinctMultiDimensionalArray($array, $keySearch, $overwrite = false, $exception = array())
    {

      // Check if it's an array
      if( !is_array($array) )
        return false;

      $result = array();

      foreach ( $array as $entry )
      {
        // If email doesn't exist
        if ( !isset($result[$entry[$keySearch]]) )
          $result[$entry[$keySearch]] = $entry;
        else
        {
          // If email exist
          foreach ( $entry as $key => $value )
          {
            if( !empty($value) )
            {
              // If not empty value and this value is different from before and you don't want to overwrite values
              // Or you want to overwrite values except some keys
              if( ( !empty( $result[$entry[$keySearch]][$key] )
                    && $result[$entry[$keySearch]][$key] != $value
                    && $overwrite == false )
                ||
                  ( $overwrite == true
                    && in_array($key, $exception) ) )
                $result[$entry[$keySearch]][$key] = $result[$entry[$keySearch]][$key] . ', ' . $value;
              else
                $result[$entry[$keySearch]][$key] = $value;
            }

          }
        }
      }
      $result = array_values($result);

      return $result;
    }

Thanks a lot !


问:
Upgrade python to 3.10 in windows; Do I have to reinstall all site-packages manually?
I have in windows 10 64 bit installed python 3.9 with site-packages. I would like to install python 3.10.2 on windows 10 64 bit and find a way to install packages automatically in python 3.10.2, the same ones I currently have installed in python 3.9. I am also interested in the answer to this question for windows 11 64 bit.</p>

答:
I upgraded to python 3.10.2 in windows 10 64 bit. To properly install the packages, install the appropriate version of the Microsoft Visual C++ compiler if necessary. Details can be read https://wiki.python.org/moin/WindowsCompilers . With the upgrade to python 3.10.2 from 3.9, it turned out that I had to do it, due to errors that are appearing during the installation of the packages. Before the installing python 3.10.2, type and execute the following command in the windows command prompt:

```<code>pip freeze > reqs.txt
</code>```

This command writes to the reqs.txt file the names of all installed packages in the version suitable for pip. If you run the command prompt with administrator privileges, the reqs.txt file will be saved in the directory C:\WINDOWS\system32.

Then, after the installing of python 3.10.2 and the adding it to the paths in PATH, with the help of the command prompt you need to issue the command:

```<code>pip install -r reqs.txt
</code>```

This will start the installing of the packages in the same versions as for python 3.9. If problems occur, e.g. an installation error appears during the installation of lxml, then you can remove from the regs.txt file the entry with the name of the package whose installation is causing the problem and then install it manually. To edit the reqs.txt file you need the administrator privileges. The easiest way is to run the command prompt in the administrator mode, type reqs.txt and click Enter to edit it.

I decided later to update the missing packages to the latest version, because I suspected that with python 3.10.2 older versions were not compatible.
This means that when upgrading to python 3.10.2 it is worth asking yourself whether it is better to upgrade for all packages. To do this, you can generate the list of the outdated packages using the command:

```<code>pip list –-outdated
</code>```

After the printing of the list in the command prompt, you can upgrade the outdated packages using the command:

```<code>pip install --upgrade <package-name>
</code>```

This can be automated by the editing of the reqs.txt file and the changing of the mark == to > which will speed up the upgrade. The mark >  should only be changed for the outdated packages or you will get an error: "Could not find a version that satisfies the requirement ... ".

Supplement to virtual environments:

When you enter a virtual environment directory (in the windows command prompt):, such as D:\python_projects\data_visualization\env\Scripts, type activate to activate it. Then create the reqs.txt file analogous to the description above. Then, copy the file to a temporary directory. After this delete the virtual environment, e.g. using the windows explorator by the deleting of the contents of the env directory. Then, using the version of python in windows of our choice, create a virtual environment using the env directory (see: https://docs.python.org/3/library/venv.html). Copy the regs.txt file to the newly created D:\python_projects\data_visualization\env\Scripts directory. Install site-packages with the support of the regs.txt file as described above.

Body:
I upgraded to python 3.10.2 in windows 10 64 bit. To properly install the packages, install the appropriate version of the Microsoft Visual C++ compiler if necessary. Details can be read https://wiki.python.org/moin/WindowsCompilers . With the upgrade to python 3.10.2 from 3.9, it turned out that I had to do it, due to errors that are appearing during the installation of the packages. Before the installing python 3.10.2, type and execute the following command in the windows command prompt:

pip freeze > reqs.txt

This command writes to the reqs.txt file the names of all installed packages in the version suitable for pip. If you run the command prompt with administrator privileges, the reqs.txt file will be saved in the directory C:\WINDOWS\system32.

Then, after the installing of python 3.10.2 and the adding it to the paths in PATH, with the help of the command prompt you need to issue the command:

pip install -r reqs.txt

This will start the installing of the packages in the same versions as for python 3.9. If problems occur, e.g. an installation error appears during the installation of lxml, then you can remove from the regs.txt file the entry with the name of the package whose installation is causing the problem and then install it manually. To edit the reqs.txt file you need the administrator privileges. The easiest way is to run the command prompt in the administrator mode, type reqs.txt and click Enter to edit it.

I decided later to update the missing packages to the latest version, because I suspected that with python 3.10.2 older versions were not compatible.
This means that when upgrading to python 3.10.2 it is worth asking yourself whether it is better to upgrade for all packages. To do this, you can generate the list of the outdated packages using the command:

pip list –-outdated

After the printing of the list in the command prompt, you can upgrade the outdated packages using the command:

pip install --upgrade <package-name>

This can be automated by the editing of the reqs.txt file and the changing of the mark == to > which will speed up the upgrade. The mark >  should only be changed for the outdated packages or you will get an error: "Could not find a version that satisfies the requirement ... ".

Supplement to virtual environments:

When you enter a virtual environment directory (in the windows command prompt):, such as D:\python_projects\data_visualization\env\Scripts, type activate to activate it. Then create the reqs.txt file analogous to the description above. Then, copy the file to a temporary directory. After this delete the virtual environment, e.g. using the windows explorator by the deleting of the contents of the env directory. Then, using the version of python in windows of our choice, create a virtual environment using the env directory (see: https://docs.python.org/3/library/venv.html). Copy the regs.txt file to the newly created D:\python_projects\data_visualization\env\Scripts directory. Install site-packages with the support of the regs.txt file as described above.


问:
Replace consecutive identic elements in the beginning of an array with 0
I want to replace the N first identic consecutive numbers from an array with 0.

```<code>import numpy as np

x = np.array([1, 1, 1, 1, 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2])
</code>```

OUT -> np.array([0, 0, 0, 0 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2])

Loop works, but what would be a faster-vectorized implementation?

```<code>i = 0
first = x[0]
while x[i] == first and i <= x.size - 1:
    x[i] = 0
    i += 1
</code>```

答:
You can use argmax on a boolean array to get the index of the first changing value.

Then slice and replace:

```<code>n = (x!=x[0]).argmax()  # 4
x[:n] = 0
</code>```

output:

```<code>array([0, 0, 0, 0, 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2])
</code>```

intermediate array:

```<code>(x!=x[0])

#                            n=4
# [False False False False  True  True  True  True  True  True  True  True
#  True  True  True  True  True  True  True]
</code>```

Body:
I want to replace the N first identic consecutive numbers from an array with 0.

import numpy as np

x = np.array([1, 1, 1, 1, 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2])

OUT -> np.array([0, 0, 0, 0 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2])

Loop works, but what would be a faster-vectorized implementation?

i = 0
first = x[0]
while x[i] == first and i <= x.size - 1:
    x[i] = 0
    i += 1

Body:
You can use argmax on a boolean array to get the index of the first changing value.

Then slice and replace:

n = (x!=x[0]).argmax()  # 4
x[:n] = 0

output:

array([0, 0, 0, 0, 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2])

intermediate array:

(x!=x[0])

#                            n=4
# [False False False False  True  True  True  True  True  True  True  True
#  True  True  True  True  True  True  True]


问:
How to create a pathlib relative path with a dot starting point?
I needed to create a relative path starting with the current directory as a "." dot

For example, in windows ".\envs\.some.env" or "./envs/.some.env" elsewhere

I wanted to do this using pathlib. A solution was found, but it has a kludgy replace statement.  Is there a better way to do this using pathlib?

The usage was django-environ, and the goal was to support multiple env files. The working folder contained an envs folder with the multiple env files within that folder.

```<code>import environ
from pathlib import Path
import os

domain_env = Path.cwd()

dotdot = Path("../")
some_env = dotdot / "envs" / ".some.env"

envsome = environ.Env()
envsome.read_env(envsome.str(str(domain_env), str(some_env).replace("..", ".")))

print(str(some_env))
print(str(some_env).replace("..", "."))

dot = Path("./")    # Path(".") gives the same result
some_env = dot / "envs" / ".some.env"

print(str(some_env))
</code>```

On windows gives:

```<code>..\envs\.some.env
.\envs\.some.env
envs\.some.env
</code>```

答:
The best I could find was (as suggested by metatoaster in the question’s comments):

os.path.join(".", some_env)
```

where some_env may either be a string or bytes or (since Python 3.6) any path-like object (which means you don’t have to convert your Path objects to strings anymore).

And since some people are wondering why this might be useful:

A shell script foo.sh in the current directory cannot be called by foo.sh (except when . is in $PATH), but must instead be invoked using ./foo.sh.

As Boris explained, in a Node.js require() statement there’s a difference between foo and ./foo.

I myself needed this in order to create a file name argument to ExifTool that’s guaranteed to not be parsed as a command line option, even if the file is for example called -quiet. ExifTool doesn’t adhere to the Unix convention of having a -- argument that denotes all the following argument to not be options, and the official suggestion by its author is to “[p]ut the directory name before the file name if the file name begins with a dash”.

Body:
I needed to create a relative path starting with the current directory as a "." dot

For example, in windows ".\envs\.some.env" or "./envs/.some.env" elsewhere

I wanted to do this using pathlib. A solution was found, but it has a kludgy replace statement.  Is there a better way to do this using pathlib?

The usage was django-environ, and the goal was to support multiple env files. The working folder contained an envs folder with the multiple env files within that folder.

import environ
from pathlib import Path
import os

domain_env = Path.cwd()

dotdot = Path("../")
some_env = dotdot / "envs" / ".some.env"

envsome = environ.Env()
envsome.read_env(envsome.str(str(domain_env), str(some_env).replace("..", ".")))

print(str(some_env))
print(str(some_env).replace("..", "."))

dot = Path("./")    # Path(".") gives the same result
some_env = dot / "envs" / ".some.env"

print(str(some_env))

On windows gives:

..\envs\.some.env
.\envs\.some.env
envs\.some.env

Body:
The best I could find was (as suggested by metatoaster in the question’s comments):

os.path.join(".", some_env)

where some_env may either be a string or bytes or (since Python 3.6) any path-like object (which means you don’t have to convert your Path objects to strings anymore).

And since some people are wondering why this might be useful:

A shell script foo.sh in the current directory cannot be called by foo.sh (except when . is in $PATH), but must instead be invoked using ./foo.sh.

As Boris explained, in a Node.js require() statement there’s a difference between foo and ./foo.

I myself needed this in order to create a file name argument to ExifTool that’s guaranteed to not be parsed as a command line option, even if the file is for example called -quiet. ExifTool doesn’t adhere to the Unix convention of having a -- argument that denotes all the following argument to not be options, and the official suggestion by its author is to “[p]ut the directory name before the file name if the file name begins with a dash”.


问:
How to overcome the FCBL_FIELD_COULD_BE_LOCAL issue in FindBugs?
In FindBugs, I am getting an issue like FCBL_FIELD_COULD_BE_LOCAL on the class name line of this code:

```<code>@Entity
@Table(name = "Student")
@Immutable
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class RetrievableStudent extends BaseStudent
{
    @Id
    @Column(name = "STUDENT_ID")
    private long studentId;

    @Column(name = "STUD_NOTE")
    private String studenetNote;
}
</code>```

How can I resolve this issue?

答:
My POJO has already getters setters, equals, hashcode.

It worked when I tried adding @JsonProperty annotation, as my POJO is built for API response purposes.

If the POJO is for ORM purposes (means database entity) the on getters and setters @Column annotation should work.

Body:
In FindBugs, I am getting an issue like FCBL_FIELD_COULD_BE_LOCAL on the class name line of this code:

@Entity
@Table(name = "Student")
@Immutable
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class RetrievableStudent extends BaseStudent
{
    @Id
    @Column(name = "STUDENT_ID")
    private long studentId;

    @Column(name = "STUD_NOTE")
    private String studenetNote;
}

How can I resolve this issue?


问:
Device not applicable for the "main.dart" configuration ,
I use Android Studio as my IDE in coding Flutter. I was able to create 2 projects before this and it worked absolutely fine. I had to clone a repo from Github. The IDE said to get config. I did that then this happened.

I already installed sdk .

My android devices android version is 7.0

Flutter Doctor result:

```<code>[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.720], locale en-US)
    • Flutter version 1.12.13+hotfix.8 at C:\src\flutter\flutter
    • Framework revision 0b8abb4724 (6 weeks ago), 2020-02-11 11:44:36 -0800
    • Engine revision e1e6ced81d
    • Dart version 2.7.0

[X] Android toolchain - develop for Android devices
    X Unable to locate Android SDK.
      Install Android Studio from: https://developer.android.com/studio/index.html
      On first launch it will assist you in installing the Android SDK components.
      (or visit https://flutter.dev/setup/#android-setup for detailed instructions).
      If the Android SDK has been installed to a custom location, set ANDROID_HOME to that location.
      You may also want to add it to your PATH environment variable.

[√] Android Studio (version 3.6)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 44.0.2
    • Dart plugin version 192.7761
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)

[!] Android Studio
    • Android Studio at C:\Program
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    X android-studio-dir = C:\Program
    X Android Studio not found at C:\Program
    • Try updating or re-installing Android Studio.
    • Consider removing your android-studio-dir setting by running:
      flutter config --android-studio-dir=

[!] VS Code
    • VS Code at C:\Users\Tamim Mostafa\AppData\Local\Programs\Microsoft VS Code
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[!] Connected device
    ! No devices available

! Doctor found issues in 4 categories.
</code>```

I also tried changing the directory an using folder with no white space. I moved the Sdk folder to D:\Android\Sdk. flutter doctor -v:

```<code>[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.720], locale en-US)
    • Flutter version 1.12.13+hotfix.8 at C:\src\flutter\flutter
    • Framework revision 0b8abb4724 (6 weeks ago), 2020-02-11 11:44:36 -0800
    • Engine revision e1e6ced81d
    • Dart version 2.7.0

[X] Android toolchain - develop for Android devices
    X ANDROID_HOME = D:\Android\Sdk
      but Android SDK not found at this location.

[√] Android Studio (version 3.6)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 44.0.2
    • Dart plugin version 192.7761
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)

[!] Android Studio
    • Android Studio at C:\Program
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    X android-studio-dir = C:\Program
    X Android Studio not found at C:\Program
    • Try updating or re-installing Android Studio.
    • Consider removing your android-studio-dir setting by running:
      flutter config --android-studio-dir=

[!] VS Code
    • VS Code at C:\Users\Tamim Mostafa\AppData\Local\Programs\Microsoft VS Code
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[!] Connected device
    ! No devices available

! Doctor found issues in 4 categories.
</code>```

答:
This kind of problem I was facing so When I was done with Invalid caches/ restart then it automatically detect the main. dart and works fine.

Just give it a try with Invalid Caches/ Restart.

Body:
I use Android Studio as my IDE in coding Flutter. I was able to create 2 projects before this and it worked absolutely fine. I had to clone a repo from Github. The IDE said to get config. I did that then this happened.

I already installed sdk .

My android devices android version is 7.0

Flutter Doctor result:

[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.720], locale en-US)
    • Flutter version 1.12.13+hotfix.8 at C:\src\flutter\flutter
    • Framework revision 0b8abb4724 (6 weeks ago), 2020-02-11 11:44:36 -0800
    • Engine revision e1e6ced81d
    • Dart version 2.7.0

[X] Android toolchain - develop for Android devices
    X Unable to locate Android SDK.
      Install Android Studio from: https://developer.android.com/studio/index.html
      On first launch it will assist you in installing the Android SDK components.
      (or visit https://flutter.dev/setup/#android-setup for detailed instructions).
      If the Android SDK has been installed to a custom location, set ANDROID_HOME to that location.
      You may also want to add it to your PATH environment variable.

[√] Android Studio (version 3.6)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 44.0.2
    • Dart plugin version 192.7761
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)

[!] Android Studio
    • Android Studio at C:\Program
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    X android-studio-dir = C:\Program
    X Android Studio not found at C:\Program
    • Try updating or re-installing Android Studio.
    • Consider removing your android-studio-dir setting by running:
      flutter config --android-studio-dir=

[!] VS Code
    • VS Code at C:\Users\Tamim Mostafa\AppData\Local\Programs\Microsoft VS Code
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[!] Connected device
    ! No devices available

! Doctor found issues in 4 categories.

I also tried changing the directory an using folder with no white space. I moved the Sdk folder to D:\Android\Sdk. flutter doctor -v:

[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.720], locale en-US)
    • Flutter version 1.12.13+hotfix.8 at C:\src\flutter\flutter
    • Framework revision 0b8abb4724 (6 weeks ago), 2020-02-11 11:44:36 -0800
    • Engine revision e1e6ced81d
    • Dart version 2.7.0

[X] Android toolchain - develop for Android devices
    X ANDROID_HOME = D:\Android\Sdk
      but Android SDK not found at this location.

[√] Android Studio (version 3.6)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 44.0.2
    • Dart plugin version 192.7761
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)

[!] Android Studio
    • Android Studio at C:\Program
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    X android-studio-dir = C:\Program
    X Android Studio not found at C:\Program
    • Try updating or re-installing Android Studio.
    • Consider removing your android-studio-dir setting by running:
      flutter config --android-studio-dir=

[!] VS Code
    • VS Code at C:\Users\Tamim Mostafa\AppData\Local\Programs\Microsoft VS Code
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[!] Connected device
    ! No devices available

! Doctor found issues in 4 categories.


问:
Escape ampersand in PL/SQL Developer
I'm trying a simple INSERT statement against an Oracle database.  One of the values is a VARCHAR2 field and the insert statement contains an ampersand.  How do I do this?  I've tried the following methods:

Escape the & as \& with set escape on

set scan off (this causes an ORA-00922 missing or invalid option error)

set define off (this causes an ORA-00922 missing or invalid option error)

Any other ideas?

答:
How I solved it is escaping the & with another &.

For example:

```<code>INSERT INTO Foo (Bar) VALUES ('Up && Away');
</code>```

Works nicely. Thanks for all the help

Title: Escape ampersand in PL/SQL Developer

Body:
How I solved it is escaping the & with another &.

For example:

INSERT INTO Foo (Bar) VALUES ('Up && Away');

Works nicely. Thanks for all the help


问:
Longest word in file
My program needs to print longest word which contains only letters from a file.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int checkString(const char s[]) {
  unsigned char c;
  while ((c = *s) && (isalpha(c) || isblank(c)))
    ++s;
  return *s == '\0';
}
int main() {
  char file_name[]="document.txt";
  FILE *fp = fopen(file_name, "r");
  char *largest = str;
  int largest_len = 0;
  while (fgets(file_name, 1000, fp) != NULL) {
    char *temp = strtok(file_name, " ");
    while (temp != NULL) {
      if (strlen(temp) > largest_len) {
        strcpy(largest, temp);
        largest_len = strlen(largest);
      }
      temp = strtok(NULL, "\",.,1,2,4,5,6,7,8,9 ");
    }
  }
  if(checkString(largest))
  printf("%s", largest);
  fclose(fp);
  return 0;
}
</code>```

In my code, if the largest word contains only letters it will be printed. How to modify this code to check next words if the largest doesn't contain only letters?

答:
There are a number of problems here:

you use the same buffer (str) for two different uses: as a read buffer and to store the longest word. If you find the largest word in the first line, the word will be erased when reading the second line. Furthemore, if you find a rather long word at the beginning of a line, the strings pointed to by largest and temp could overlap which leads to undefined behaviour => use a different array or strdup (and free) for largest

you only use the space as possible separator. You should wonder whether you should add tab and/or punctuations

once you have got a word you should ensure that it only contains valid letters before testing its length and ignore it if for example it contains digits.

if a single line can be longer than 1000 characters, you should wrap the end of the current part before the beginning of the next one for the possible case where a long word would be splitted there.

For additional corner case processing, you should specify what to do if a word contains illegal characters but only at one side. For example if . is not used as a word delimiter, a word with an embedded . like "a.b" should be ignored, but a terminating . should only be stripped (like "example." should become "example"

Title: Longest word in file

Body:
My program needs to print longest word which contains only letters from a file.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int checkString(const char s[]) {
  unsigned char c;
  while ((c = *s) && (isalpha(c) || isblank(c)))
    ++s;
  return *s == '\0';
}
int main() {
  char file_name[]="document.txt";
  FILE *fp = fopen(file_name, "r");
  char *largest = str;
  int largest_len = 0;
  while (fgets(file_name, 1000, fp) != NULL) {
    char *temp = strtok(file_name, " ");
    while (temp != NULL) {
      if (strlen(temp) > largest_len) {
        strcpy(largest, temp);
        largest_len = strlen(largest);
      }
      temp = strtok(NULL, "\",.,1,2,4,5,6,7,8,9 ");
    }
  }
  if(checkString(largest))
  printf("%s", largest);
  fclose(fp);
  return 0;
}

In my code, if the largest word contains only letters it will be printed. How to modify this code to check next words if the largest doesn't contain only letters?


问:
How to modify values in delimiter text file in unix
I have a huge file with delimited value with '~' example

abc~poi~123~jijda~123~abc

Requirement is to replace the values at 3rd occurrence (which is 123 in our case) to be replaced with 111.

I used the below command

awk -F '~' -v OFS='~' '$3 == "123" {$3 = "111"} 1 ' file.txt > Newfile.txt

this works for manually created file but when it the file was created using utf-8 encoding it doesn't work. Can some one help on this. Thanks!

答:
UTF-8 should be no problem.

```<code># SO71048003.awk
BEGIN {
  FS = OFS = "~"
  out = "Newfile.txt"
}

{
  if ($3 == "123")
    $3 = "111"
  print $0 > out
}
</code>```

Call:

```<code>awk -f SO71048003.awk file.txt
=> Newfile.txt with content:
abc~poi~111~jijda~123~abc
</code>```

Body:
UTF-8 should be no problem.

# SO71048003.awk
BEGIN {
  FS = OFS = "~"
  out = "Newfile.txt"
}

{
  if ($3 == "123")
    $3 = "111"
  print $0 > out
}

Call:

awk -f SO71048003.awk file.txt
=> Newfile.txt with content:
abc~poi~111~jijda~123~abc


问:
Apply function to a list of lists
I have a list of length 100. Each entry is itself a list containing 31 matrices with 10 rows and five columns.

```<code>>length(dati_fault)
[1] 100
</code>```
```<code>> length(dati_fault[[1]])
[1] 31
</code>```

I should get 100 averages of the variables summarizing the 31 matrices each element of the list

```<code>media_1<-list()
for(i in nrow(dati_fault)){
  for(j in nrow(dati_fault[[i]]))
  media_1[[i]]<-lapply(dati_fault, colMeans(j))

}
media_1
</code>```

But I get nothing because the media_1 list remains empty

答:
sample data

```<code>dati_fault <- lapply(1:100, function(x) {
  rep(list(matrix(sample(50, replace = T), nrow = 10, ncol = 5)), 31)
})
</code>```

case 1: calculate means for each matrix

```<code># to get the colMeans of each matrix (100 * 31 mean vectors)
lapply(dati_fault, function(x) lapply(x, colMeans))
</code>```

case 2: calculate the mean of all matrixes in same list

```<code># to get the colMeans of all 31 matrixes together (100 mean vectors)
lapply(dati_fault, function(x) colMeans(do.call(rbind, x)))
</code>```

Title: Apply function to a list of lists

Body:
I have a list of length 100. Each entry is itself a list containing 31 matrices with 10 rows and five columns.

>length(dati_fault)
[1] 100

> length(dati_fault[[1]])
[1] 31

I should get 100 averages of the variables summarizing the 31 matrices each element of the list

media_1<-list()
for(i in nrow(dati_fault)){
  for(j in nrow(dati_fault[[i]]))
  media_1[[i]]<-lapply(dati_fault, colMeans(j))

}
media_1

But I get nothing because the media_1 list remains empty

Body:
sample data

dati_fault <- lapply(1:100, function(x) {
  rep(list(matrix(sample(50, replace = T), nrow = 10, ncol = 5)), 31)
})

case 1: calculate means for each matrix

# to get the colMeans of each matrix (100 * 31 mean vectors)
lapply(dati_fault, function(x) lapply(x, colMeans))

case 2: calculate the mean of all matrixes in same list

# to get the colMeans of all 31 matrixes together (100 mean vectors)
lapply(dati_fault, function(x) colMeans(do.call(rbind, x)))


问:
PYSPARK - Unique Occurrence of a column + 1
What is the best approach to create a new column in df like the below Count column where it checks all columns in the START column and only increments the count by +1 when a new occurrence is seen.</p>
```<code>
+---------+--------+------+------+
|START    |KEY1    |Color  Count |
+---------+--------+------+------+
| 100     |  1     | White|  1   |
| 100     |  2     | Blue|   1   |
| 101     |  3     | Green|  2   |
+---------+--------+------+------+

</code>```

Body:
What is the best approach to create a new column in df like the below Count column where it checks all columns in the START column and only increments the count by +1 when a new occurrence is seen.

+---------+--------+------+------+
|START    |KEY1    |Color  Count |
+---------+--------+------+------+
| 100     |  1     | White|  1   |
| 100     |  2     | Blue|   1   |
| 101     |  3     | Green|  2   |
+---------+--------+------+------+

Body:
You can do this with dense_rank

df = pd.read_csv(StringIO("""
START,KEY1,Color
100,1,Blue
100,2,White
101,3,Green
102,3,Black
101,5,Brown
"""))

sparkDF = sql.createDataFrame(df)
sparkDF.show()

+-----+----+-----+
|START|KEY1|Color|
+-----+----+-----+
|  100|   1| Blue|
|  100|   2|White|
|  101|   3|Green|
|  102|   3|Black|
|  101|   5|Brown|
+-----+----+-----+

Dense Rank

window = Window.orderBy(F.col('START'))

sparkDF = sparkDF.withColumn('Count',F.dense_rank().over(window))

sparkDF.show()

+-----+----+-----+-----+
|START|KEY1|Color|Count|
+-----+----+-----+-----+
|  100|   1| Blue|    1|
|  100|   2|White|    1|
|  101|   3|Green|    2|
|  101|   5|Brown|    2|
|  102|   3|Black|    3|
+-----+----+-----+-----+

Dense Rank - SparkSQL

sparkDF.registerTempTable("TB1")

sql.sql("""
    SELECT
        START
        ,KEY1
        ,COLOR
        ,DENSE_RANK() OVER(ORDER BY START) as COUNT
    FROM TB1
""").show()

+-----+----+-----+-----+
|START|KEY1|Color|Count|
+-----+----+-----+-----+
|  100|   1| Blue|    1|
|  100|   2|White|    1|
|  101|   3|Green|    2|
|  101|   5|Brown|    2|
|  102|   3|Black|    3|
+-----+----+-----+-----+


问:
Quickblox Flutter Ios Undefined symbols for architecture arm64:
I am making a new flutter project adding quickblox in pubspec.yaml making pubg get pod install and then I am trying to run it in ios device. I always get this error. Am I missing something on ios that I need to add it in xcode? I havent worked with xcode a lot so my knowledge is limited.Thanks in advance

答:
looks like the issue is caused by QuickBlox: Undefined symbols for architecture arm64

I assume that when iOS devs release a new iOS SDK they will also update the one for Flutter.


问:
ASP.NET Storing global variables - accessible from every page
I am building a large application and I ususally use a simple session to store private  global information however as the application could be rather large I belive this could be a problem due to the amount of memory sessions it could have.

Is there a better way to store such variables?

For example, when the user logs in I want to store data about that user and display it where needed without having to query the database each time.

答:
Don't assume there will be a problem with the size of session state until you see such a problem and have tried to solve it. For instance, it's possible that, although the application as a whole may use a large amount of session state, that any given user may not use that much in the course of a session.

I's also possible that changing from the default session state provider to the SQL provider or state server provider would ease a memory issue.

You can use Cache, but Cache is application-wide. You would need to qualify Cache entries with the user id or session id: Cache[userID + ".MyCacheEntry"].

Do not, under any circumstances, use static variables to store this data. As suggested by your subject line, they are application-wide, not per-user.

OwnerDisplayName: HenryH

LastEditorDisplayName: Rich B

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: John Saunders


问:
why String.format 0.1d double value as exact 0.1 in java?
IEEE 754 float numbers are discret.

```<code>public class MyTest2 {
  public static void main(String[] args) {
    //about 1.00000001490116119384765625E-1 in IEEE-754
    float f = 0.1f;
    //about 1.00000000000000005551115123126E-1 in IEEE-754
    double d = 0.1d;
    System.out.println(String.format("double 0.1= %.30f", d));
    System.out.println(String.format("float 0.1 = %.15f", f));
    System.out.println(d+"");
  }
}
</code>```

See this code run live at IdeOne.com. Running in JDK8, output is

```<code>double 0.1= 0.100000000000000000000000000000
float 0.1 = 0.100000001490116
0.1
</code>```

The float value is printed as expected.
I expect double value 0.1d to be printed something like 1.000000000000000055511151231260. Why it print
all zeros in fraction part?

If I convert double variable d to string, it prints 0.1.

```<code>System.out.println(d+"");
</code>```

How does java convet the neartest float value of 0.1d (which is stroed as about 1.00000001490116119384765625E-1) to exact 0.1?

答:
If you see java ource code, you observe that

```<code>System.out.println(d+"");
</code>```

Will use something like this:

```<code>Double.toString(d)
</code>```

that in turn will call

```<code>FloatingDecimal.toJavaFormatString(d)
</code>```

String.format uses other mechanism. That is why you see this behaviour.

References:

https://www.thoughtco.com/concatenation-2034055

Java source code

Body:
IEEE 754 float numbers are discret.

public class MyTest2 {
  public static void main(String[] args) {
    //about 1.00000001490116119384765625E-1 in IEEE-754
    float f = 0.1f;
    //about 1.00000000000000005551115123126E-1 in IEEE-754
    double d = 0.1d;
    System.out.println(String.format("double 0.1= %.30f", d));
    System.out.println(String.format("float 0.1 = %.15f", f));
    System.out.println(d+"");
  }
}

See this code run live at IdeOne.com. Running in JDK8, output is

double 0.1= 0.100000000000000000000000000000
float 0.1 = 0.100000001490116
0.1

The float value is printed as expected.
I expect double value 0.1d to be printed something like 1.000000000000000055511151231260. Why it print
all zeros in fraction part?

If I convert double variable d to string, it prints 0.1.

System.out.println(d+"");

How does java convet the neartest float value of 0.1d (which is stroed as about 1.00000001490116119384765625E-1) to exact 0.1?

Body:
If you see java ource code, you observe that

System.out.println(d+"");

Will use something like this:

Double.toString(d)

that in turn will call

FloatingDecimal.toJavaFormatString(d)

String.format uses other mechanism. That is why you see this behaviour.

References:

https://www.thoughtco.com/concatenation-2034055

Java source code


问:
Android Spinner -- how to size to currently selected item?
It appears that a spinner is sized to the longest item given in its adapter.  This is a good behavior for the majority of cases, but it is undesirable in my particular case.

Is this possible to turn this off?  My guess is no, by looking at Spinner.onMeasure() in the source, but figured I'd ask.

答:
Here is more elegant almost one-liner solution:</p>
```<code>class ResizingArrayAdapter<T>(context: Context, @LayoutRes layoutResId: Int, @IdRes textViewResourceId: Int, objects: List<T>) :
    ArrayAdapter<T>(context, layoutResId, textViewResourceId, objects) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View =
        super.getView(if (parent is AdapterView<*>) parent.selectedItemPosition else position, convertView, parent)
}
</code>```

Body:
Here is more elegant almost one-liner solution:

class ResizingArrayAdapter<T>(context: Context, @LayoutRes layoutResId: Int, @IdRes textViewResourceId: Int, objects: List<T>) :
    ArrayAdapter<T>(context, layoutResId, textViewResourceId, objects) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View =
        super.getView(if (parent is AdapterView<*>) parent.selectedItemPosition else position, convertView, parent)
}


问:
head tag not appearing in view source : next:js
i have created my next js appp where i have implemented my head tag but when i check the view source  by right clicking i dont see my title and meta tags there  how can i achive that?

eventhough the head tag is missing in view souce  it can be found in inspect element

```<code><Head>
                <title> {itm.Name} - wixten </title>
                <link rel="shortcut icon" href="/wixten.png" />
                <meta
                  name="viewport"
                  content="initial-scale=1.0, width=device-width"
                />
                <meta name="description" content={itm.Summary} />
                <meta charSet="utf-8" />
                <meta property="og:title" content={itm.Name} />
                <meta property="og:description" content={itm.Summary} />
                <meta property="og:image" content="images/wixten.png" />
                <meta property="og:locale" key="og:locale" content="en_US" />
                <meta property="og:type" key="og:type" content="website" />
                <meta
                  property="og:url"
                  key="og:url"
                  content={`${baseurl}${itm._id}`}
                />
              </Head>
</code>```

i am adding full code in codesandbox

https://codesandbox.io/s/sweet-franklin-gpht9?file=/pages/index.js

the website i am faceing issue is this

https://wixten.com/query/61f4f5f9e41f700023c833c0

答:
You can use Next.js Head to set the title

```<code>import Head from "next/head";
const Home = () => {
  return (
    <div>
      <Head>
        <title>your title</title>
      </Head>
     // code
    </div>
  );
};
</code>```

Body:
i have created my next js appp where i have implemented my head tag but when i check the view source  by right clicking i dont see my title and meta tags there  how can i achive that?

eventhough the head tag is missing in view souce  it can be found in inspect element

                <title> {itm.Name} - wixten </title>
                <link rel="shortcut icon" href="/wixten.png" />
                <meta
                  name="viewport"
                  content="initial-scale=1.0, width=device-width"
                />
                <meta name="description" content={itm.Summary} />
                <meta charSet="utf-8" />
                <meta property="og:title" content={itm.Name} />
                <meta property="og:description" content={itm.Summary} />
                <meta property="og:image" content="images/wixten.png" />
                <meta property="og:locale" key="og:locale" content="en_US" />
                <meta property="og:type" key="og:type" content="website" />
                <meta
                  property="og:url"
                  key="og:url"
                  content={`${baseurl}${itm._id}`}
                />

i am adding full code in codesandbox

https://codesandbox.io/s/sweet-franklin-gpht9?file=/pages/index.js

the website i am faceing issue is this

https://wixten.com/query/61f4f5f9e41f700023c833c0

Body:
You can use Next.js Head to set the title

import Head from "next/head";
const Home = () => {
  return (
    <div>
      <Head>
        <title>your title</title>
      </Head>
     // code
    </div>
  );
};


答:
Basic accumulator:

result = []
acc = []
for x in l:
    acc.append(x)
    if x == 1:
        result.append(acc)
        acc = []
print(result)
```
<p>Using <code>groupby</code> and list comprehension:</p>
<pre class="lang-py prettyprint-override"><code>from itertools import groupby
[[*x, 1] for (is_valid, x) in groupby(l, key=lambda x: x != 1) if is_valid]
</code>```

Title: How to group list till the specific element occurs in python?

Body:
How to group list till the specific element occurs

l= [45, 22, 11, 5, 2, 1, 20, 10, 5, 2, 1, 40, 20, 10, 5, 2, 1, 26, 13, 6, 3, 1, 32, 16, 8, 4, 2, 1]

e=1

My code:

l=[45, 22, 11, 5, 2, 1, 20, 10, 5, 2, 1, 40, 20, 10, 5, 2, 1, 26, 13, 6, 3, 1, 32, 16, 8, 4, 2, 1]
e=1

l=[l[i:l.index(e)+1] for i in range(0,len(l))]
print(l)

My output:

[[45, 22, 11, 5, 2, 1], [22, 11, 5, 2, 1], [11, 5, 2, 1], [5, 2, 1], [2, 1], [1], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]

Needed output:

[[45, 22, 11, 5, 2, 1], [20, 10, 5, 2, 1], [40, 20, 10, 5, 2, 1], [26, 13, 6, 3, 1], [32, 16, 8, 4, 2, 1]]

What mistake i made?

Body:
Basic accumulator:

result = []
acc = []
for x in l:
    acc.append(x)
    if x == 1:
        result.append(acc)
        acc = []
print(result)

Using groupby and list comprehension:

from itertools import groupby
[[*x, 1] for (is_valid, x) in groupby(l, key=lambda x: x != 1) if is_valid]


问:
How to build a Loki server Docker image using Docker-compose
I have created a directory and mounted all the required files in each directory but when I try to create the docker image, It creates Promtail and Grafana but the LOKI wouldn't create. I get the error message below;

ERROR: for 9c35c983e8e4_cbxs_loki_1  Cannot start service loki: Mounts denied:
You can configure shared paths from Docker -> Preferences... -> Resources -> File Sharing.

I have mounted the files just as the order containers..
Please help

docker-compose.yml

Please see the file on the link below
https://docs.technotim.live/posts/grafana-loki/

```<code>version: "3"
networks:
  loki:
services:
  loki:
    image: grafana/loki:2.4.0
    ports:
      - "3100:3100"
    restart: unless-stopped
    command: -config.file=/etc/loki/loki-config.yml
    networks:
      - loki
  promtail:
    image: grafana/promtail:2.4.0
    volumes:
      - /var/log:/var/log
      - /Users/emma.egbu/CBCS/Promtail:/etc/promtail
    ports:
      - "1514:1514"
    restart: unless-stopped
    command: -config.file=/etc/promtail/promtail-config.yml
    networks:
      - loki
  grafana:
    image: grafana/grafana:latest
    user: "1000"
    volumes:
    - /Users/emma.egbu/CBCS/Grafana:/var/lib/grafana
    ports:
      - "3000:3000"
    restart: unless-stopped
    networks:
      - loki
</code>```

Thank you so much ! That was helpful...
For anyone going through the same struggle, here was what I did:
I went to edit the docker daemon config file
sudo nano /etc/docker/daemon.json - Probably you won't have write access so
sudo vi chmod 666  /etc/docker/daemon.json - This will allow u write
I pasted the file below

```<code>{
    "log-driver": "loki",
    "log-opts": {
        "loki-url": "http://localhost:3100/loki/api/v1/push",
        "loki-batch-size": "400"
    }
</code>```

Afterwards I restarted my docker then also
docker-compose up -d --force-recreate - to run up the docker-compose file

答: You have defined a volume mount for /var/log in your container, but most likely don't have this defined in Docker Desktop (under Docker -> Preferences... -> Resources -> File Sharing). You are probably best off removing this volume definition from the compose file, unless you actually want to read these logs on your Mac.

Body:
I have created a directory and mounted all the required files in each directory but when I try to create the docker image, It creates Promtail and Grafana but the LOKI wouldn't create. I get the error message below;

ERROR: for 9c35c983e8e4_cbxs_loki_1  Cannot start service loki: Mounts denied:
You can configure shared paths from Docker -> Preferences... -> Resources -> File Sharing.

I have mounted the files just as the order containers..
Please help

docker-compose.yml

Please see the file on the link below
https://docs.technotim.live/posts/grafana-loki/

version: "3"
networks:
  loki:
services:
  loki:
    image: grafana/loki:2.4.0
    ports:
      - "3100:3100"
    restart: unless-stopped
    command: -config.file=/etc/loki/loki-config.yml
    networks:
      - loki
  promtail:
    image: grafana/promtail:2.4.0
    volumes:
      - /var/log:/var/log
      - /Users/emma.egbu/CBCS/Promtail:/etc/promtail
    ports:
      - "1514:1514"
    restart: unless-stopped
    command: -config.file=/etc/promtail/promtail-config.yml
    networks:
      - loki
  grafana:
    image: grafana/grafana:latest
    user: "1000"
    volumes:
    - /Users/emma.egbu/CBCS/Grafana:/var/lib/grafana
    ports:
      - "3000:3000"
    restart: unless-stopped
    networks:
      - loki

Thank you so much ! That was helpful...
For anyone going through the same struggle, here was what I did:
I went to edit the docker daemon config file
sudo nano /etc/docker/daemon.json - Probably you won't have write access so
sudo vi chmod 666  /etc/docker/daemon.json - This will allow u write
I pasted the file below

{
    "log-driver": "loki",
    "log-opts": {
        "loki-url": "http://localhost:3100/loki/api/v1/push",
        "loki-batch-size": "400"
    }

Afterwards I restarted my docker then also
docker-compose up -d --force-recreate - to run up the docker-compose file


答:
Based on @solveMe asnwer (https://stackoverflow.com/a/39165933/641263) which I think is one of the most correct ways by utilising decimal context, I created following method which does the job exactly as needed:</p>
```<code>import decimal

def truncate_decimal(dec: Decimal, digits: int) -> decimal.Decimal:
    round_down_ctx = decimal.getcontext()
    round_down_ctx.rounding = decimal.ROUND_DOWN
    new_dec = round_down_ctx.create_decimal(dec)
    return round(new_dec, digits)
</code>```

Title: Truncate to three decimals in Python

Body:
How do I get 1324343032.324?

As you can see below, the following do not work:

>>1324343032.324325235 * 1000 / 1000
1324343032.3243253
>>int(1324343032.324325235 * 1000) / 1000.0
1324343032.3239999
>>round(int(1324343032.324325235 * 1000) / 1000.0,3)
1324343032.3239999
>>str(1324343032.3239999)
'1324343032.32'

Body:
Based on @solveMe asnwer (https://stackoverflow.com/a/39165933/641263) which I think is one of the most correct ways by utilising decimal context, I created following method which does the job exactly as needed:

import decimal

def truncate_decimal(dec: Decimal, digits: int) -> decimal.Decimal:
    round_down_ctx = decimal.getcontext()
    round_down_ctx.rounding = decimal.ROUND_DOWN
    new_dec = round_down_ctx.create_decimal(dec)
    return round(new_dec, digits)


问:
Why am I unable to programmatically close a Dialog on JavaFX?
This sample of code shows but doesn't close a javafx.scene.control.Dialog on JavaFx:

```<code>Dialog<Void> dialog = new Dialog<Void>();
dialog.show();
dialog.close();
</code>```

or

```<code>Dialog<Void> dialog = new Dialog<Void>();
dialog.show();
dialog.hide();
</code>```

Why?

答:
You can close the dialog by accessing the window its DialogPane is embedded in:

```<code>Window window = dialog.getDialogPane().getScene().getWindow();
window.setOnCloseRequest(event -> dialog.close());
</code>```

Now the dialog should close like every other window.

Body:
This sample of code shows but doesn't close a javafx.scene.control.Dialog on JavaFx:

Dialog<Void> dialog = new Dialog<Void>();
dialog.show();
dialog.close();

or

Dialog<Void> dialog = new Dialog<Void>();
dialog.show();
dialog.hide();

Why?

Body:
You can close the dialog by accessing the window its DialogPane is embedded in:

Window window = dialog.getDialogPane().getScene().getWindow();
window.setOnCloseRequest(event -> dialog.close());

Now the dialog should close like every other window.


问:
Insert trigger doesnt do what i want it to do
i made a trigger which should avoid inserting a record  in the  rental 'uitlening' table if the person has an overdue payment (Boete). Unfortunately it doesnt work and i cant find the reason why. 'Boete' is an attribute of another table than rental. Can someone help me?

CREATE TRIGGER [dbo].[Trigger_uitlening]
ON [dbo].[Uitlening]
FOR INSERT
AS
BEGIN
    DECLARE @Boete decimal(10, 2);

    SET @Boete = (SELECT Boete FROM Lid WHERE LidNr = (SELECT LidNr FROM inserted));
    IF @Boete = 0
    BEGIN
        INSERT INTO Uitlening
        SELECT *
        FROM inserted;
    END;
END;
```

答:
Assuming you just want to insert records into [Rental] of those users, who have [PaymentDue] <= 0. As you mentioned in your last comment:

no record in rental can be inserted if the person has a PaymentDue
thats greater than zero

And other records should be silently discarded as you didn't give a clear answer to @Larnu's question:

should that row be silently discarded, or should an error be thrown?

If above assumptions are true, your trigger would look like:

```<code>CREATE TRIGGER [dbo].[Trigger_uitlening]
ON [Rental]
INSTEAD OF INSERT
AS
BEGIN

    INSERT INTO [Rental] ( [DATE], [personID], [productID])
    SELECT i.[DATE], i.[personID], i.[productID]
    FROM INSERTED i
    INNER JOIN Person p ON i.[personID] = p.[personID]
    WHERE p.[PaymentDue] <= 0

END;
</code>```

Body:
Assuming you just want to insert records into [Rental] of those users, who have [PaymentDue] <= 0. As you mentioned in your last comment:

no record in rental can be inserted if the person has a PaymentDue
thats greater than zero

And other records should be silently discarded as you didn't give a clear answer to @Larnu's question:

should that row be silently discarded, or should an error be thrown?

If above assumptions are true, your trigger would look like:

CREATE TRIGGER [dbo].[Trigger_uitlening]
ON [Rental]
INSTEAD OF INSERT
AS
BEGIN

    INSERT INTO [Rental] ( [DATE], [personID], [productID])
    SELECT i.[DATE], i.[personID], i.[productID]
    FROM INSERTED i
    INNER JOIN Person p ON i.[personID] = p.[personID]
    WHERE p.[PaymentDue] <= 0

END;


问:
How to get webhook response data in .NET 6
I've created an endpoint in my API than I'm going to use to use the webhook of Uber.
It is my first time working with webhook, so :
How I'm going to get the response they will give me by using my endpoint ?

Here what they will send to me (the datas bellow are for test):

```<code>{
    "event_type": "orders.notification",
    "event_id": "c4d2261e-2779-4eb6-beb0-cb41235c751e",
    "event_time": 1427343990,
    "meta": {
        "resource_id": "153dd7f1-339d-4619-940c-418943c14636",
        "status": "pos",
        "user_id": "89dd9741-66b5-4bb4-b216-a813f3b21b4f"
    },
    "resource_href": "https://api.uber.com/v2/eats/order/153dd7f1-339d-4619-940c-418943c14636",
}
</code>```

And here my Api endpoint : (empty because I don't know how to handle it)

```<code>[HttpPost("/api/v1/.../delivery/hook")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(404)]
        public async Task<IActionResult> HookDelivery()
        {
            return Ok("hook reached");
        }
</code>```

答:
When webhook event occurs, the source application typically triggers an http POST. So the easiest way is to create a C# representation of the JSON object you provided and use it as an input param fro your API method. Something like this:

```<code>public class WebHookData
{
   public string EventType {get;set;}
   public string EventId {get;set;}
   etc....
}
</code>```

and then

```<code>    [HttpPost("/api/v1/.../delivery/hook")]
    [ProducesResponseType(200)]
    [ProducesResponseType(400)]
    [ProducesResponseType(404)]
    public async Task<IActionResult> ExistTerminalSerialNumber(WebHookData webHookData)
    {
        // do something with your input here
        return Ok("hook reached");
    }
</code>```

or something generic and have custom method that "converts" the incoming object to whatever you want it :

```<code>public async Task<IHttpActionResult> ExistTerminalSerialNumber([FromBody]JObject data)
{
    string eventType= data["event_type"].ToString();
        switch (eventType)
        {
            case "orders.notification":
                // do something
                return Ok();
            default:
                return BadRequest();
        }
}
</code>```

Body:
I've created an endpoint in my API than I'm going to use to use the webhook of Uber.
It is my first time working with webhook, so :
How I'm going to get the response they will give me by using my endpoint ?

Here what they will send to me (the datas bellow are for test):

{
    "event_type": "orders.notification",
    "event_id": "c4d2261e-2779-4eb6-beb0-cb41235c751e",
    "event_time": 1427343990,
    "meta": {
        "resource_id": "153dd7f1-339d-4619-940c-418943c14636",
        "status": "pos",
        "user_id": "89dd9741-66b5-4bb4-b216-a813f3b21b4f"
    },
    "resource_href": "https://api.uber.com/v2/eats/order/153dd7f1-339d-4619-940c-418943c14636",
}

And here my Api endpoint : (empty because I don't know how to handle it)

[HttpPost("/api/v1/.../delivery/hook")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(404)]
        public async Task<IActionResult> HookDelivery()
        {
            return Ok("hook reached");
        }

Body:
When webhook event occurs, the source application typically triggers an http POST. So the easiest way is to create a C# representation of the JSON object you provided and use it as an input param fro your API method. Something like this:

public class WebHookData
{
   public string EventType {get;set;}
   public string EventId {get;set;}
   etc....
}

and then

    [HttpPost("/api/v1/.../delivery/hook")]
    [ProducesResponseType(200)]
    [ProducesResponseType(400)]
    [ProducesResponseType(404)]
    public async Task<IActionResult> ExistTerminalSerialNumber(WebHookData webHookData)
    {
        // do something with your input here
        return Ok("hook reached");
    }

or something generic and have custom method that "converts" the incoming object to whatever you want it :

public async Task<IHttpActionResult> ExistTerminalSerialNumber([FromBody]JObject data)
{
    string eventType= data["event_type"].ToString();
        switch (eventType)
        {
            case "orders.notification":
                // do something
                return Ok();
            default:
                return BadRequest();
        }
}


问:
How to override CSS styles of Bootstrap for ".navlink"?
I'm not able to change the color of the ".navlink" to white in my html file.
Please help me to change the color of the ".navlink" to white.

       tent workshop
       <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

       </button>

                   Home

                   Contact

                   Products

```

答:
```<code><nav class="navbar navbar-light navbar-expand-md bg-light " >
</code>```

Try this . It will make your navigation bar background color to white

Body:
<nav class="navbar navbar-light navbar-expand-md bg-light " >

Try this . It will make your navigation bar background color to white


问:
Set specified grid lines in matplotlib without changing ticklabels
I try to plot a bar graph with a pre-defined number of grid lines like below. However, once I plot it, some yticklabels (A_2,A_3,etc) have not shown (only A_1, A_5, A_9,A_13,A_17 shown). I want to keep all ytick labels, but the gridline should be the same as x axis. Do you have any ideas to fix it?

```<code>import matplotlib.pyplot as plt
import numpy as np
mdict={"Column1":["A_"+str(i) for i in range(1,21)],"Value":[i for i in range(1,21)]}
# Create a dataframe
df=pd.DataFrame(mdict)
# Set plot params
fig, ax = plt.subplots(figsize=(12,8))

ax.barh(df.Column1,df.Value, color="darkgray",edgecolor="black", linewidth=0.5)
ax.set_xlabel("Numbers", fontsize=15)

# ax.set_yticklabels(list(df_cor.Country.values.tolist()), fontsize=15)
major_ticks_top=np.linspace(0,20,6)
minor_ticks_top=np.linspace(0,20,6)
ax.set_xticks(major_ticks_top)
ax.set_yticks(minor_ticks_top)
ax.grid(alpha=0.2,color="black")

plt.show()
</code>```

答:
I wouldn't explicitly set the ticks and labels but modify the output matplotlib generates:

```<code>import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.ticker import MultipleLocator

mdict={"Column1":["A_"+str(i) for i in range(1,21)],"Value":[i for i in range(1,21)]}
df=pd.DataFrame(mdict)

fig, ax = plt.subplots(figsize=(12,8))
ax.barh(df.Column1, df.Value, color="darkgray", edgecolor="black", linewidth=0.5)
ax.set_xlabel("Numbers", fontsize=15)

#set every fourth tick
n=4
ax.xaxis.set_major_locator(MultipleLocator(n))
ax.grid(alpha=0.2,color="black")
#remove unwanted gridlines on the y-axis
ygrd_lines = ax.get_ygridlines()
[grd_line.set_visible(False) for i, grd_line in enumerate(ygrd_lines) if i%n]

plt.show()
</code>```

Sample output:

Methods used:

MultipleLocator() setting ticks at defined intervals

.get_ygridlines returning gridlines as a list of Line2D objects for further modification

Body:
I try to plot a bar graph with a pre-defined number of grid lines like below. However, once I plot it, some yticklabels (A_2,A_3,etc) have not shown (only A_1, A_5, A_9,A_13,A_17 shown). I want to keep all ytick labels, but the gridline should be the same as x axis. Do you have any ideas to fix it?

import matplotlib.pyplot as plt
import numpy as np
mdict={"Column1":["A_"+str(i) for i in range(1,21)],"Value":[i for i in range(1,21)]}
# Create a dataframe
df=pd.DataFrame(mdict)
# Set plot params
fig, ax = plt.subplots(figsize=(12,8))

ax.barh(df.Column1,df.Value, color="darkgray",edgecolor="black", linewidth=0.5)
ax.set_xlabel("Numbers", fontsize=15)

# ax.set_yticklabels(list(df_cor.Country.values.tolist()), fontsize=15)
major_ticks_top=np.linspace(0,20,6)
minor_ticks_top=np.linspace(0,20,6)
ax.set_xticks(major_ticks_top)
ax.set_yticks(minor_ticks_top)
ax.grid(alpha=0.2,color="black")

plt.show()

Body:
I wouldn't explicitly set the ticks and labels but modify the output matplotlib generates:

import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.ticker import MultipleLocator

mdict={"Column1":["A_"+str(i) for i in range(1,21)],"Value":[i for i in range(1,21)]}
df=pd.DataFrame(mdict)

fig, ax = plt.subplots(figsize=(12,8))
ax.barh(df.Column1, df.Value, color="darkgray", edgecolor="black", linewidth=0.5)
ax.set_xlabel("Numbers", fontsize=15)

#set every fourth tick
n=4
ax.xaxis.set_major_locator(MultipleLocator(n))
ax.grid(alpha=0.2,color="black")
#remove unwanted gridlines on the y-axis
ygrd_lines = ax.get_ygridlines()
[grd_line.set_visible(False) for i, grd_line in enumerate(ygrd_lines) if i%n]

plt.show()

Sample output:

Methods used:

MultipleLocator() setting ticks at defined intervals

.get_ygridlines returning gridlines as a list of Line2D objects for further modification


问:
Combine csv files with same name from different subfolders in to one csv
I have three CSV files each for a particular filename for multiple files. Let's say there are a total 20 filenames so total 20* 3csv files in three different folders.

Folder A- 1001.CSV,1002.CSV,1003.CSV...

  Folder B-1001.CSV,1002.CSV,1003.CSV

  Folder C-1001.csv,1002.csv,1003.csv......

I want to get a single CSV file for each 1001,1002,1003,1004.....
So total 20csv files

How can I do this? Since the files are in different folders glob is not working(or I don't know how to)

答:
```<code>import os
import shutil
import glob
import pandas as pd

path = '/mypath/'

# rename files
count = 1

for root, dirs, files in os.walk(path):
    for i in files:
        if i == 'whatever.csv':
            os.rename(os.path.join(root, i), os.path.join(root, "whatever" + str(count) + ".csv"))
            count += 1

# delete unwanted files
main_dir = path

folders = os.listdir(main_dir)

for (dirname, dirs, files) in os.walk(main_dir):
   for file in files:
      if file.startswith('dontwant'):
          source_file = os.path.join(dirname, file)
          os.remove(source_file)

# copy files to dir
for root, dirs, files in os.walk(path):  # replace the . with your starting directory
   for file in files:
       if file.endswith('.csv'):
          path_file = os.path.join(root,file)
          shutil.copy2(path_file,path) # change you destination dir

# combine files
os.chdir(path)
extension = 'csv'
all_filenames = [i for i in glob.glob('*.{}'.format(extension))]
combined_csv = pd.concat([pd.read_csv(f) for f in all_filenames ])
combined_csv.to_csv( "combined_csv.csv", index=False, encoding='utf-8-sig')
</code>```


问:
How to do performance testing with key-cloak authentication in Jmeter
I try to do performance testing but particular site have enable key-cloak authentication.any suggesstions</p>

答:
It's just a matter of correlation, the exact steps will be different for OpenID Connect and SAML so you need to determine which client protocol is being used in that particular Keycloak instance.

In order to get help with correlating individual parameters you will need to provide the previous response and the format of the next request so we could come up with the relevant instructions for JMeter Post-Processors setup.


问:
How to Convert a Map<String, List<List<String>>> to Map<String, List<String>>
```<code> Map<String, List<String>> map1 = new HashMap<>();
  Map<String, List<String>> map2 = new HashMap<>();
   map1.put("a", Lists.newArrayList("1","123"));
    map1.put("b", Lists.newArrayList("2","223"));

    map2.put("c", Lists.newArrayList("11","1123"));
    map2.put("a", Lists.newArrayList("22","2223"));
  Map<String, List<List<String>>> collect = Stream.of(map1, map2)
            .flatMap(m -> m.entrySet().stream())
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue,
                            Collectors.toList())
            ));
 System.out.println(collect);
</code>```

print: {a=[[1, 123], [22, 2223, 1, 123]], b=[[2, 223]], c=[[11, 1123]]}

how can print:
{a=[22, 2223, 1, 123], b=[2, 223], c=[11, 1123]}

答:
I wouldn't create List<List<String>>s in the first place

```<code>Map<String, List<String>> map1 = new HashMap<>();
Map<String, List<String>> map2 = new HashMap<>();
map1.put("a", Lists.newArrayList("1","123"));
map1.put("b", Lists.newArrayList("2","223"));

map2.put("c", Lists.newArrayList("11","1123"));
map2.put("a", Lists.newArrayList("22","2223"));

Map<String, List<String>> collect = Stream.of(map1, map2)
        .flatMap(m -> m.entrySet().stream())
        .collect(Collectors.groupingBy(Map.Entry::getKey,
                 Collectors.flatMapping(e -> e.getValue().stream(), Collectors.toList())));
</code>```

Body:
 Map<String, List<String>> map1 = new HashMap<>();
  Map<String, List<String>> map2 = new HashMap<>();
   map1.put("a", Lists.newArrayList("1","123"));
    map1.put("b", Lists.newArrayList("2","223"));

    map2.put("c", Lists.newArrayList("11","1123"));
    map2.put("a", Lists.newArrayList("22","2223"));
  Map<String, List<List<String>>> collect = Stream.of(map1, map2)
            .flatMap(m -> m.entrySet().stream())
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue,
                            Collectors.toList())
            ));
 System.out.println(collect);

print: {a=[[1, 123], [22, 2223, 1, 123]], b=[[2, 223]], c=[[11, 1123]]}

how can print:
{a=[22, 2223, 1, 123], b=[2, 223], c=[11, 1123]}

Body:
I wouldn't create List<List<String>>s in the first place

Map<String, List<String>> map1 = new HashMap<>();
Map<String, List<String>> map2 = new HashMap<>();
map1.put("a", Lists.newArrayList("1","123"));
map1.put("b", Lists.newArrayList("2","223"));

map2.put("c", Lists.newArrayList("11","1123"));
map2.put("a", Lists.newArrayList("22","2223"));

Map<String, List<String>> collect = Stream.of(map1, map2)
        .flatMap(m -> m.entrySet().stream())
        .collect(Collectors.groupingBy(Map.Entry::getKey,
                 Collectors.flatMapping(e -> e.getValue().stream(), Collectors.toList())));


问:
Different ways to create an empty list
I want to create an empty list and append some values inside this list. So far I know that if I want to create and empty list I can do it either like this:

```<code>list1 = []
</code>```

or like this:

```<code>list1 = list()
</code>```

(My apologies if there is another way that currently I don't know)

My question at this point is if there is a difference between those two ways to create a list; in terms of efficiency for example.

Thank you in advance for your help.

答:
The literal syntax, list1 = [], is slightly faster. There's been a handful of threads on this worth reading:

[] and {} vs list() and dict(), which is better?

Why is [] faster than list()?

Title: Different ways to create an empty list

Body:
I want to create an empty list and append some values inside this list. So far I know that if I want to create and empty list I can do it either like this:

list1 = []

or like this:

list1 = list()

(My apologies if there is another way that currently I don't know)

My question at this point is if there is a difference between those two ways to create a list; in terms of efficiency for example.

Thank you in advance for your help.


问:
How to avoid call observe() twice?
I have an observer inside a function. I call this function firstly in my activity's onCreate() and it works fine.  After that when I call this function again, the code inside my observer is called twice. How can I prevent this behaviour?

Here is my function with observer

```<code>private lateinit var word: String

fun addViews() {

    viewModel.getQuestion()

    viewModel.questionResponse.observe(this, { it ->
        this.word = it.data.word

            createAnswerTextView(this.word.length)

        }
    })
}
</code>```

EDIT:

What I wanted to do is refreshing the layout by removing and adding views in these steps.

Creating text views as long as word length. ( addViews()
does it for me )

Removing those views.

Creating text views again as long as new word length. (
addViews() does it for me )

I couldn't create the observer only once in activity's onCreate() method. Because I needed to use addViews function and its observer multi times.

viewModel.questionResponse.removeObservers(this) didn't work too.

But adding viewModel.questionResponse = MutableLiveData() in function where I remove my text views and clear value of my properties solved my problem.

答:
after getting data you should call
viewModel?.getData()?.removeObservers(this)</p>

Title: How to avoid call observe() twice?

Body:
I have an observer inside a function. I call this function firstly in my activity's onCreate() and it works fine.  After that when I call this function again, the code inside my observer is called twice. How can I prevent this behaviour?

Here is my function with observer

private lateinit var word: String

fun addViews() {

    viewModel.getQuestion()

    viewModel.questionResponse.observe(this, { it ->
        this.word = it.data.word

            createAnswerTextView(this.word.length)

        }
    })
}

EDIT:

What I wanted to do is refreshing the layout by removing and adding views in these steps.

Creating text views as long as word length. ( addViews()
does it for me )

Removing those views.

Creating text views again as long as new word length. (
addViews() does it for me )

I couldn't create the observer only once in activity's onCreate() method. Because I needed to use addViews function and its observer multi times.

viewModel.questionResponse.removeObservers(this) didn't work too.

But adding viewModel.questionResponse = MutableLiveData() in function where I remove my text views and clear value of my properties solved my problem.