问:
How to simulate dark mode on iOS Xcode Swift Playground
Similar to How to use dark mode in simulator iOS 13? and How to enable Dark Mode on the Simulator?, how can you enable dark mode in the Xcode Swift Playground Live View?</p>

答:
You can test it in any view using overrideUserInterfaceStyle

As an example, you can paste this code in a playground to check it (tested in Xcode 11.3.1):

```<code>import Foundation
import PlaygroundSupport

extension UIColor {

    static var primary: UIColor {
        UIColor { trait -> UIColor in
            return trait.userInterfaceStyle == .light ? .black : .white
        }
    }

    static var secondary: UIColor {
        UIColor { trait -> UIColor in
            return trait.userInterfaceStyle == .light ? .white : .black
        }
    }
}

class DarkModeTestView: UIView {

    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 375, height: 300))

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = .secondary

        label.text = "This text should be displayed in black for light mode and white for dark mode"
        label.textColor = .primary
        label.numberOfLines = 0

        addSubview(label)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

let testView = DarkModeTestView(frame: CGRect(x: 0, y: 0, width: 375, height: 300))
testView.overrideUserInterfaceStyle = .dark // Change here .light or .dark

PlaygroundPage.current.liveView = testView
</code>```

Body:
You can test it in any view using overrideUserInterfaceStyle

As an example, you can paste this code in a playground to check it (tested in Xcode 11.3.1):

import Foundation
import PlaygroundSupport

extension UIColor {

    static var primary: UIColor {
        UIColor { trait -> UIColor in
            return trait.userInterfaceStyle == .light ? .black : .white
        }
    }

    static var secondary: UIColor {
        UIColor { trait -> UIColor in
            return trait.userInterfaceStyle == .light ? .white : .black
        }
    }
}

class DarkModeTestView: UIView {

    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 375, height: 300))

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = .secondary

        label.text = "This text should be displayed in black for light mode and white for dark mode"
        label.textColor = .primary
        label.numberOfLines = 0

        addSubview(label)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

let testView = DarkModeTestView(frame: CGRect(x: 0, y: 0, width: 375, height: 300))
testView.overrideUserInterfaceStyle = .dark // Change here .light or .dark

PlaygroundPage.current.liveView = testView


来源: stackexchange

问:
The URL of the index.html file in my new Google bucket includes the google storage path
I made a new bucket in google cloud. Set the access permissions for allusers to view, and uploaded the website folders and files.

The url www.sustainabledebtrecovery.com doesn't work in my browser, so I checked the address of index.html in google cloud, and it this:

https://storage.cloud.google.com/www.sustainabledebtrecovery.com/index.html

Can anybody please help me... How do I get www.sustainabledebtrecovery.com to work on its own?

Thank you very much.

答:
You should follow this documentation on how to set up DNS records properly (screenshot in Google Domains and have a look at this one on how to set up static website on GCP buckets.

But first make sure your CNAME record is pointing to the c.storage.googleapis.com.

Right now your DNS points to the other provider you mentioned:

```<code>    dig www.sustainabledebtrecovery.com

; <<>> DiG 9.11.3-1ubuntu1.12-Ubuntu <<>> www.sustainabledebtrecovery.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47899
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;www.sustainabledebtrecovery.com. IN    A

;; ANSWER SECTION:
www.sustainabledebtrecovery.com. 6181 IN CNAME  sustainabledebtrecovery.com.
sustainabledebtrecovery.com. 6225 IN    A       68.66.226.78
</code>```

Proper configuration should look like this:

You don't need A record in this case.

When you change back your CNAME records please check with those tools: MX Toolbox and DNS Checker to ensure they propagated properly.

Next - make sure your bucket name matches your domain name - in your case www.sustainabledebtrecovery.com

Upload the files, set the permissions (at bucket level if you want the users to be able to access all files in it or object level to have more control over who can access what)

If everything is set up right your site should be working and accessible for everyone.

ContentLicense: CC BY-SA 4.0

Body:
You should follow this documentation on how to set up DNS records properly (screenshot in Google Domains and have a look at this one on how to set up static website on GCP buckets.

But first make sure your CNAME record is pointing to the c.storage.googleapis.com.

Right now your DNS points to the other provider you mentioned:

    dig www.sustainabledebtrecovery.com

; <<>> DiG 9.11.3-1ubuntu1.12-Ubuntu <<>> www.sustainabledebtrecovery.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47899
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;www.sustainabledebtrecovery.com. IN    A

;; ANSWER SECTION:
www.sustainabledebtrecovery.com. 6181 IN CNAME  sustainabledebtrecovery.com.
sustainabledebtrecovery.com. 6225 IN    A       68.66.226.78

Proper configuration should look like this:

You don't need A record in this case.

When you change back your CNAME records please check with those tools: MX Toolbox and DNS Checker to ensure they propagated properly.

Next - make sure your bucket name matches your domain name - in your case www.sustainabledebtrecovery.com

Upload the files, set the permissions (at bucket level if you want the users to be able to access all files in it or object level to have more control over who can access what)

If everything is set up right your site should be working and accessible for everyone.


问:
Kendo grid hierarchy data not displaying
I have an MVVM application using Kendo Grid, and I want to display hierarchy (nested grid). I am trying to replicate this example but I am not able to display the hierarchy data. How can I get the hierarchy records to display?

cshtml code:

```<code><div id="custOrderGrid"
        data-role="grid"
        data-resizable="false"
        data-navigatable="true"
        data-editable="true"
        data-pageable="false"
        data-scrollable="true"
        onscroll="true"
        data-detail-template="child-template"
        data-columns="[
                { 'field': 'OrderID', 'title': '<b>Order #', 'width': 65 },
                { 'field': 'LineNo', 'title': '<b>Line Number', 'width': 65 },
                { 'field': 'ItemNo', 'title': '<b>Item Number', 'width': 65 },
                { 'field': 'Desc', 'title': '<b>Description', 'width': 150 }
            ]"
        data-bind="source: orderSearchResults"
        style="height: 55%">
</div>

<script id="child-template" type="text/x-kendo-template">
    <div data-role="grid"
         data-bind="source: obj2"
         data-columns="[
    { field: 'name' },
    { field: 'oid' }
    ]"></div>
</script>
</code>```

typescript code:

```<code>orderSearchResults = new kendo.data.DataSource({
  schema: {
    model: {
      id: "OrderID",
      fields: {
        LineNo: { type: "string" },
        ItemNo: { type: "string" },
        Description: { type: "string" }
      }
    }
  },
  data: [
    {
      OrderID: "L44ZX4",
      LineNo: "15",
      ItemNo: "*X1WCJH",
      Description: "CDF9X2XSB",
      obj2: [
        {
          name: 'a1',
          oid: 1
        },
        {
          name: 'b1',
          oid: 2
        },
        {
          name: 'c1',
          oid: 3
        }
      ]
    }
  ]
});
</code>```

The yellow highlighted section is where the Hierarchy data should be displayed.

答:
Here's a link to what I've tried.

I thought the hierarchy grid wasn't created but actually, it is created nested within the main grid.  Your screenshot doesn't display the right part of the grid, but you probably have 2 scroll arrows on the right side of the grid that would allow you to see the sub grid content.

Removing the style="height: 55%" fixed the problem.

N.B. I'm not sure if I reproduced you problem correctly...  in your screen shoot you do have another main record displayed so the subgrid would normally be displayed between those 2 main records.  If the height style was the reel problem, then the second main record would also be hidden.  If I'm wrong, feel free to update my example to reproduce your issue.

Body:
I have an MVVM application using Kendo Grid, and I want to display hierarchy (nested grid). I am trying to replicate this example but I am not able to display the hierarchy data. How can I get the hierarchy records to display?

cshtml code:

<div id="custOrderGrid"
        data-role="grid"
        data-resizable="false"
        data-navigatable="true"
        data-editable="true"
        data-pageable="false"
        data-scrollable="true"
        onscroll="true"
        data-detail-template="child-template"
        data-columns="[
                { 'field': 'OrderID', 'title': 'Order #', 'width': 65 },
                { 'field': 'LineNo', 'title': 'Line Number', 'width': 65 },
                { 'field': 'ItemNo', 'title': 'Item Number', 'width': 65 },
                { 'field': 'Desc', 'title': 'Description', 'width': 150 }
            ]"
        data-bind="source: orderSearchResults"
        style="height: 55%">

typescript code:

orderSearchResults = new kendo.data.DataSource({
  schema: {
    model: {
      id: "OrderID",
      fields: {
        LineNo: { type: "string" },
        ItemNo: { type: "string" },
        Description: { type: "string" }
      }
    }
  },
  data: [
    {
      OrderID: "L44ZX4",
      LineNo: "15",
      ItemNo: "*X1WCJH",
      Description: "CDF9X2XSB",
      obj2: [
        {
          name: 'a1',
          oid: 1
        },
        {
          name: 'b1',
          oid: 2
        },
        {
          name: 'c1',
          oid: 3
        }
      ]
    }
  ]
});

The yellow highlighted section is where the Hierarchy data should be displayed.


问:
Hadamard pattern question
I am writing a program that displays Hadamard pattern using recursion.

A 1-by-1 Hadamard pattern is a single black square. In general a 2N-by-2N Hadamard pattern is obtained by aligning 4 copies of the N-by-N pattern in the form of a 2-by-2 grid, and then inverting the colors of all the squares in the lower right N-by-N copy.

I would like to produce the same picture as  this one

My code is:

```<code>import java.awt.*;

import javax.swing.*;

@SuppressWarnings("serial")
public class Hadamard extends JPanel{

@SuppressWarnings("unused")
private void hadamard(Graphics g, int n, int x, int y, int width, int height){

    if(n == 0){

        g.fillRect(x/2, y/2, width, height);
        return;
    }
    else{

        hadamard(g, n-1, x, y, width/2, height/2);

        hadamard(g, n-1, x + width, y,  width/2, height/2);

        hadamard(g, n-1, x, y + height, width/2, height/2);

        g.setColor(Color.WHITE);
        hadamard(g, n-1, x + width, y + height, width/2, height/2);
        g.setColor(Color.BLACK);

    }
}

protected void paintComponent(Graphics g){
    super.paintComponent(g);

    hadamard(g, 2, getWidth() / 2, getHeight() / 2, getWidth() / 2, getHeight() / 2);

}

public static void main(String[] args) {

    Hadamard panel = new Hadamard();
    JFrame app = new JFrame();

    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    app.add(panel);
    app.setSize(516, 538);
    app.setVisible(true);

}
</code>```

}

I don't change properly the colors of the squares in the lower right corner. I've been stuck at this step for the last a couple of hours and am hoping someone would give me an idea how to do it correctly because I don't know.

Thank you in advance.
Nath

答:
Your code is not inverting the lower-right quadrant, it's simply forcing it to be white.

I would say that the best solution is to add an extra parameter to your recursive method (let's call it b), whose value can be true or false.  You can then recurse as:

```<code>    hadamard(g, n-1, x, y, width/2, height/2, b);
    hadamard(g, n-1, x + width, y,  width/2, height/2, b);
    hadamard(g, n-1, x, y + height, width/2, height/2, b);
    hadamard(g, n-1, x + width, y + height, width/2, height/2, !b);
</code>```

Then when you get to the fillRect calls, choose white or black depending on the value of b.

ContentLicense: CC BY-SA 3.0

Title: Hadamard pattern question

Body:
I am writing a program that displays Hadamard pattern using recursion.

A 1-by-1 Hadamard pattern is a single black square. In general a 2N-by-2N Hadamard pattern is obtained by aligning 4 copies of the N-by-N pattern in the form of a 2-by-2 grid, and then inverting the colors of all the squares in the lower right N-by-N copy.

I would like to produce the same picture as  this one

My code is:

import java.awt.*;

import javax.swing.*;

@SuppressWarnings("serial")
public class Hadamard extends JPanel{

@SuppressWarnings("unused")
private void hadamard(Graphics g, int n, int x, int y, int width, int height){

    if(n == 0){

        g.fillRect(x/2, y/2, width, height);
        return;
    }
    else{

        hadamard(g, n-1, x, y, width/2, height/2);

        hadamard(g, n-1, x + width, y,  width/2, height/2);

        hadamard(g, n-1, x, y + height, width/2, height/2);

        g.setColor(Color.WHITE);
        hadamard(g, n-1, x + width, y + height, width/2, height/2);
        g.setColor(Color.BLACK);

    }
}

protected void paintComponent(Graphics g){
    super.paintComponent(g);

    hadamard(g, 2, getWidth() / 2, getHeight() / 2, getWidth() / 2, getHeight() / 2);

}

public static void main(String[] args) {

    Hadamard panel = new Hadamard();
    JFrame app = new JFrame();

    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    app.add(panel);
    app.setSize(516, 538);
    app.setVisible(true);

}

}

I don't change properly the colors of the squares in the lower right corner. I've been stuck at this step for the last a couple of hours and am hoping someone would give me an idea how to do it correctly because I don't know.

Thank you in advance.
Nath

Body:
Your code is not inverting the lower-right quadrant, it's simply forcing it to be white.

I would say that the best solution is to add an extra parameter to your recursive method (let's call it b), whose value can be true or false.  You can then recurse as:

    hadamard(g, n-1, x, y, width/2, height/2, b);
    hadamard(g, n-1, x + width, y,  width/2, height/2, b);
    hadamard(g, n-1, x, y + height, width/2, height/2, b);
    hadamard(g, n-1, x + width, y + height, width/2, height/2, !b);

Then when you get to the fillRect calls, choose white or black depending on the value of b.


问:
Split IP addresses in a CSV Cell
I am struggling in importing from a CSV file.  This file has and "IP Address" field however the program that generates the form (which I have not control over) can create a CSV file like this

hostname,IP Address,Site
server1,192.168.1.10,florida
Server2,192.168.10.100
192.168.10.101
8.8.8.8,Alaska
server3,10.10.10.10,Ohio

I import the csv into variable
$sessions=import-csv -path $Path

In a foreach ($session in $sessions) loop I try to get the IP's and split them with the following:

$IPs=$session."IP Address" -split "`r`n"

However when I check the $IPs it does not seem to be an array as for server 2 $IPs shows

```
PS c:\$IPS
 192.168.10.100
192.168.10.101
8.8.8.8
PS c:\$IPs.count
1
```

What can I do to split the Cell in to an array so I can process the IP's found in a foreach ($IP in $IPs) loop

答:
Using "`r`n" to split on newlines will fail if the input doesn't use carriage returns.

Either make the carriage return char optional in the regex pattern:

```<code>$IPs = $session."IP Address" -split "`r?`n"
</code>```

Or use -split in unary mode, which will trim the input string and split on consecutive whitespace sequences:

```<code>$IPs = -split $session."IP Address"
</code>```

Title: Split IP addresses in a CSV Cell

Body:
I am struggling in importing from a CSV file.  This file has and "IP Address" field however the program that generates the form (which I have not control over) can create a CSV file like this

hostname,IP Address,Site
server1,192.168.1.10,florida
Server2,192.168.10.100
192.168.10.101
8.8.8.8,Alaska
server3,10.10.10.10,Ohio

I import the csv into variable
$sessions=import-csv -path $Path

In a foreach ($session in $sessions) loop I try to get the IP's and split them with the following:

$IPs=$session."IP Address" -split "`r`n"

However when I check the $IPs it does not seem to be an array as for server 2 $IPs shows

PS c:\$IPS
 192.168.10.100
192.168.10.101
8.8.8.8
PS c:\$IPs.count
1

What can I do to split the Cell in to an array so I can process the IP's found in a foreach ($IP in $IPs) loop

Body:
Using "`r`n" to split on newlines will fail if the input doesn't use carriage returns.

Either make the carriage return char optional in the regex pattern:

$IPs = $session."IP Address" -split "`r?`n"

Or use -split in unary mode, which will trim the input string and split on consecutive whitespace sequences:

$IPs = -split $session."IP Address"


问:
How to delete last element in array and put new in front?
I have a question concerning Java. I started up new to Java and my google search brought many results but non was the final help.
I created a class to track historical information. I have different values for different days and need to update them un a regular basis. I want to keep track of the last 30 days and created an array with 30 elements. When I call my 'shift' function I want to drop the last n elements and put zeros in front. Here is a minial example for 5 days:

```<code>public class Testclass {

    private int[] histInfo;

    public Element()
    {
        this.histInfo = new int[5];
    }

    public void shift_histInfo(long m)
    {
        //do magic
    }
}
</code>```

What I want shift to do is

```<code>INPUT:
histInfo = [50,21,1,45,901]

OPERATION:
shift_histInfo(2);

RESULT:
histInfo = [0,0,50,21,1]
</code>```

I am thankfull for every kind of help you can support as well for thought-provoking impulses if you think that there is a way more elegant or efficient way.

Best :-)

答:
For constraints that you wanted, although I did initialise the data in the same method instead of Element(). I don't know why the parameter is of type long so I left it and made an int local variable.

All it does is copy the index value over to the new array starting at m then increments/iterates until the end of the array.

You can also make the method return type int[] and then simply return changedInfo array. Instead of histInfo = changedInfo.clone();

```<code>private int[] histInfo;

    public void shift_histInfo(long m) {
        int n = (int) m;
        this.histInfo = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15};

        int length = this.histInfo.length;
        int[] changedInfo = new int[length];

        if (length - n >= 0) System.arraycopy(histInfo, 0, changedInfo, n + 0, length - n); //Edit: shortened to one line.

        histInfo = changedInfo.clone();
        System.out.println("Remove: " + n + " - " + Arrays.toString(changedInfo) + "\n");

    }
    public static void main(String[] args) {
        Main main = new Main();
        main.shift_histInfo(0);
        main.shift_histInfo(30);
        main.shift_histInfo(1);
        main.shift_histInfo(15);
        main.shift_histInfo(29);
    }
</code>```

println:

```<code>Remove: 0 - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Remove: 30 - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Remove: 1 - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Remove: 15 - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Remove: 29 - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
</code>```

Body:
I have a question concerning Java. I started up new to Java and my google search brought many results but non was the final help.
I created a class to track historical information. I have different values for different days and need to update them un a regular basis. I want to keep track of the last 30 days and created an array with 30 elements. When I call my 'shift' function I want to drop the last n elements and put zeros in front. Here is a minial example for 5 days:

public class Testclass {

    private int[] histInfo;

    public Element()
    {
        this.histInfo = new int[5];
    }

    public void shift_histInfo(long m)
    {
        //do magic
    }
}

What I want shift to do is

INPUT:
histInfo = [50,21,1,45,901]

OPERATION:
shift_histInfo(2);

RESULT:
histInfo = [0,0,50,21,1]

I am thankfull for every kind of help you can support as well for thought-provoking impulses if you think that there is a way more elegant or efficient way.

Best :-)

Body:
For constraints that you wanted, although I did initialise the data in the same method instead of Element(). I don't know why the parameter is of type long so I left it and made an int local variable.

All it does is copy the index value over to the new array starting at m then increments/iterates until the end of the array.

You can also make the method return type int[] and then simply return changedInfo array. Instead of histInfo = changedInfo.clone();

private int[] histInfo;

    public void shift_histInfo(long m) {
        int n = (int) m;
        this.histInfo = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15};

        int length = this.histInfo.length;
        int[] changedInfo = new int[length];

        if (length - n >= 0) System.arraycopy(histInfo, 0, changedInfo, n + 0, length - n); //Edit: shortened to one line.

        histInfo = changedInfo.clone();
        System.out.println("Remove: " + n + " - " + Arrays.toString(changedInfo) + "\n");

    }
    public static void main(String[] args) {
        Main main = new Main();
        main.shift_histInfo(0);
        main.shift_histInfo(30);
        main.shift_histInfo(1);
        main.shift_histInfo(15);
        main.shift_histInfo(29);
    }

println:

Remove: 0 - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Remove: 30 - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Remove: 1 - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Remove: 15 - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Remove: 29 - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]


问:
Trouble installing Pygame
I am having difficulty installing Pygame on Python 3.8 (MacOS)

When I attempt to run install hg+http://bitbucket.org/pygame/pygame, I get the following error message:

```<code>Installing collected packages: pygame
 Running setup.py install for pygame ... error
 ERROR: Command errored out with exit status 1:
 command:
  ....

        36 warnings and 8 errors generated.
        error: command 'gcc' failed with exit status 1
        ----------------------------------------
    ERROR: Command errored out with exit status 1:.
</code>```

When I attempt to import Pygame into my project I get ModuleNotFoundError (as expected).

Thank you in advance for any advice on how to resolve this issue!

答:
If you have pip installed (I think macos comes with it) you can run:

pip install pygame

If you still can't import try

pip3 install pygame

Title: Trouble installing Pygame

Body:
I am having difficulty installing Pygame on Python 3.8 (MacOS)

When I attempt to run install hg+http://bitbucket.org/pygame/pygame, I get the following error message:

Installing collected packages: pygame
 Running setup.py install for pygame ... error
 ERROR: Command errored out with exit status 1:
 command:
  ....

        36 warnings and 8 errors generated.
        error: command 'gcc' failed with exit status 1
        ----------------------------------------
    ERROR: Command errored out with exit status 1:.

When I attempt to import Pygame into my project I get ModuleNotFoundError (as expected).

Thank you in advance for any advice on how to resolve this issue!


问:
regex to add a limit of 10 digits with decimal value having no limit
I want to apply a validation where I need a limit of 10 digits on value but the value after decimal has no limit.

Like this
1000000000.2121
The value before decimal should be less than 10 digits.
I am trying this regex
^(10|\d)(\.\d{1,2})?$
 But By this, I only add decimal digits with a limit of two. How can I achieve this?

答:
If the total should be no more than 10, and the digit can not start with a comma, you could assert not 11 digits and keep the \d+ to match 1 or more digits.

```<code>^(?!(?:[^\d\r\n]*\d){11})\d+(?:\.\d+)?$
</code>```

Explanation

^ Start of string

(?! Negative lookahead, assert that what is on the right is not

(?:[^\d\r\n]*\d){11} Match 11 times any char except a newline followed by a digit

) Close lookahead.

\d+ Match 1+ digits

(?:\.\d+)? Optionally match a dot and 1+ digits

$ End of string

Regex demo

Body:
If the total should be no more than 10, and the digit can not start with a comma, you could assert not 11 digits and keep the \d+ to match 1 or more digits.

^(?!(?:[^\d\r\n]*\d){11})\d+(?:\.\d+)?$

Explanation

^ Start of string

(?! Negative lookahead, assert that what is on the right is not

(?:[^\d\r\n]*\d){11} Match 11 times any char except a newline followed by a digit

) Close lookahead.

\d+ Match 1+ digits

(?:\.\d+)? Optionally match a dot and 1+ digits

$ End of string

Regex demo


问:
when using BouncyCastle How to customize keyManagerFactory
i manage to make a https request with BouncyCastleProvider in order to fit "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8" cipher suite

```<code>  Security.addProvider(new BouncyCastleProvider());
            Security.addProvider(new BouncyCastleJsseProvider());
            SSLContext sslContext = SSLContext.getInstance("TLS", BouncyCastleJsseProvider.PROVIDER_NAME);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                    "PKIX"
                    ,BouncyCastleJsseProvider.PROVIDER_NAME
            );
            KeyStore clientStore = KeyStore.getInstance("PKCS12");
            InputStream instream =Thread.currentThread().getContextClassLoader().getResourceAsStream(PFX_PATH);

   sslContext.init(
                        wrapKeyManagers(keyManagerFactory.getKeyManagers()),
                    new TrustManager[]{trustManager},
//                            tmf.getTrustManagers(),
                        SecureRandom.getInstance("DEFAULT", BouncyCastleProvider.PROVIDER_NAME) );
</code>```

and i tring to customize keyManagerFactory in wrapKeyManagers method.

```<code>private KeyManager[] wrapKeyManagers(KeyManager[] managers) {
    return Arrays.stream(managers)
            .map(manager -> {
                if (manager instanceof X509KeyManager) {
                    X509KeyManager wrappedManager = (X509KeyManager) manager;
                    return new X509KeyManager() {
                        @Override
                        public String[] getClientAliases(String s, Principal[] principals) {
                            return wrappedManager.getClientAliases(replaceRsaWithEc(s), principals);
                        }
</code>```

i find it does not work , i can not run into  these override method

```<code>@Override
public String[] getClientAliases(String s, Principal[] principals) {
return wrappedManager.getClientAliases(replaceRsaWithEc(s), principals);
}

@Override
 public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
    return wrappedManager.chooseClientAlias(replaceRsaWithEc(strings), principals, socket);
 }

 @Override
 public String[] getServerAliases(String s, Principal[] principals) {
     return wrappedManager.getServerAliases(replaceRsaWithEc(s), principals);
 }
</code>```

I am pretty true this is some thing wrong about BouncyCastle
Is there any api or something to  customize keyManagerFactory?

Badly in need of help

答:
```<code> <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bctls-jdk15on</artifactId>
            <version>1.65</version>
        </dependency>
</code>```

change the version to 1.64 problem solved

Body:
i manage to make a https request with BouncyCastleProvider in order to fit "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8" cipher suite

  Security.addProvider(new BouncyCastleProvider());
            Security.addProvider(new BouncyCastleJsseProvider());
            SSLContext sslContext = SSLContext.getInstance("TLS", BouncyCastleJsseProvider.PROVIDER_NAME);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                    "PKIX"
                    ,BouncyCastleJsseProvider.PROVIDER_NAME
            );
            KeyStore clientStore = KeyStore.getInstance("PKCS12");
            InputStream instream =Thread.currentThread().getContextClassLoader().getResourceAsStream(PFX_PATH);

   sslContext.init(
                        wrapKeyManagers(keyManagerFactory.getKeyManagers()),
                    new TrustManager[]{trustManager},
//                            tmf.getTrustManagers(),
                        SecureRandom.getInstance("DEFAULT", BouncyCastleProvider.PROVIDER_NAME) );

and i tring to customize keyManagerFactory in wrapKeyManagers method.

private KeyManager[] wrapKeyManagers(KeyManager[] managers) {
    return Arrays.stream(managers)
            .map(manager -> {
                if (manager instanceof X509KeyManager) {
                    X509KeyManager wrappedManager = (X509KeyManager) manager;
                    return new X509KeyManager() {
                        @Override
                        public String[] getClientAliases(String s, Principal[] principals) {
                            return wrappedManager.getClientAliases(replaceRsaWithEc(s), principals);
                        }

i find it does not work , i can not run into  these override method

@Override
public String[] getClientAliases(String s, Principal[] principals) {
return wrappedManager.getClientAliases(replaceRsaWithEc(s), principals);
}

@Override
 public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
    return wrappedManager.chooseClientAlias(replaceRsaWithEc(strings), principals, socket);
 }

 @Override
 public String[] getServerAliases(String s, Principal[] principals) {
     return wrappedManager.getServerAliases(replaceRsaWithEc(s), principals);
 }

I am pretty true this is some thing wrong about BouncyCastle
Is there any api or something to  customize keyManagerFactory?

Badly in need of help

Body:
 <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bctls-jdk15on</artifactId>
            <version>1.65</version>
        </dependency>

change the version to 1.64 problem solved


问:
Mongoose unique compound index if other field is false or doesn't exist
I have item names that need to be unique for each country if they are not flagged as inactive, so I would like to set some kind of compound index to enforce this if the inactive flag is not set at all or if the inactive flag is set to false. Can this be accomplished with an index or would I have to write a pre save hook?</p>

```<code>let itemSchema = new Schema({
    name: String,
    country: String,
    inactive: Boolean
})

itemSchema.index(
    {
        name: 1,
        country: 1
    },
    {
        // How do I set it to unique if inactive is false or does not exist?
        unique: true
    }
)
</code>```

答:
I had a very similar problem and solved it with the help of this answer.

```<code>itemSchema.index(
    {
        name: 1,
        country: 1
    },
    {
        unique: true,
        partialFilterExpression: { inactive: { $eq: false } }
    }
)
</code>```

I haven't tried it with $exists, but presumably you can modify the partialFilterExpression to include it as follows:

```<code>partialFilterExpression: { inactive: { $eq: false, $exists: false } }
</code>```

Body:
I have item names that need to be unique for each country if they are not flagged as inactive, so I would like to set some kind of compound index to enforce this if the inactive flag is not set at all or if the inactive flag is set to false. Can this be accomplished with an index or would I have to write a pre save hook?

let itemSchema = new Schema({
    name: String,
    country: String,
    inactive: Boolean
})

itemSchema.index(
    {
        name: 1,
        country: 1
    },
    {
        // How do I set it to unique if inactive is false or does not exist?
        unique: true
    }
)

Body:
I had a very similar problem and solved it with the help of this answer.

itemSchema.index(
    {
        name: 1,
        country: 1
    },
    {
        unique: true,
        partialFilterExpression: { inactive: { $eq: false } }
    }
)

I haven't tried it with $exists, but presumably you can modify the partialFilterExpression to include it as follows:

partialFilterExpression: { inactive: { $eq: false, $exists: false } }


问:
Add multiple elements into flexbox column with jQuery
I have an array of objects I am iterating through. For each object, I am using jQuery to generate a div (with an attribute from an object) and two buttons.

```<code>        arrayOfObjects.forEach(object => {
            $('.container').append(`<div>${object.attribute}</div> <button>Default</button> <button>Default</button>`);
        })
</code>```

All of this is housed inside a flexbox container that's to be displayed as wrapped columns (arrangement as columns is important). In other words, I am expecting/want this:

Note: I do not want row wrap. Which does what I expect but, once again, arrangement as columns is important:

Instead, I get every element placed on its own column.

How can I make it so that it displays as I expected/want? Is it even possible?

This is my current setup:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <style type='text/css'>
        .container{
            height: 30vh;
            display: flex;
            flex-flow: column wrap;
        }
    </style>
</head>
<body>
    <div class="container"></div>
</body>
<script type='text/javascript'>
    $(document).ready(function(){
        arrayOfObjects.forEach(object => {
            $('.container').append(`<div>${object.attribute}</div> <button>Default</button> <button>Default</button>`);
        })
    });
</script>
</html>
</code>```

答:
Your problem is in this line flex-flow: column wrap;. Basically, you're displaying the container flex but in a column while you want it to be in a row. Here's how you fix it

```<code>flex-flow: row wrap;
</code>```

also here's an example: Exemple

Body:
I have an array of objects I am iterating through. For each object, I am using jQuery to generate a div (with an attribute from an object) and two buttons.

        arrayOfObjects.forEach(object => {
            $('.container').append(`<div>${object.attribute}</div> <button>Default</button> <button>Default</button>`);
        })

All of this is housed inside a flexbox container that's to be displayed as wrapped columns (arrangement as columns is important). In other words, I am expecting/want this:

Note: I do not want row wrap. Which does what I expect but, once again, arrangement as columns is important:

Instead, I get every element placed on its own column.

How can I make it so that it displays as I expected/want? Is it even possible?

This is my current setup:

<!DOCTYPE html>

Body:
Your problem is in this line flex-flow: column wrap;. Basically, you're displaying the container flex but in a column while you want it to be in a row. Here's how you fix it

flex-flow: row wrap;

also here's an example: Exemple


问:
python/tkinter popup window appears fine on windows or linux but not on OSX Mojave. NO ERRORS
"I'm learning Tkinter from the "GUI Programming Cookbook". Using my MacBook Pro running Mojave, python3.8 and the Tkinter that came packaged. There is one method where a popup tool tip shows when the mouse is hovered over a widget. It works fine on Win 10 and linux, but the popup does not appear on my Mac. There are no errors.

I put in some debug print() statements and the mouse coordinates and movement are correct.

This works****. Window text hovers over widget

here is output from print(sys.version) on linux.

3.7.4 (default, Jul  9 2019, 16:48:28)
[GCC 8.3.1 20190223 (Red Hat 8.3.1-2)]

This doe NOT work **** popup does not appear

output from print(sys.version) on Mac

3.8.0 (v3.8.0:fa919fdf25, Oct 14 2019, 10:23:27)
[Clang 6.0 (clang-600.0.57)]

===================

```<code>'''
Created on May 3, 2019

@author: Burkhard A. Meier
'''
#======================
# imports
#======================
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import messagebox as msg
from tkinter import Spinbox

        #====================================================
class ToolTip(object):
    def __init__(self, widget, tip_text=None):
        self.widget = widget
        self.tip_text = tip_text
        widget.bind('<Enter>', self.mouse_enter)
          # bind mouse events
        widget.bind('<Leave>', self.mouse_leave)

    def mouse_enter(self, _event):
        self.show_tooltip()
        print('entered the widget')

    def mouse_leave(self, _event):
        self.hide_tooltip()
        print('entered the widget')

    def show_tooltip(self):
        if self.tip_text:
            x_left = self.widget.winfo_rootx()
                # get widget top-left coordinates
            y_top = self.widget.winfo_rooty() - 18

            #DEBUG
            print('self.widget, y_top, x_left')
            print(self.widget, y_top, x_left)

            # place tooltip above widget or it flickers

            self.tip_window = tk.Toplevel(self.widget)
           # create Toplevel window; parent=widget
            self.tip_window.overrideredirect(True)
            # remove surrounding toolbar window
            self.tip_window.geometry("+%d+%d" % (x_left, y_top))
            # position tooltip

            #print('\nTOOLTIP before author code line')
            #print(self.tip_text)
            #label = tk.Label(self.tip_window, text=self.tip_text,
             #justify=tk.LEFT, background="#ffffe0",
             # relief=tk.SOLID,
             #borderwidth=1, font=("tahoma", "8", "normal"))

            #below is my code cus the above line does
            #not show up EKK 10/25/19

            label = tk.Label(self.tip_window, text=self.tip_text,
             justify=tk.LEFT)
            label.pack(fill="both")
            #label.pack(ipadx=1)

            print('TOOLTIP after author code line')
            print(self.tip_text)

    def hide_tooltip(self):
        if self.tip_window:
            self.tip_window.destroy()

#=====================================================
# just added all the code.
# the above class is called by the Spinbox and Scroll methods below.

          # Create instance
win = tk.Tk()

# Add a title
win.title("Python GUI")

tabControl = ttk.Notebook(win)          # Create Tab Control

tab1 = ttk.Frame(tabControl)            # Create a tab
tabControl.add(tab1, text='Tab 1')      # Add the tab
tab2 = ttk.Frame(tabControl)            # Add a second tab
tabControl.add(tab2, text='Tab 2')      # Make second tab visible

tabControl.pack(expand=1, fill="both")  # Pack to make visible

# LabelFrame using tab1 as the parent
mighty = ttk.LabelFrame(tab1, text=' Mighty Python ')
mighty.grid(column=0, row=0, padx=8, pady=4)

# Modify adding a Label using mighty as the parent instead of win
a_label = ttk.Label(mighty, text="Enter a name:")
a_label.grid(column=0, row=0, sticky='W')

# Modified Button Click Function
def click_me():
    action.configure(text='Hello ' + name.get() + ' ' +
                     number_chosen.get())

# Adding a Textbox Entry widget
name = tk.StringVar()
name_entered = ttk.Entry(mighty, width=12, textvariable=name)
name_entered.grid(column=0, row=1, sticky='W')
# align left/West

# Adding a Button
action = ttk.Button(mighty, text="Click Me!", command=click_me)
action.grid(column=2, row=1)

ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0)
number = tk.StringVar()
number_chosen = ttk.Combobox(mighty, width=12, textvariable=number, state='readonly')
number_chosen['values'] = (1, 2, 4, 42, 100)
number_chosen.grid(column=1, row=1)
number_chosen.current(0)

# Spinbox callback
def _spin():
    value = spin.get()
    print(value)
    scrol.insert(tk.INSERT, value + '\n')

# Adding a Spinbox widget
spin = Spinbox(mighty, values=(1, 2, 4, 42, 100), width=5, bd=9, command=_spin)
# using range
spin.grid(column=0, row=2)

    # Add a Tooltip to the Spinbox
ToolTip(spin, 'This is a Spin control')

# Using a scrolled Text control
scrol_w  = 30
scrol_h  =  3
scrol = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD)
scrol.grid(column=0, row=3, sticky='WE', columnspan=3)

# Add a Tooltip to the ScrolledText widget
ToolTip(scrol, 'This is a ScrolledText widget')

# Bunch of code snipped here

name_entered.focus()      # Place cursor into name Entry
#======================
# Start GUI
#======================
win.mainloop()

</code>```

the class is called from other code. the label on lines 42 and 46 will not show up on my MacBook but everything is fine on windows and Linux. There are no error messages. the window just never appears. anyone have  suggestions?? I'm going nuts here!  Thanks in advance.

答:
If you're still having this problem on Mac OSX, I found a reddit thread that pointed to:

https://github.com/python/cpython/blob/master/Lib/idlelib/tooltip.py

I added the following two lines to the end of my show_tooltip():

```<code>tw.update_idletasks()  # Needed on MacOS -- see #34275.
tw.lift()  # work around bug in Tk 8.5.18+ (issue #24570)
</code>```

And the tooltips started showing up.

Body:
"I'm learning Tkinter from the "GUI Programming Cookbook". Using my MacBook Pro running Mojave, python3.8 and the Tkinter that came packaged. There is one method where a popup tool tip shows when the mouse is hovered over a widget. It works fine on Win 10 and linux, but the popup does not appear on my Mac. There are no errors.

I put in some debug print() statements and the mouse coordinates and movement are correct.

This works****. Window text hovers over widget

here is output from print(sys.version) on linux.

3.7.4 (default, Jul  9 2019, 16:48:28)
[GCC 8.3.1 20190223 (Red Hat 8.3.1-2)]

This doe NOT work **** popup does not appear

output from print(sys.version) on Mac

3.8.0 (v3.8.0:fa919fdf25, Oct 14 2019, 10:23:27)
[Clang 6.0 (clang-600.0.57)]

===================

'''
Created on May 3, 2019

@author: Burkhard A. Meier
'''
#======================
# imports
#======================
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import messagebox as msg
from tkinter import Spinbox

        #====================================================
class ToolTip(object):
    def __init__(self, widget, tip_text=None):
        self.widget = widget
        self.tip_text = tip_text
        widget.bind('<Enter>', self.mouse_enter)
          # bind mouse events
        widget.bind('<Leave>', self.mouse_leave)

    def mouse_enter(self, _event):
        self.show_tooltip()
        print('entered the widget')

    def mouse_leave(self, _event):
        self.hide_tooltip()
        print('entered the widget')

    def show_tooltip(self):
        if self.tip_text:
            x_left = self.widget.winfo_rootx()
                # get widget top-left coordinates
            y_top = self.widget.winfo_rooty() - 18

            #DEBUG
            print('self.widget, y_top, x_left')
            print(self.widget, y_top, x_left)

            # place tooltip above widget or it flickers

            self.tip_window = tk.Toplevel(self.widget)
           # create Toplevel window; parent=widget
            self.tip_window.overrideredirect(True)
            # remove surrounding toolbar window
            self.tip_window.geometry("+%d+%d" % (x_left, y_top))
            # position tooltip

            #print('\nTOOLTIP before author code line')
            #print(self.tip_text)
            #label = tk.Label(self.tip_window, text=self.tip_text,
             #justify=tk.LEFT, background="#ffffe0",
             # relief=tk.SOLID,
             #borderwidth=1, font=("tahoma", "8", "normal"))

            #below is my code cus the above line does
            #not show up EKK 10/25/19

            label = tk.Label(self.tip_window, text=self.tip_text,
             justify=tk.LEFT)
            label.pack(fill="both")
            #label.pack(ipadx=1)

            print('TOOLTIP after author code line')
            print(self.tip_text)

    def hide_tooltip(self):
        if self.tip_window:
            self.tip_window.destroy()

#=====================================================
# just added all the code.
# the above class is called by the Spinbox and Scroll methods below.

          # Create instance
win = tk.Tk()

# Add a title
win.title("Python GUI")

tabControl = ttk.Notebook(win)          # Create Tab Control

tab1 = ttk.Frame(tabControl)            # Create a tab
tabControl.add(tab1, text='Tab 1')      # Add the tab
tab2 = ttk.Frame(tabControl)            # Add a second tab
tabControl.add(tab2, text='Tab 2')      # Make second tab visible

tabControl.pack(expand=1, fill="both")  # Pack to make visible

# LabelFrame using tab1 as the parent
mighty = ttk.LabelFrame(tab1, text=' Mighty Python ')
mighty.grid(column=0, row=0, padx=8, pady=4)

# Modify adding a Label using mighty as the parent instead of win
a_label = ttk.Label(mighty, text="Enter a name:")
a_label.grid(column=0, row=0, sticky='W')

# Modified Button Click Function
def click_me():
    action.configure(text='Hello ' + name.get() + ' ' +
                     number_chosen.get())

# Adding a Textbox Entry widget
name = tk.StringVar()
name_entered = ttk.Entry(mighty, width=12, textvariable=name)
name_entered.grid(column=0, row=1, sticky='W')
# align left/West

# Adding a Button
action = ttk.Button(mighty, text="Click Me!", command=click_me)
action.grid(column=2, row=1)

ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0)
number = tk.StringVar()
number_chosen = ttk.Combobox(mighty, width=12, textvariable=number, state='readonly')
number_chosen['values'] = (1, 2, 4, 42, 100)
number_chosen.grid(column=1, row=1)
number_chosen.current(0)

# Spinbox callback
def _spin():
    value = spin.get()
    print(value)
    scrol.insert(tk.INSERT, value + '\n')

# Adding a Spinbox widget
spin = Spinbox(mighty, values=(1, 2, 4, 42, 100), width=5, bd=9, command=_spin)
# using range
spin.grid(column=0, row=2)

    # Add a Tooltip to the Spinbox
ToolTip(spin, 'This is a Spin control')

# Using a scrolled Text control
scrol_w  = 30
scrol_h  =  3
scrol = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD)
scrol.grid(column=0, row=3, sticky='WE', columnspan=3)

# Add a Tooltip to the ScrolledText widget
ToolTip(scrol, 'This is a ScrolledText widget')

# Bunch of code snipped here

name_entered.focus()      # Place cursor into name Entry
#======================
# Start GUI
#======================
win.mainloop()

the class is called from other code. the label on lines 42 and 46 will not show up on my MacBook but everything is fine on windows and Linux. There are no error messages. the window just never appears. anyone have  suggestions?? I'm going nuts here!  Thanks in advance.

Body:
If you're still having this problem on Mac OSX, I found a reddit thread that pointed to:

https://github.com/python/cpython/blob/master/Lib/idlelib/tooltip.py

I added the following two lines to the end of my show_tooltip():

tw.update_idletasks()  # Needed on MacOS -- see #34275.
tw.lift()  # work around bug in Tk 8.5.18+ (issue #24570)

And the tooltips started showing up.


问:
R - Finding identical rows or rows that only differ by x columns
I'm trying to use R on a large CSV file that for this example can be said to represent a list of people and forms of transportation. If a person owns that mode of transportation, this is represented by a X in the corresponding cell. Example data of this is as per below:

```<code>Type,Peter,Paul,Mary,Don,Stan,Mike
Scooter,X,X,X,,X,
Car,,,,X,,X
Bike,,,,,,
Skateboard,X,X,X,X,X,X
Boat,,X,,,,
</code>```

The below image makes it easier to see what it represents:

What I'm after is to learn which persons have identical modes of transportation, or, ideally, where the modes of transportation differs by no more than one.

The format is a bit weird but, assuming the csv file is named example.csv, I can read it into a data frame and transpose it as per below (it should be fairly obvious that I'm a complete R noob)

```<code>ex <- read.csv('example.csv')
ext <- as.data.frame(t(ex))
</code>```

This post explained how to find duplicates and it seems to work

```<code>duplicated(ext) | duplicated(ext[nrow(ext):1, ])[nrow(ext):1]
which(duplicated(ext) | duplicated(ext[nrow(ext):1, ])[nrow(ext):1])
</code>```

This returns the following indexes:

1 2 4 5 6 7

That does indeed correspond with what I consider to be duplicate rows. That is, Peter has the same modes of transportation as Mary and Stan (indexes 2, 4 and 6); Don and Mike likewise share the same modes of transportation, indexes 5 and 7.

Again, that seems to work ok but if the modes of transportation and number of people are significant, it becomes really difficult finding/knowing not just which rows are duplicates, but which indexes actually matched. In this case that indexes 2, 4 and 6 are identical and that 5 and 7 are identical.

Is there an easy way of getting that information so that one doesn't have to try and find the matches manually?

Also, given all of the above, is it possible to alter the code in any way so that it would consider rows to match if there was only a difference in X positions (for example a difference of one is acceptable so as long as the persons in the above example have no more than one mode of transportation that is different, it's still considered a match)?

Happy to elaborate further and very grateful for any and all help.

答:
library(dplyr)
library(tidyr)

ex <- read.csv(text = "Type,Peter,Paul,Mary,Don,Stan,Mike
Scooter,X,X,X,,X,
Car,,,,X,,X
Bike,,,,,,
Skateboard,X,X,X,X,X,X
Boat,,X,,,,", )

ext <- tidyr::pivot_longer(ex, -Type, names_to = "person")

# head(ext)
ext <- ext %>%
  group_by(person) %>%
  filter(value == "X") %>%
  summarise(Modalities = n(), Which = paste(Type, collapse=", ")) %>%
  arrange(desc(Modalities), Which) %>%
  mutate(IdenticalGrp = rle(Which)$lengths %>% {rep(seq(length(.)), .)})

ext
#> # A tibble: 6 x 4
#>   person Modalities Which                     IdenticalGrp
#>   <chr>       <int> <chr>                            <int>
#> 1 Paul            3 Scooter, Skateboard, Boat            1
#> 2 Don             2 Car, Skateboard                      2
#> 3 Mike            2 Car, Skateboard                      2
#> 4 Mary            2 Scooter, Skateboard                  3
#> 5 Peter           2 Scooter, Skateboard                  3
#> 6 Stan            2 Scooter, Skateboard                  3
```

<p>To get a membership list in any particular IndenticalGrp you can just <code>pull</code> like this.</p>

<pre class="lang-r prettyprint-override"><code>ext %>% filter(IdenticalGrp == 3) %>% pull(person)
#> [1] "Mary"  "Peter" "Stan"
</code>```

Body:
I'm trying to use R on a large CSV file that for this example can be said to represent a list of people and forms of transportation. If a person owns that mode of transportation, this is represented by a X in the corresponding cell. Example data of this is as per below:

Type,Peter,Paul,Mary,Don,Stan,Mike
Scooter,X,X,X,,X,
Car,,,,X,,X
Bike,,,,,,
Skateboard,X,X,X,X,X,X
Boat,,X,,,,

The below image makes it easier to see what it represents:

What I'm after is to learn which persons have identical modes of transportation, or, ideally, where the modes of transportation differs by no more than one.

The format is a bit weird but, assuming the csv file is named example.csv, I can read it into a data frame and transpose it as per below (it should be fairly obvious that I'm a complete R noob)

ex <- read.csv('example.csv')
ext <- as.data.frame(t(ex))

This post explained how to find duplicates and it seems to work

duplicated(ext) | duplicated(ext[nrow(ext):1, ])[nrow(ext):1]
which(duplicated(ext) | duplicated(ext[nrow(ext):1, ])[nrow(ext):1])

This returns the following indexes:

1 2 4 5 6 7

That does indeed correspond with what I consider to be duplicate rows. That is, Peter has the same modes of transportation as Mary and Stan (indexes 2, 4 and 6); Don and Mike likewise share the same modes of transportation, indexes 5 and 7.

Again, that seems to work ok but if the modes of transportation and number of people are significant, it becomes really difficult finding/knowing not just which rows are duplicates, but which indexes actually matched. In this case that indexes 2, 4 and 6 are identical and that 5 and 7 are identical.

Is there an easy way of getting that information so that one doesn't have to try and find the matches manually?

Also, given all of the above, is it possible to alter the code in any way so that it would consider rows to match if there was only a difference in X positions (for example a difference of one is acceptable so as long as the persons in the above example have no more than one mode of transportation that is different, it's still considered a match)?

Happy to elaborate further and very grateful for any and all help.

Body:
library(dplyr)
library(tidyr)

ex <- read.csv(text = "Type,Peter,Paul,Mary,Don,Stan,Mike
Scooter,X,X,X,,X,
Car,,,,X,,X
Bike,,,,,,
Skateboard,X,X,X,X,X,X
Boat,,X,,,,", )

ext <- tidyr::pivot_longer(ex, -Type, names_to = "person")

# head(ext)
ext <- ext %>%
  group_by(person) %>%
  filter(value == "X") %>%
  summarise(Modalities = n(), Which = paste(Type, collapse=", ")) %>%
  arrange(desc(Modalities), Which) %>%
  mutate(IdenticalGrp = rle(Which)$lengths %>% {rep(seq(length(.)), .)})

ext
#> # A tibble: 6 x 4
#>   person Modalities Which                     IdenticalGrp
#>   <chr>       <int> <chr>                            <int>
#> 1 Paul            3 Scooter, Skateboard, Boat            1
#> 2 Don             2 Car, Skateboard                      2
#> 3 Mike            2 Car, Skateboard                      2
#> 4 Mary            2 Scooter, Skateboard                  3
#> 5 Peter           2 Scooter, Skateboard                  3
#> 6 Stan            2 Scooter, Skateboard                  3

To get a membership list in any particular IndenticalGrp you can just pull like this.

ext %>% filter(IdenticalGrp == 3) %>% pull(person)
#> [1] "Mary"  "Peter" "Stan"


问:
How to create a dhall schema with arbitrary key but typed values?
In dhall, how can I create a schema for the following yaml?

```<code>environment:
    local:
        path: "/path/to/env"
        envvars:
            - var1
            - var2
    stage:
        path: "/path/to/env"
        envvars:
            - var1
            - var2
    prod:
        path: "/path/to/env"
        envvars:
            - var1
            - var2
</code>```

As you can see, it has arbitrary key ("local", "stage", etc) but same type for the values.  I believe this is a fairly common use case, but I didn't see it discussed in the tutorial.

答:
You can use Map, defined in the Prelude and discussed in the Language Tour.

```<code>let Prelude = http://prelude.dhall-lang.org/v16.0.0/package.dhall

let Environment = { path : Text, envvars : List Text }

let EnvironmentSet = { environment : Prelude.Map.Type Text Environment }

in    { environment = toMap
          { local = { path = "/path/to/env", envvars = [ "var1", "var2" ] }
          , stage = { path = "/path/to/env", envvars = [ "var1", "var2" ] }
          , prod = { path = "/path/to/env", envvars = [ "var1", "var2" ] }
          }
      }
    : EnvironmentSet
</code>```

dhall-to-yaml produces the original YAML (modulo key order):

```<code>% dhall-to-yaml < tmp.dhall
environment:
  local:
    envvars:
      - var1
      - var2
    path: /path/to/env
  prod:
    envvars:
      - var1
      - var2
    path: /path/to/env
  stage:
    envvars:
      - var1
      - var2
    path: /path/to/env
</code>```

You can also get rid of much of the boilerplate by defining some functions to create the records and maps.

```<code>let Map = http://prelude.dhall-lang.org/v16.0.0/Map/package.dhall

let Environment = { path : Text, envvars : List Text }

let makeEnv =
        λ(name : Text)
      → λ(path : Text)
      → λ(vars : List Text)
      → Map.keyValue Environment name { path = path, envvars = vars }

let makeEnvironmentSet =
      λ(envs : List (Map.Entry Text Environment)) → { environment = envs }

in  makeEnvironmentSet
      [ makeEnv "local" "/path/to/local" [ "localvar1", "localvar2" ]
      , makeEnv "stage" "/path/to/stage" [ "stagevar1", "stagevar2" ]
      , makeEnv "prod" "/path/to/prod" [ "prodvar1", "prodvar2" ]
      ]
</code>```

dhall-to-yaml converts a record of type {mapKey: k, mapValue: v} to a YAML object.

Body:
In dhall, how can I create a schema for the following yaml?

environment:
    local:
        path: "/path/to/env"
        envvars:
            - var1
            - var2
    stage:
        path: "/path/to/env"
        envvars:
            - var1
            - var2
    prod:
        path: "/path/to/env"
        envvars:
            - var1
            - var2

As you can see, it has arbitrary key ("local", "stage", etc) but same type for the values.  I believe this is a fairly common use case, but I didn't see it discussed in the tutorial.

Body:
You can use Map, defined in the Prelude and discussed in the Language Tour.

let Prelude = http://prelude.dhall-lang.org/v16.0.0/package.dhall

let Environment = { path : Text, envvars : List Text }

let EnvironmentSet = { environment : Prelude.Map.Type Text Environment }

in    { environment = toMap
          { local = { path = "/path/to/env", envvars = [ "var1", "var2" ] }
          , stage = { path = "/path/to/env", envvars = [ "var1", "var2" ] }
          , prod = { path = "/path/to/env", envvars = [ "var1", "var2" ] }
          }
      }
    : EnvironmentSet

dhall-to-yaml produces the original YAML (modulo key order):

% dhall-to-yaml < tmp.dhall
environment:
  local:
    envvars:
      - var1
      - var2
    path: /path/to/env
  prod:
    envvars:
      - var1
      - var2
    path: /path/to/env
  stage:
    envvars:
      - var1
      - var2
    path: /path/to/env

You can also get rid of much of the boilerplate by defining some functions to create the records and maps.

let Map = http://prelude.dhall-lang.org/v16.0.0/Map/package.dhall

let Environment = { path : Text, envvars : List Text }

let makeEnv =
        λ(name : Text)
      → λ(path : Text)
      → λ(vars : List Text)
      → Map.keyValue Environment name { path = path, envvars = vars }

let makeEnvironmentSet =
      λ(envs : List (Map.Entry Text Environment)) → { environment = envs }

in  makeEnvironmentSet
      [ makeEnv "local" "/path/to/local" [ "localvar1", "localvar2" ]
      , makeEnv "stage" "/path/to/stage" [ "stagevar1", "stagevar2" ]
      , makeEnv "prod" "/path/to/prod" [ "prodvar1", "prodvar2" ]
      ]

dhall-to-yaml converts a record of type {mapKey: k, mapValue: v} to a YAML object.


问:
Java, moving from desktop app to web app
I'm going to write my first Java based web app, and I'm sort of lost how to begin.

Firstly, I would like a web app and a desktop app that do pretty much the same thing, without the hackish idea of embedding a web browser into the desktop app because that doesn't allow to easily make changes to the desktop without affecting the web app and vice versa.

Now, here my questions.

Right now, I have a bunch of POJOs and they communicate with a single class that, right now, uses a flat file as a "database", of course, in production, I would use a legitimate database and just change that single class. Is this a good idea? Will I be able to go from POJOs to a web app?

Should I use a framework? I would like to have this app written pretty soon, seeing that all the buisness logic is there, I just need to wrap it so its usable, so, I don't want to spend an extreme amount of time learning, say, Spring (which AFAIK is huge), but, I don't want to keep reinventing the wheel throughout my app either. I can always just use JSP and scriptlets...

If you said yes to the above, what framework(s) do you suggest? Please note that I would like a framework that I can start using in maybe 3-4 weeks of learning.

Will I have to start from scratch with the POJOs that I have written? They're well over 30k LOC, so, if it is like that, I'll be hesitant.

答:
You will need:

a web framework. Since you have Swing background, JSF 2 will be your best bet (everything will be painful, of course, but JSF will get you up and going quickly and will help you avoid the most tragic mistakes). Also, wrapping business pojos into web guis is the main use-case for JSF and it's biggest focus.

a "glue framework". One thing that is much different with web applications as opposed to desktop ones is that you cannot create view components by yourself - they must be created when browser requests a page. So you have to find a way to create the view objects and deliver all the references to the pojos that represent logic, some of which may have very different lifecycles (this is not a problem on desktop, but on web you have to distinguish between pojos that live along with the whole application, along with a single user session, along with a single request, and so on).

The "glue framework" could also provide the additional benefit of managing transactions. You have three choices:

Spring. It's not half as complex as you thing; you only need to learn some basic stuff.

EJB. You would need a real application server, like Glassfish or JBoss

bare JSF has good support for dependency injection, the only drawback is the lack of automatic transaction management.

If I were in your position, I would go with bare JSF 2.0 - this way you only need to learn one new technology. At first, try to avoid libraries like PrimeFaces - they usually work worse than advertised.

edit - and addendum

or - what is "dependency injection"(abridged and simplified)

When request comes to a web application, a new task starts in a new thread (well, the thread is probably recycled, but that's not important).

The application has already been running for some time and most of the objects you are going to need are already built and should not get created again: you have your database connection pool, maybe some parts of business layer; it is also possible that the request is just one of many request made during one session, and you already have a bunch of POJOs that the user is working on. The question is - how to get references to those objects?

You could arrange your application so that resources are available through some static fields. They may be singletons themselves, or they could be acquired through a singleton locator. This tends to work, but is out of fashion (hard to test, hard to refactor, hard to reuse, lifecycles are hard coded in application). The real code could look like this:
```
 public void doSomething() {
     Customer Service cs = AppManager.getInstance().getCustomerService();
     System.out.println(cs.getVersion());
 }
```

if you need clustering and session management, you could build a special kind of broker that would know and provide to anyone all kinds of needed objects. Each type of object would be registered as a factory under a different name. This also works and is implemented in Java as JNDI. The actual client code would look like this:

```
public void doSomething() throws Exception {
     CustomerService cs = (CustomerService)new InitialContext().lookup("some_fancy_looking_name_in_reality_just_string");
     System.out.println(cs.getVersion());
 }
```

The last way is the nicest. Since your initial object is not created by you but by the server just after http request arrives (details depend on the technology you choose, but your entry point might be a JSF managed bean or some kind of action controller), you can just advertise which references you need and let the server take care of finding them for you. This is called "Dependency Injection". Your acts as if everything is taken care of before your code is ever launched. Spring or EJB container, or CDI, or JSF take care of the rest. The code would look like this (just an example):

```
    @EJB
    CustomerService cs;</p>

```public void doSomething() {
     System.out.println(cs.getVersion());
}
```

<p>```

Note:

when you use DI, it really uses one of the two former methods under the hood. The good thing is: you do not have to know which one and in some cases you can even switch them without altering your code;

the exact means of registering components for injection differs from framework to framework. It might be a piece of Java code (like in Guice), an XML file (classic Spring) or an annotation (classic EJB 3). Most of the mentioned technologies support different kinds of configuration.

Body:
You will need:

a web framework. Since you have Swing background, JSF 2 will be your best bet (everything will be painful, of course, but JSF will get you up and going quickly and will help you avoid the most tragic mistakes). Also, wrapping business pojos into web guis is the main use-case for JSF and it's biggest focus.

a "glue framework". One thing that is much different with web applications as opposed to desktop ones is that you cannot create view components by yourself - they must be created when browser requests a page. So you have to find a way to create the view objects and deliver all the references to the pojos that represent logic, some of which may have very different lifecycles (this is not a problem on desktop, but on web you have to distinguish between pojos that live along with the whole application, along with a single user session, along with a single request, and so on).

The "glue framework" could also provide the additional benefit of managing transactions. You have three choices:

Spring. It's not half as complex as you thing; you only need to learn some basic stuff.

EJB. You would need a real application server, like Glassfish or JBoss

bare JSF has good support for dependency injection, the only drawback is the lack of automatic transaction management.

If I were in your position, I would go with bare JSF 2.0 - this way you only need to learn one new technology. At first, try to avoid libraries like PrimeFaces - they usually work worse than advertised.

edit - and addendum

or - what is "dependency injection"(abridged and simplified)

When request comes to a web application, a new task starts in a new thread (well, the thread is probably recycled, but that's not important).

The application has already been running for some time and most of the objects you are going to need are already built and should not get created again: you have your database connection pool, maybe some parts of business layer; it is also possible that the request is just one of many request made during one session, and you already have a bunch of POJOs that the user is working on. The question is - how to get references to those objects?

You could arrange your application so that resources are available through some static fields. They may be singletons themselves, or they could be acquired through a singleton locator. This tends to work, but is out of fashion (hard to test, hard to refactor, hard to reuse, lifecycles are hard coded in application). The real code could look like this:

 public void doSomething() {
     Customer Service cs = AppManager.getInstance().getCustomerService();
     System.out.println(cs.getVersion());
 }

if you need clustering and session management, you could build a special kind of broker that would know and provide to anyone all kinds of needed objects. Each type of object would be registered as a factory under a different name. This also works and is implemented in Java as JNDI. The actual client code would look like this:

public void doSomething() throws Exception {
     CustomerService cs = (CustomerService)new InitialContext().lookup("some_fancy_looking_name_in_reality_just_string");
     System.out.println(cs.getVersion());
 }

The last way is the nicest. Since your initial object is not created by you but by the server just after http request arrives (details depend on the technology you choose, but your entry point might be a JSF managed bean or some kind of action controller), you can just advertise which references you need and let the server take care of finding them for you. This is called "Dependency Injection". Your acts as if everything is taken care of before your code is ever launched. Spring or EJB container, or CDI, or JSF take care of the rest. The code would look like this (just an example):

    @EJB
    CustomerService cs;

public void doSomething() {
     System.out.println(cs.getVersion());
}

Note:

when you use DI, it really uses one of the two former methods under the hood. The good thing is: you do not have to know which one and in some cases you can even switch them without altering your code;

the exact means of registering components for injection differs from framework to framework. It might be a piece of Java code (like in Guice), an XML file (classic Spring) or an annotation (classic EJB 3). Most of the mentioned technologies support different kinds of configuration.


问:
Creating a "dictionary of sets"
I need to efficiently store data in something that would resemble a "dictionary of sets" e.g. have a dictionary with multiple (unique) values matching each unique key. The source of my data would be a (not very well) structured XML.

My idea is:
I will look through a number of elements and find keys. If the key does not exist, add it to dictionary, if it already exists, just add a new value in the corresponding key.

And the result would be something like:

```<code>{
 'key1': {'1484', '1487', 1488', ...}
 'key2': {'1485', '1486', '1489', ...}
 'key3': {'1490', '1491', '1492', ...}
 ...
}
</code>```

I need to add new keys on the go.
I need to push unique values into each set.
I need to be able to iterate through the whole dictionary.

I am not sure if this is even feasible, but if anybody could push me in the right direction, I would be more than thankful.

答:
Using dict.setdefault() to create the key if it doesn't exist, and initialising it with an empty set:

store = {}
for key, value in yoursource:
    store.setdefault(key, set()).add(value)
```

Title: Creating a "dictionary of sets"

Body:
I need to efficiently store data in something that would resemble a "dictionary of sets" e.g. have a dictionary with multiple (unique) values matching each unique key. The source of my data would be a (not very well) structured XML.

My idea is:
I will look through a number of elements and find keys. If the key does not exist, add it to dictionary, if it already exists, just add a new value in the corresponding key.

And the result would be something like:

{
 'key1': {'1484', '1487', 1488', ...}
 'key2': {'1485', '1486', '1489', ...}
 'key3': {'1490', '1491', '1492', ...}
 ...
}

I need to add new keys on the go.
I need to push unique values into each set.
I need to be able to iterate through the whole dictionary.

I am not sure if this is even feasible, but if anybody could push me in the right direction, I would be more than thankful.


答:
The following pattern will work for <= 10 digits to value before the dot and any number of digits after the dot.</p>

```<code>$b = preg_match("!^\d{1,10}(\.\d*)?$!",109.9);
</code>```

Title: regex to add a limit of 10 digits with decimal value having no limit

Body:
I want to apply a validation where I need a limit of 10 digits on value but the value after decimal has no limit.

Like this
1000000000.2121
The value before decimal should be less than 10 digits.
I am trying this regex
^(10|\d)(\.\d{1,2})?$
 But By this, I only add decimal digits with a limit of two. How can I achieve this?

Body:
The following pattern will work for <= 10 digits to value before the dot and any number of digits after the dot.

$b = preg_match("!^\d{1,10}(\.\d*)?$!",109.9);


问:
What is the right way to wire together 2 javascript objects?
I'm currently facing a conundrum: What is the right way to wire together 2 javascript objects?

Imagine an application like a text editor with several different files.  I have some HTML page that represents the view for the notebook. I have a file notebook.js that contains class definitions for NotebookController and Notebook View.

NotebookControler object responsible for performing business logic on the Notebook like "Save Notebook," "Load Notebook," "New Notebook."  NotebookView is responsible for managing the HTML that is used for presentation.  It does low level stuff like "get/set notebook body" "get/set notebook name." It also listens for DOM events (onClick) and fires business events (saveNotebook). This is my attempt at the Passive View pattern.

I want my javascript client-side code to be object-oriented, separated concerns, and unit-testable.  I want to test NotebookController with a mock NotebookView and vice versa.  This means that I can't just instantiate a NotebookView inside the NotebookController.  So do I

Put some logic in my notebook.js that wires the 2 together

Have a global function in my application that knows to instantiate one of each and wire them together

Use Dependency Injection, either a home-grown one or something like SquirrelIoc

In Java, the choice is a natural one: use Spring.  But that doesn't seem very JavaScript-y. What's the right thing to do?

答:
Thanks for the insight.  I ended up writing a simple JavaScript dependency injection utility.  After debating for a while and your comments, it occured to me that DI was really the right answer because:

It totally separated the concerns of wiring from the business logic while keeping the wiring logic close to the things being wired.

It allowed me to generically provide a "you're all wired up" callback on my objects so that I could do a 3 phase initialization: instantiate everything, wire it all up, call everyone's callbacks and tell them they're wired.

It was easy to check for dependency missing problems.

So here's the DI utility:

```<code>var Dependency = function(_name, _instance, _dependencyMap) {
    this.name = _name;
    this.instance = _instance;
    this.dependencyMap = _dependencyMap;
}

Dependency.prototype.toString = function() {
    return this.name;
}

CONCORD.dependencyinjection = {};

CONCORD.dependencyinjection.Context = function() {
    this.registry = {};
}

CONCORD.dependencyinjection.Context.prototype = {
    register : function(name, instance, dependencyMap) {
        this.registry[name] = new Dependency(name, instance, dependencyMap);
    },
    get : function(name) {
        var dependency = this.registry[name];
        return dependency != null ? dependency.instance : null;
    },

    init : function() {
        YAHOO.log("Initializing Dependency Injection","info","CONCORD.dependencyinjection.Context");
        var registryKey;
        var dependencyKey;
        var dependency;
        var afterDependenciesSet = [];
        for (registryKey in this.registry) {
            dependency = this.registry[registryKey];
            YAHOO.log("Initializing " + dependency.name,"debug","CONCORD.dependencyinjection.Context");

            for(dependencyKey in dependency.dependencyMap) {
                var name = dependency.dependencyMap[dependencyKey];
                var instance = this.get(name);
                if(instance == null) {
                    throw "Unsatisfied Dependency: "+dependency+"."+dependencyKey+" could not find instance for "+name;
                }
                dependency.instance[dependencyKey] = instance;
            }

            if(typeof dependency.instance['afterDependenciesSet'] != 'undefined') {
                afterDependenciesSet.push(dependency);
            }
        }

        var i;
        for(i = 0; i < afterDependenciesSet.length; i++) {
            afterDependenciesSet[i].instance.afterDependenciesSet();
        }
    }

}
</code>```

OwnerDisplayName: Jonathan Hess

Body:
Thanks for the insight.  I ended up writing a simple JavaScript dependency injection utility.  After debating for a while and your comments, it occured to me that DI was really the right answer because:

It totally separated the concerns of wiring from the business logic while keeping the wiring logic close to the things being wired.

It allowed me to generically provide a "you're all wired up" callback on my objects so that I could do a 3 phase initialization: instantiate everything, wire it all up, call everyone's callbacks and tell them they're wired.

It was easy to check for dependency missing problems.

So here's the DI utility:

var Dependency = function(_name, _instance, _dependencyMap) {
    this.name = _name;
    this.instance = _instance;
    this.dependencyMap = _dependencyMap;
}

Dependency.prototype.toString = function() {
    return this.name;
}

CONCORD.dependencyinjection = {};

CONCORD.dependencyinjection.Context = function() {
    this.registry = {};
}

CONCORD.dependencyinjection.Context.prototype = {
    register : function(name, instance, dependencyMap) {
        this.registry[name] = new Dependency(name, instance, dependencyMap);
    },
    get : function(name) {
        var dependency = this.registry[name];
        return dependency != null ? dependency.instance : null;
    },

    init : function() {
        YAHOO.log("Initializing Dependency Injection","info","CONCORD.dependencyinjection.Context");
        var registryKey;
        var dependencyKey;
        var dependency;
        var afterDependenciesSet = [];
        for (registryKey in this.registry) {
            dependency = this.registry[registryKey];
            YAHOO.log("Initializing " + dependency.name,"debug","CONCORD.dependencyinjection.Context");

            for(dependencyKey in dependency.dependencyMap) {
                var name = dependency.dependencyMap[dependencyKey];
                var instance = this.get(name);
                if(instance == null) {
                    throw "Unsatisfied Dependency: "+dependency+"."+dependencyKey+" could not find instance for "+name;
                }
                dependency.instance[dependencyKey] = instance;
            }

            if(typeof dependency.instance['afterDependenciesSet'] != 'undefined') {
                afterDependenciesSet.push(dependency);
            }
        }

        var i;
        for(i = 0; i < afterDependenciesSet.length; i++) {
            afterDependenciesSet[i].instance.afterDependenciesSet();
        }
    }

}

ContentLicense: CC BY-SA 2.5


问:
How can you get the first digit in an int (C#)?
In C#, what's the best way to get the 1st digit in an int? The method I came up with is to turn the int into a string, find the 1st char of the string, then turn it back to an int.

```<code>int start = Convert.ToInt32(curr.ToString().Substring(0, 1));
</code>```

While this does the job, it feels like there is probably a good, simple, math-based solution to such a problem. String manipulation feels clunky.

Edit: irrespective of speed differences, mystring[0] instead of Substring() is still just string manipulation

答:
I just stumbled upon this old question and felt inclined to propose another suggestion since none of the other answers so far returns the correct result for all possible input values and it can still be made faster:

```<code>public static int GetFirstDigit( int i )
{
    if( i < 0 && ( i = -i ) < 0 ) return 2;
    return ( i < 100 ) ? ( i < 1 ) ? 0 : ( i < 10 )
            ? i : i / 10 : ( i < 1000000 ) ? ( i < 10000 )
            ? ( i < 1000 ) ? i / 100 : i / 1000 : ( i < 100000 )
            ? i / 10000 : i / 100000 : ( i < 100000000 )
            ? ( i < 10000000 ) ? i / 1000000 : i / 10000000
            : ( i < 1000000000 ) ? i / 100000000 : i / 1000000000;
}
</code>```

This works for all signed integer values inclusive -2147483648 which is the smallest signed integer and doesn't have a positive counterpart. Math.Abs( -2147483648 ) triggers a System.OverflowException and - -2147483648 computes to -2147483648.

The implementation can be seen as a combination of the advantages of the two fastest implementations so far. It uses a binary search and avoids superfluous divisions. A quick benchmark with the index of a loop with 100,000,000 iterations shows that it is twice as fast as the currently fastest implementation.

It finishes after 2,829,581 ticks.

For comparison I also measured a corrected variant of the currently fastest implementation which took 5,664,627 ticks.

```<code>public static int GetFirstDigitX( int i )
{
    if( i < 0 && ( i = -i ) < 0 ) return 2;
    if( i >= 100000000 ) i /= 100000000;
    if( i >= 10000 ) i /= 10000;
    if( i >= 100 ) i /= 100;
    if( i >= 10 ) i /= 10;
    return i;
}
</code>```

The accepted answer with the same correction needed 16,561,929 ticks for this test on my computer.

```<code>public static int GetFirstDigitY( int i )
{
    if( i < 0 && ( i = -i ) < 0 ) return 2;
    while( i >= 10 )
        i /= 10;
    return i;
}
</code>```

Simple functions like these can easily be proven for correctness since iterating all possible integer values takes not much more than a few seconds on current hardware. This means that it is less important to implement them in a exceptionally readable fashion as there simply won't ever be the need to fix a bug inside them later on.

OwnerDisplayName: Dinah

Body:
In C#, what's the best way to get the 1st digit in an int? The method I came up with is to turn the int into a string, find the 1st char of the string, then turn it back to an int.

int start = Convert.ToInt32(curr.ToString().Substring(0, 1));

While this does the job, it feels like there is probably a good, simple, math-based solution to such a problem. String manipulation feels clunky.

Edit: irrespective of speed differences, mystring[0] instead of Substring() is still just string manipulation

LastEditorDisplayName: Dinah

Body:
I just stumbled upon this old question and felt inclined to propose another suggestion since none of the other answers so far returns the correct result for all possible input values and it can still be made faster:

public static int GetFirstDigit( int i )
{
    if( i < 0 && ( i = -i ) < 0 ) return 2;
    return ( i < 100 ) ? ( i < 1 ) ? 0 : ( i < 10 )
            ? i : i / 10 : ( i < 1000000 ) ? ( i < 10000 )
            ? ( i < 1000 ) ? i / 100 : i / 1000 : ( i < 100000 )
            ? i / 10000 : i / 100000 : ( i < 100000000 )
            ? ( i < 10000000 ) ? i / 1000000 : i / 10000000
            : ( i < 1000000000 ) ? i / 100000000 : i / 1000000000;
}

This works for all signed integer values inclusive -2147483648 which is the smallest signed integer and doesn't have a positive counterpart. Math.Abs( -2147483648 ) triggers a System.OverflowException and - -2147483648 computes to -2147483648.

The implementation can be seen as a combination of the advantages of the two fastest implementations so far. It uses a binary search and avoids superfluous divisions. A quick benchmark with the index of a loop with 100,000,000 iterations shows that it is twice as fast as the currently fastest implementation.

It finishes after 2,829,581 ticks.

For comparison I also measured a corrected variant of the currently fastest implementation which took 5,664,627 ticks.

public static int GetFirstDigitX( int i )
{
    if( i < 0 && ( i = -i ) < 0 ) return 2;
    if( i >= 100000000 ) i /= 100000000;
    if( i >= 10000 ) i /= 10000;
    if( i >= 100 ) i /= 100;
    if( i >= 10 ) i /= 10;
    return i;
}

The accepted answer with the same correction needed 16,561,929 ticks for this test on my computer.

public static int GetFirstDigitY( int i )
{
    if( i < 0 && ( i = -i ) < 0 ) return 2;
    while( i >= 10 )
        i /= 10;
    return i;
}

Simple functions like these can easily be proven for correctness since iterating all possible integer values takes not much more than a few seconds on current hardware. This means that it is less important to implement them in a exceptionally readable fashion as there simply won't ever be the need to fix a bug inside them later on.


问:
Send an executable python file to someone
I've done a project and i want to send it to my friends to see and try

The problem is that once I make it an executable file i can t send it anywhere

They don t have python install so i can't  just send the files and i was
wondering what are the possibilities to send the executable

I've tried to rename the file extension, send it, but he could not run it

I want to know if there is a chance that windows can't compile or open the executable if python is not install

here s the code in any case

```<code>from tkinter import *

tura=0

def golire(parent):
    for elemente in parent.winfo_children():
        elemente.grid_forget()

def terminare(parent,castigator,joc_nou):
    global tura
    tura=0
    golire(parent)
    afis=Label(parent,text=castigator+' a castigat!',font=('Arial',30),width=20,height=3)
    buton1=Button(parent,text='Din nou?',font=('Courier',10),width=5,height=5,command=joc_nou)
    buton2=Button(parent,text='Neah',font=('Courier',10),width=5,height=5,command=root.quit)

    afis.grid(columnspan=2,sticky=NSEW)
    buton1.grid(row=1,column=0,sticky=NSEW)
    buton2.grid(row=1,column=1,sticky=NSEW)

class joc:
    def __init__(self,parent):
        global tura

        tura=0

        self.parent=parent

        b0=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b0.grid(row=0,column=0,sticky=NSEW)

        b1=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b1.grid(row=0,column=1,sticky=NSEW)

        b2=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b2.grid(row=0,column=2,sticky=NSEW)

        b3=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b3.grid(row=1,column=0,sticky=NSEW)

        b4=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b4.grid(row=1,column=1,sticky=NSEW)

        b5=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b5.grid(row=1,column=2,sticky=NSEW)

        b6=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b6.grid(row=2,column=0,sticky=NSEW)

        b7=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b7.grid(row=2,column=1,sticky=NSEW)

        b8=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b8.grid(row=2,column=2,sticky=NSEW)

        def enter(event):
            event.widget.config(bg='black')
        def left(event):
            event.widget.config(bg='white')

        def adaugare(event):
            global tura
            if event.widget['state']!='disabled':
                if tura%2==0:
                    event.widget.config(text='X')
                else:
                    event.widget.config(text='O')
                event.widget.config(state='disabled')
                tura+=1
        def verificare(event):
            def joc_nou():
                golire(self.parent)
                joc(self.parent)

            if b0['text']==b1['text']==b2['text'] and b0['state']==b1['state']==b2['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b3['text']==b4['text']==b5['text'] and b3['state']==b4['state']==b5['state']=='disabled':
                terminare(self.parent,b3['text'],joc_nou)
            elif b6['text']==b7['text']==b8['text'] and b6['state']==b7['state']==b8['state']=='disabled':
                terminare(self.parent,b6['text'],joc_nou)
            elif b0['text']==b3['text']==b6['text'] and b0['state']==b3['state']==b6['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b1['text']==b4['text']==b7['text'] and b1['state']==b4['state']==b7['state']=='disabled':
                terminare(self.parent,b1['text'],joc_nou)
            elif b2['text']==b5['text']==b8['text'] and b2['state']==b5['state']==b8['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b0['text']==b4['text']==b8['text'] and b0['state']==b4['state']==b8['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b2['text']==b4['text']==b6['text'] and b2['state']==b4['state']==b6['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b0['state']==b1['state']==b2['state']==b3['state']==b4['state']==b5['state']==b6['state']==b7['state']==b8['state']=='disabled':
                terminare(self.parent,'Nimeni',joc_nou)

        b0.bind("<Enter>",enter)
        b0.bind("<Leave>",left)

        b1.bind("<Enter>",enter)
        b1.bind("<Leave>",left)

        b2.bind("<Enter>",enter)
        b2.bind("<Leave>",left)

        b3.bind("<Enter>",enter)
        b3.bind("<Leave>",left)

        b4.bind("<Enter>",enter)
        b4.bind("<Leave>",left)

        b5.bind("<Enter>",enter)
        b5.bind("<Leave>",left)

        b6.bind("<Enter>",enter)
        b6.bind("<Leave>",left)

        b7.bind("<Enter>",enter)
        b7.bind("<Leave>",left)

        b8.bind("<Enter>",enter)
        b8.bind("<Leave>",left)

        b0.bind("<Button-1>",adaugare,add="+")

        b1.bind("<Button-1>",adaugare,add="+")

        b2.bind("<Button-1>",adaugare,add="+")

        b3.bind("<Button-1>",adaugare,add="+")

        b4.bind("<Button-1>",adaugare,add="+")

        b5.bind("<Button-1>",adaugare,add="+")

        b6.bind("<Button-1>",adaugare,add="+")

        b7.bind("<Button-1>",adaugare,add="+")

        b8.bind("<Button-1>",adaugare,add="+")

        #verificare
        b0.bind("<Button-1>",verificare,add="+")

        b1.bind("<Button-1>",verificare,add="+")

        b2.bind("<Button-1>",verificare,add="+")

        b3.bind("<Button-1>",verificare,add="+")

        b4.bind("<Button-1>",verificare,add="+")

        b5.bind("<Button-1>",verificare,add="+")

        b6.bind("<Button-1>",verificare,add="+")

        b7.bind("<Button-1>",verificare,add="+")

        b8.bind("<Button-1>",verificare,add="+")

if __name__=='__main__':
    root=Tk()
    joc(root)
    root.mainloop()
</code>```

答:
You've got 2 options here:

convince them to install python.

package it using a tool like PyInstaller or py2exe, then send them the compiled executable

Body:
I've done a project and i want to send it to my friends to see and try

The problem is that once I make it an executable file i can t send it anywhere

They don t have python install so i can't  just send the files and i was
wondering what are the possibilities to send the executable

I've tried to rename the file extension, send it, but he could not run it

I want to know if there is a chance that windows can't compile or open the executable if python is not install

here s the code in any case

from tkinter import *

tura=0

def golire(parent):
    for elemente in parent.winfo_children():
        elemente.grid_forget()

def terminare(parent,castigator,joc_nou):
    global tura
    tura=0
    golire(parent)
    afis=Label(parent,text=castigator+' a castigat!',font=('Arial',30),width=20,height=3)
    buton1=Button(parent,text='Din nou?',font=('Courier',10),width=5,height=5,command=joc_nou)
    buton2=Button(parent,text='Neah',font=('Courier',10),width=5,height=5,command=root.quit)

    afis.grid(columnspan=2,sticky=NSEW)
    buton1.grid(row=1,column=0,sticky=NSEW)
    buton2.grid(row=1,column=1,sticky=NSEW)

class joc:
    def __init__(self,parent):
        global tura

        tura=0

        self.parent=parent

        b0=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b0.grid(row=0,column=0,sticky=NSEW)

        b1=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b1.grid(row=0,column=1,sticky=NSEW)

        b2=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b2.grid(row=0,column=2,sticky=NSEW)

        b3=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b3.grid(row=1,column=0,sticky=NSEW)

        b4=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b4.grid(row=1,column=1,sticky=NSEW)

        b5=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b5.grid(row=1,column=2,sticky=NSEW)

        b6=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b6.grid(row=2,column=0,sticky=NSEW)

        b7=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b7.grid(row=2,column=1,sticky=NSEW)

        b8=Label(self.parent,text='',font=('Arial',30),width=7,height=3,relief='groove')
        b8.grid(row=2,column=2,sticky=NSEW)

        def enter(event):
            event.widget.config(bg='black')
        def left(event):
            event.widget.config(bg='white')

        def adaugare(event):
            global tura
            if event.widget['state']!='disabled':
                if tura%2==0:
                    event.widget.config(text='X')
                else:
                    event.widget.config(text='O')
                event.widget.config(state='disabled')
                tura+=1
        def verificare(event):
            def joc_nou():
                golire(self.parent)
                joc(self.parent)

            if b0['text']==b1['text']==b2['text'] and b0['state']==b1['state']==b2['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b3['text']==b4['text']==b5['text'] and b3['state']==b4['state']==b5['state']=='disabled':
                terminare(self.parent,b3['text'],joc_nou)
            elif b6['text']==b7['text']==b8['text'] and b6['state']==b7['state']==b8['state']=='disabled':
                terminare(self.parent,b6['text'],joc_nou)
            elif b0['text']==b3['text']==b6['text'] and b0['state']==b3['state']==b6['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b1['text']==b4['text']==b7['text'] and b1['state']==b4['state']==b7['state']=='disabled':
                terminare(self.parent,b1['text'],joc_nou)
            elif b2['text']==b5['text']==b8['text'] and b2['state']==b5['state']==b8['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b0['text']==b4['text']==b8['text'] and b0['state']==b4['state']==b8['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b2['text']==b4['text']==b6['text'] and b2['state']==b4['state']==b6['state']=='disabled':
                terminare(self.parent,b0['text'],joc_nou)
            elif b0['state']==b1['state']==b2['state']==b3['state']==b4['state']==b5['state']==b6['state']==b7['state']==b8['state']=='disabled':
                terminare(self.parent,'Nimeni',joc_nou)

        b0.bind("<Enter>",enter)
        b0.bind("<Leave>",left)

        b1.bind("<Enter>",enter)
        b1.bind("<Leave>",left)

        b2.bind("<Enter>",enter)
        b2.bind("<Leave>",left)

        b3.bind("<Enter>",enter)
        b3.bind("<Leave>",left)

        b4.bind("<Enter>",enter)
        b4.bind("<Leave>",left)

        b5.bind("<Enter>",enter)
        b5.bind("<Leave>",left)

        b6.bind("<Enter>",enter)
        b6.bind("<Leave>",left)

        b7.bind("<Enter>",enter)
        b7.bind("<Leave>",left)

        b8.bind("<Enter>",enter)
        b8.bind("<Leave>",left)

        b0.bind("<Button-1>",adaugare,add="+")

        b1.bind("<Button-1>",adaugare,add="+")

        b2.bind("<Button-1>",adaugare,add="+")

        b3.bind("<Button-1>",adaugare,add="+")

        b4.bind("<Button-1>",adaugare,add="+")

        b5.bind("<Button-1>",adaugare,add="+")

        b6.bind("<Button-1>",adaugare,add="+")

        b7.bind("<Button-1>",adaugare,add="+")

        b8.bind("<Button-1>",adaugare,add="+")

        #verificare
        b0.bind("<Button-1>",verificare,add="+")

        b1.bind("<Button-1>",verificare,add="+")

        b2.bind("<Button-1>",verificare,add="+")

        b3.bind("<Button-1>",verificare,add="+")

        b4.bind("<Button-1>",verificare,add="+")

        b5.bind("<Button-1>",verificare,add="+")

        b6.bind("<Button-1>",verificare,add="+")

        b7.bind("<Button-1>",verificare,add="+")

        b8.bind("<Button-1>",verificare,add="+")

if __name__=='__main__':
    root=Tk()
    joc(root)
    root.mainloop()