问:
Association Rule - Non-Binary Items
I have studied association rules and know how to implement the algorithm on the classic basket of goods problem, such as:

```<code>Transaction ID   Potatoes  Eggs   Milk
A                   1       0       1
B                   0       1       1
</code>```

In this problem each item has a binary identifier. 1 indicates the basket contains the good, 0 indicates it does not.

But what would be the best way to model a basket which can contain many of the same good? E.g., take the below, very unrealistic example.

```<code>Transaction ID   Potatoes  Eggs   Milk
A                   5       0       178
B                   0       35      7
</code>```

Using binary indicators in this case would obviously be losing a lot of information and I am seeking a model which takes into account not only the presence of items in the basket, but also the frequency that the items occur.

What would be a suitable algorithm for this problem?

In my actual data there are over one hundred items and, based on the profile of a user's basket, I would like to calculate the probabilities of the customer consuming the other available items.

答:
I think if you really want to have probabilities is to encode your data in a probabilistic way. Bayesian or Markov networks might be a feasible way. Nevertheless without having a reasonable structure this will be computational extremely expansive. For three item types this, however, seems to be feasible

I would try to go for a Neural Network Autoencoder if you have many more item types. If there is some dependency in the data it will discover that.

For the above example you could use a network with three input, two hidden and three output neurons.

A little bit more fancy would be to use 3 fully connected layers with drop out in the middle layer.

Title: Association Rule - Non-Binary Items

Body:
I have studied association rules and know how to implement the algorithm on the classic basket of goods problem, such as:

Transaction ID   Potatoes  Eggs   Milk
A                   1       0       1
B                   0       1       1

In this problem each item has a binary identifier. 1 indicates the basket contains the good, 0 indicates it does not.

But what would be the best way to model a basket which can contain many of the same good? E.g., take the below, very unrealistic example.

Transaction ID   Potatoes  Eggs   Milk
A                   5       0       178
B                   0       35      7

Using binary indicators in this case would obviously be losing a lot of information and I am seeking a model which takes into account not only the presence of items in the basket, but also the frequency that the items occur.

What would be a suitable algorithm for this problem?

In my actual data there are over one hundred items and, based on the profile of a user's basket, I would like to calculate the probabilities of the customer consuming the other available items.


来源: stackexchange

问:
Excel counter for when a Cell with streaming data increases?
I have a single cell that streams live data.  I'm trying to add a counter to another cell, such that each time the single streaming data cell changes, the counter increases.  (The data coming in is only increasing, so each time it increases, the counter should increase).

Any way to do this w/o a VBA macro?  Otherwise VBA code will help.  thanks

答:
This should work in the worksheet_Change event.
In this example, the streaming data would be in cell(14,9) and the counter would be in cell(1,1)</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Row = 14 And Target.Column = 9 Then
    Range("A1").Value = Range("A1").Value + 1
  End If
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This should work in the worksheet_Change event.
In this example, the streaming data would be in cell(14,9) and the counter would be in cell(1,1)

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Row = 14 And Target.Column = 9 Then
    Range("A1").Value = Range("A1").Value + 1
  End If
End Sub


问:
How can I get a HTML web page from a Windows Mobile Application?
I'm working with C#.net developing applications for windows mobile 6, and i need get the HTML code from a web page, i mean, i need download the page and then get the code or parse it to string.

someone know how can i do it?

I know there is the WebClient Class for desktop app, but i didn't find something like that for mobile app

答: Use the System.Net.WebClient class and call DownloadStringAsync to download any resource from the web asynchronously.</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Rich


问:
paintComponent not being called at the right time
I'm trying to write an app that goes something like this:

- Display a dialog

- When user clicks OK, close dialog, go to main app

Here are the relevant code snippets:

```<code>public class Owari extends JPanel implements ActionListener, MouseListener, Runnable {

// FIELDS
JFrame frame;
JTextField IP;
String IPAddress;

static final int SERVER_MODE = 0;
static final int CLIENT_MODE = 1;
int mode;

OwariBoard board;

  public static void main( String[] args ) {
    SwingUtilities.invokeLater( new Owari() );
  }

  Owari() {
    setPreferredSize( new Dimension( WIDTH, HEIGHT ) );
    board = new OwariBoard();
  }

  void main() {
    this.addMouseListener( this );
    frame.dispose();
    frame = new JFrame( "Owari" );
    frame.setContentPane( this );
    frame.pack();
    frame.setVisible(true);
    if ( mode == SERVER_MODE ) {
      server();
    }
    if ( mode == CLIENT_MODE ) {
      client();
    }
  }

  public void run() {
    frame = new JFrame( "Owari" );
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    JPanel init = new JPanel( new GridBagLayout() );
    frame.setContentPane( init );

    add some components to the init panel including a button with
    this as its actionListener and OK as its command.
    frame.pack();
    frame.setVisible( true );
  }

  public void actionPerformed( ActionEvent e ) {
    if ( e.getActionCommand().equals( "Client" ) ) {
      mode = CLIENT_MODE;
      IP.setVisible( true );
    }
    else if ( e.getActionCommand().equals( "Server" ) ) {
      mode = SERVER_MODE;
      IP.setVisible( false );
    }
    else {
      IPAddress = IP.getText();
      main();
    }
  }

  public void paintComponent( Graphics g ) {
    super.paintComponent( g );
    System.out.println( "painting" );
    do some paintin
  }

  void server() {
    frame.setTitle( "Owari Server" );
    try {
    server = new ServerSocket( 666 );
    socket = server.accept();
    initIO();
    } catch ( IOException e ) {}
    yourTurn = true;
    System.out.println( "Got to end of server()" ); // At this point, the window
                                                       DOES get painted
</code>```

What happens is the following:

The initial dialog displays:

I click the OK button.
The main window gets resized to the preferred size of the main app but it doesn't get painted, it's just transparent (shown here with this page as the background, heh):

http://imgur.com/6Ssij.jpg

I can tell the paintComponent method hasn't been called because "painting" isn't printed to the console.
However, "got to this point in the program" DOES get printed, so the program isn't hanging, it's just not calling paintComponent.
Then when I launch a client and connect, the app finally gets painted, and "painting" and "got a client" get printed to the console.
Also later on in the app, calls to repaint() are delayed (ie paintComponent is actually called later in the program than when the call to repaint() is made).

I also tried replacing the initial dialog using sthing along the lines of

```<code>public void main
  frame.getRootPane.removeAll()
  frame.setContentPane(this)
  frame.getRootPane().revalidate()
  frame.pack()
</code>```

Exact same result.

tl;dr paintcomponent isn't being called when i want it to, what do?

Bumping for some more info: the call to repaint() is done before the call to sever.accept() So why does it not repaint() before hanging at the server.accept() call?

答:
openasocketandwaitforaclient

Your code is executing in the Event Dispatch Thread so the blocking socket is preventing the GUI from repainting itself.

YOu need to use a separate Thread for the socket. Read the section from the Swing tutorial on Concurrency for an explanation and a solution.

Body:
I'm trying to write an app that goes something like this:

- Display a dialog

- When user clicks OK, close dialog, go to main app

Here are the relevant code snippets:

public class Owari extends JPanel implements ActionListener, MouseListener, Runnable {

// FIELDS
JFrame frame;
JTextField IP;
String IPAddress;

static final int SERVER_MODE = 0;
static final int CLIENT_MODE = 1;
int mode;

OwariBoard board;

  public static void main( String[] args ) {
    SwingUtilities.invokeLater( new Owari() );
  }

  Owari() {
    setPreferredSize( new Dimension( WIDTH, HEIGHT ) );
    board = new OwariBoard();
  }

  void main() {
    this.addMouseListener( this );
    frame.dispose();
    frame = new JFrame( "Owari" );
    frame.setContentPane( this );
    frame.pack();
    frame.setVisible(true);
    if ( mode == SERVER_MODE ) {
      server();
    }
    if ( mode == CLIENT_MODE ) {
      client();
    }
  }

  public void run() {
    frame = new JFrame( "Owari" );
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    JPanel init = new JPanel( new GridBagLayout() );
    frame.setContentPane( init );

    add some components to the init panel including a button with
    this as its actionListener and OK as its command.
    frame.pack();
    frame.setVisible( true );
  }

  public void actionPerformed( ActionEvent e ) {
    if ( e.getActionCommand().equals( "Client" ) ) {
      mode = CLIENT_MODE;
      IP.setVisible( true );
    }
    else if ( e.getActionCommand().equals( "Server" ) ) {
      mode = SERVER_MODE;
      IP.setVisible( false );
    }
    else {
      IPAddress = IP.getText();
      main();
    }
  }

  public void paintComponent( Graphics g ) {
    super.paintComponent( g );
    System.out.println( "painting" );
    do some paintin
  }

  void server() {
    frame.setTitle( "Owari Server" );
    try {
    server = new ServerSocket( 666 );
    socket = server.accept();
    initIO();
    } catch ( IOException e ) {}
    yourTurn = true;
    System.out.println( "Got to end of server()" ); // At this point, the window
                                                       DOES get painted

What happens is the following:

The initial dialog displays:

I click the OK button.
The main window gets resized to the preferred size of the main app but it doesn't get painted, it's just transparent (shown here with this page as the background, heh):

http://imgur.com/6Ssij.jpg

I can tell the paintComponent method hasn't been called because "painting" isn't printed to the console.
However, "got to this point in the program" DOES get printed, so the program isn't hanging, it's just not calling paintComponent.
Then when I launch a client and connect, the app finally gets painted, and "painting" and "got a client" get printed to the console.
Also later on in the app, calls to repaint() are delayed (ie paintComponent is actually called later in the program than when the call to repaint() is made).

I also tried replacing the initial dialog using sthing along the lines of

public void main
  frame.getRootPane.removeAll()
  frame.setContentPane(this)
  frame.getRootPane().revalidate()
  frame.pack()

Exact same result.

tl;dr paintcomponent isn't being called when i want it to, what do?

Bumping for some more info: the call to repaint() is done before the call to sever.accept() So why does it not repaint() before hanging at the server.accept() call?


问:
Is it possible to transfer data to SQL Server from an unconventional database
My company has a SQL Server database which they would like to populate with data from a hierarchical database (as opposed to relational). I have already written a .net application to map its schema to a relational database and have successfully done that. However my problem is that the tech being used here is so old that I see no obvious way of data transfer.

However, I have certain ideas about how I can do this. This involves having to write file scans in my unconventional database and dump out files as csv. Then do a bulk upload into SQL Server. I do not appreciate this as there is the element of invalid data involved which terminates the bulk upload quite so often.

I was hoping to explore options around service broker. I was hoping to dump out live transactions where a record has changed in my database and then this can somehow be picked up?

Secondly I was also hoping to use something which if I dump out live or changed records in a file (I can format the file to whatever format is needed), can something suck it into SQL Server?

Any help would be greatly appreciated.

Regards,

Waqar

答:
Skip bulk insert.  The SQL Server xml data type lends itself to doing what you're doing.  If you can output data from your other system into an XML format, you can push that XML directly into an argument for a stored procedure.

After that, you can use the functions for the XML type to iterate through the data as needed.


问:
iOS 11 Core NFC - any sample code?
I just installed the first iOS 11 beta to an iPhone 7 and am interested in trying the NFC. There's nothing about it in settings.  I am wondering if there's any sample code out there showing how to read a tag. Can anyone show how to use the Core NFC SDK, in a code snippet?</p>

答:
Updated for second Xcode beta.

Add the NFC capability to your app from the Developer Center. Identifiers -> App IDs -> enable "NFC Tag Reading".

If your project does not have an entitlement file, let Xcode create one for you by just activating and then subsequently deactivating any capability from within Xcode -> Project Targets -> Capabilities. You will find a new [AppName].entitlements file in your project navigator. Right-click on that file and select "Open as -> Source Code". Enter the following entry manually between <dict></dict>:

```<code><key>com.apple.developer.nfc.readersession.formats</key>
<array>
    <string>NDEF</string>
</array>
</code>```

As soon as Xcode 9 allows enabling NFC Tag Reading from the Capabilities selection this step becomes obsolete because all you have to do is to enable it there. The current (first) Beta version does not support this.

You also need to enter a usage description for the privacy warning iOS will show the user. (At the moment (beta 1) this warning will be displayed when the device is ready to scan and shows a native system dialogue which will include this message. However, this seems to be unploished.) Open your target's Info.plist and start typing "Privacy" and you can scroll down to "Privacy - NFC Usage Description" to select it by hitting return. Enter a meaningful explanation to your user in the right column.

Now you should be able to import CoreNFC, in Swift:

```<code>import CoreNFC
</code>```

Then head over to Apple's documentation.

 Important: If the compiler returns an error with No such module 'CoreNFC' check if you have selected an actual iOS 11 device to build for, not a simulator. It also has to be the iPhone 7 or 7 plus. This might change in a future version, but testing NFC will only ever be fully working with actual hardware. (cp. Core Bluetooth where you can run on Simulator but not test the actual capabilities.) Beta 2 doesn't have this issue anymore. However, actual hardware in form of iPhone 7/p is still required for actual testing.

Title: iOS 11 Core NFC - any sample code?

Body:
Updated for second Xcode beta.

Add the NFC capability to your app from the Developer Center. Identifiers -> App IDs -> enable "NFC Tag Reading".

If your project does not have an entitlement file, let Xcode create one for you by just activating and then subsequently deactivating any capability from within Xcode -> Project Targets -> Capabilities. You will find a new [AppName].entitlements file in your project navigator. Right-click on that file and select "Open as -> Source Code". Enter the following entry manually between <dict></dict>:

<key>com.apple.developer.nfc.readersession.formats</key>
<array>
    <string>NDEF</string>
</array>

As soon as Xcode 9 allows enabling NFC Tag Reading from the Capabilities selection this step becomes obsolete because all you have to do is to enable it there. The current (first) Beta version does not support this.

You also need to enter a usage description for the privacy warning iOS will show the user. (At the moment (beta 1) this warning will be displayed when the device is ready to scan and shows a native system dialogue which will include this message. However, this seems to be unploished.) Open your target's Info.plist and start typing "Privacy" and you can scroll down to "Privacy - NFC Usage Description" to select it by hitting return. Enter a meaningful explanation to your user in the right column.

Now you should be able to import CoreNFC, in Swift:

import CoreNFC

Then head over to Apple's documentation.

 Important: If the compiler returns an error with No such module 'CoreNFC' check if you have selected an actual iOS 11 device to build for, not a simulator. It also has to be the iPhone 7 or 7 plus. This might change in a future version, but testing NFC will only ever be fully working with actual hardware. (cp. Core Bluetooth where you can run on Simulator but not test the actual capabilities.) Beta 2 doesn't have this issue anymore. However, actual hardware in form of iPhone 7/p is still required for actual testing.


问:
How can I make my shell script detect a state change across multiple invocations?
I am using the following "script" to monitor a Port on a Server:

```<code>l_TELNET=`echo "quit" | telnet server.domain.tld 12345 | grep "Escape character is"`
if [ "$?" -ne 0 ]; then
  echo "Connection to $SERVER on port $PORT failed"
    #Something happens here if Service (port) down
  exit 1
else
    #Something happens here if Service (port) up
  exit 0
fi
</code>```

How can I modify this to only execute the "Service down" section the first time a service is detected to be down (until it's next back up), as opposed to every five minutes while the service continues to be down?

答:
What about using temp files?</p>

```<code>l_TELNET=`echo "quit" | telnet server.domain.tld 12345 | grep "Escape character is"`
if [ "$?" -ne 0 ]; then
    if  [ ! -f /tmp/12345down]; then
        echo "Connection to $SERVER on port $PORT failed"
        #Something happens here if Service (port) down
        touch /tmp/12345down
        exit 1
    fi
    exit 0
else
    #Something happens here if Service (port) up
    if  [ -f /tmp/12345down]; then
        rm -f /tmp/12345down
    fi
    exit 0
fi
</code>```

Body:
I am using the following "script" to monitor a Port on a Server:

l_TELNET=`echo "quit" | telnet server.domain.tld 12345 | grep "Escape character is"`
if [ "$?" -ne 0 ]; then
  echo "Connection to $SERVER on port $PORT failed"
    #Something happens here if Service (port) down
  exit 1
else
    #Something happens here if Service (port) up
  exit 0
fi

How can I modify this to only execute the "Service down" section the first time a service is detected to be down (until it's next back up), as opposed to every five minutes while the service continues to be down?

Body:
What about using temp files?

l_TELNET=`echo "quit" | telnet server.domain.tld 12345 | grep "Escape character is"`
if [ "$?" -ne 0 ]; then
    if  [ ! -f /tmp/12345down]; then
        echo "Connection to $SERVER on port $PORT failed"
        #Something happens here if Service (port) down
        touch /tmp/12345down
        exit 1
    fi
    exit 0
else
    #Something happens here if Service (port) up
    if  [ -f /tmp/12345down]; then
        rm -f /tmp/12345down
    fi
    exit 0
fi


问:
Regular expression for accepting only alphabets and within 2 to 5 char length
For example:

Accept:

text

Text

Don't accept:

text1

text@

123@#

Te12$

答:
Try this:

const isValid = str => /^[a-zA-Z]{2,5}$/.test(str);
console.log(isValid('test')); // true
console.log(isValid('Test')); // true
console.log(isValid('test1')); // false
console.log(isValid('text@')); // false
console.log(isValid('123@#')); // false
console.log(isValid('Te12$')); // false```


问:
Windows Forms form opens in the background if I open an OpenFileDialog in its Load event
I need the user to select a file to open before they can use the main form in the program I'm writing. I wrote the following in the form's load event handler:

```<code>private void MainForm_Load(object sender, EventArgs e)
{
    if (openXmlFileDialog.ShowDialog() != DialogResult.OK)
        Application.Exit();

    fileName = openXmlFileDialog.FileName;
    Activate();
}
</code>```

After this, MainForm appears in the background in spite of calling Activate() on it.

Another problem is that if the user presses Cancel and Application.Exit() is called, it has no effect.

答: Put the code inside the Shown event instead.

Body:
I need the user to select a file to open before they can use the main form in the program I'm writing. I wrote the following in the form's load event handler:

private void MainForm_Load(object sender, EventArgs e)
{
    if (openXmlFileDialog.ShowDialog() != DialogResult.OK)
        Application.Exit();

    fileName = openXmlFileDialog.FileName;
    Activate();
}

After this, MainForm appears in the background in spite of calling Activate() on it.

Another problem is that if the user presses Cancel and Application.Exit() is called, it has no effect.


问:
Golang dynamic sizing slice when reading a file using buffo.read
I have a problem where, I need to use bufio.read to read a tsv file line by line and I need to record how many bytes each line Ive read is.

The problem is, It seems like I can't just initialize an empty slice and pass it into bufio.read and expect the slice to contain the entire line of the file.

```<code>file, _ := os.Open("file.tsv")

reader := bufio.NewReader(file)

b := make([]byte, 10)
for {
    bytesRead, err:= reader.Read(b)
    fmt.Println(bytesRead, b)
    if err != nil {
        break
    }
}
</code>```

So, for this example, since I specified the slice to be 10 bytes, the reader will read at most 10 bytes even if the line is bigger than 10 bytes.

However:

```<code>file, _ := os.Open("file.tsv")

reader := bufio.NewReader(file)

b := byte{} //or var b []byte
for {
    bytesRead, err:= reader.Read(b)
    fmt.Println(bytesRead, b)
    if err != nil {
        break
    }
}
</code>```

This will always read 0 bytes and I assume its because the buffer is length 0 or capacity 0.

How do I read a file Line by line, save the entire line in a variable or buffer, and return exactly how many bytes Ive read?

Thanks!

答:
If you want to read line by line, and you're using a buffered reader, use the buffered reader's ReadBytes method.

```<code>line,err := reader.ReadBytes('\n')
</code>```

This will give you a full line, one line at a time, regardless of byte length.

Body:
I have a problem where, I need to use bufio.read to read a tsv file line by line and I need to record how many bytes each line Ive read is.

The problem is, It seems like I can't just initialize an empty slice and pass it into bufio.read and expect the slice to contain the entire line of the file.

file, _ := os.Open("file.tsv")

reader := bufio.NewReader(file)

b := make([]byte, 10)
for {
    bytesRead, err:= reader.Read(b)
    fmt.Println(bytesRead, b)
    if err != nil {
        break
    }
}

So, for this example, since I specified the slice to be 10 bytes, the reader will read at most 10 bytes even if the line is bigger than 10 bytes.

However:

file, _ := os.Open("file.tsv")

reader := bufio.NewReader(file)

b := byte{} //or var b []byte
for {
    bytesRead, err:= reader.Read(b)
    fmt.Println(bytesRead, b)
    if err != nil {
        break
    }
}

This will always read 0 bytes and I assume its because the buffer is length 0 or capacity 0.

How do I read a file Line by line, save the entire line in a variable or buffer, and return exactly how many bytes Ive read?

Thanks!

Body:
If you want to read line by line, and you're using a buffered reader, use the buffered reader's ReadBytes method.

line,err := reader.ReadBytes('\n')

This will give you a full line, one line at a time, regardless of byte length.


问:
Escape unicode in golang
I'm trying to read a file containing unicode and display it as normal string:

example.txt

processSpecification=Sp\u00e9cification du processus

materialDomain=Domaine mat\u00e9riel

Expected result:

processSpecification=Spécification du processus

materialDomain=Domaine matériel

Actual result:

processSpecification=Sp\u00e9cification du processus

materialDomain=Domaine mat\u00e9riel

I foundhow to do this in 5 min in python :
for decodedLine in open('Z:\m1msgcatalog\PLMVocabulary_ds6w_fr.properties', 'r', encoding='unicode-escape'):
    print(decodedLine)

but I don't get how to do this in golang

答:
Perhaps you can use strconv.Unquote? (But be careful... that does more than just replace \u sequences.)

```<code>package main

import (
    "fmt"
    "strconv"
)

func main() {
    input := `processSpecification=Sp\u00e9cification du processus`
    fmt.Println(input)
    fmt.Println(strconv.Unquote("\"" + input + "\""))
}

// Output:
// processSpecification=Sp\u00e9cification du processus
// processSpecification=Spécification du processus
</code>```

https://play.golang.org/p/Uq4vIdNyya

Title: Escape unicode in golang

Body:
Perhaps you can use strconv.Unquote? (But be careful... that does more than just replace \u sequences.)

package main

import (
    "fmt"
    "strconv"
)

func main() {
    input := `processSpecification=Sp\u00e9cification du processus`
    fmt.Println(input)
    fmt.Println(strconv.Unquote("\"" + input + "\""))
}

// Output:
// processSpecification=Sp\u00e9cification du processus
// processSpecification=Spécification du processus

https://play.golang.org/p/Uq4vIdNyya


问:
How to bind data locally with Kendo UI diagram?
We use Kendo UI diagram to represent a BPMN diagram (activity flow).

We also use Angular.

How can I bind an array of objects to the shapes Data Source, aka, every change to this array will mimic the same change in the Kendo UI diagram?

Update:
I found an example without Angular JS: http://dojo.telerik.com/ILUCOQ

答:
Here you can defined scope and pass to function as a parameter and you can change dynamically change scope, and on scope change re-call those function that render UI with new parameter[scope].</p>

```<code><!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/diagram/angular">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.504/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.504/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.504/styles/kendo.material.mobile.min.css" />

<script src="https://kendo.cdn.telerik.com/2017.2.504/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.504/js/angular.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.504/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example" ng-app="KendoDemos">
<div class="demo-section k-content wide" ng-controller="MyCtrl">
  <div kendo-diagram k-options="options"></div>
</div>
</div>
<script>
angular.module("KendoDemos", ["kendo.directives"])
    .controller("MyCtrl", function($scope){
                    $scope.change = [3,3,2]; // You Can Dynamically Change this scope that will reflect the UI

        $scope.options = {
            dataSource: {
                data: diagramNodes($scope.c),
                schema: {
                    model: {
                        children: "items"
                    }
                }
            },
            layout: {
                type: "tree",
                subtype: "down",
                horizontalSeparation: 30,
                verticalSeparation: 20
            },
            shapeDefaults: {
                width: 40,
                height: 40
            }
        };
    })

function diagramNodes(data) {
        var root = { name: "0", items: [] };
        addNodes(root, data);
        return [root];
    }

    function addNodes(root, levels) {
        if (levels.length > 0) {
            for (var i = 0; i < levels[0]; i++) {
                var node = { name: "0", items: [] };
                root.items.push(node);

                addNodes(node, levels.slice(1));
            }
        }
    }
</script>
</body>
</html>
</code>```

Body:
Here you can defined scope and pass to function as a parameter and you can change dynamically change scope, and on scope change re-call those function that render UI with new parameter[scope].

<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/diagram/angular">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.504/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.504/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.504/styles/kendo.material.mobile.min.css" />

<script src="https://kendo.cdn.telerik.com/2017.2.504/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.504/js/angular.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.504/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example" ng-app="KendoDemos">
<div class="demo-section k-content wide" ng-controller="MyCtrl">
  <div kendo-diagram k-options="options"></div>
</div>
</div>
<script>
angular.module("KendoDemos", ["kendo.directives"])
    .controller("MyCtrl", function($scope){
                    $scope.change = [3,3,2]; // You Can Dynamically Change this scope that will reflect the UI

        $scope.options = {
            dataSource: {
                data: diagramNodes($scope.c),
                schema: {
                    model: {
                        children: "items"
                    }
                }
            },
            layout: {
                type: "tree",
                subtype: "down",
                horizontalSeparation: 30,
                verticalSeparation: 20
            },
            shapeDefaults: {
                width: 40,
                height: 40
            }
        };
    })

function diagramNodes(data) {
        var root = { name: "0", items: [] };
        addNodes(root, data);
        return [root];
    }

    function addNodes(root, levels) {
        if (levels.length > 0) {
            for (var i = 0; i < levels[0]; i++) {
                var node = { name: "0", items: [] };
                root.items.push(node);

                addNodes(node, levels.slice(1));
            }
        }
    }
</script>
</body>
</html>


问:
Stop CSS3 opacity animation before 1
I'm trying to animate a certain div opacity from 0 to 0.6, but it seems that at the end of the animation it jumps to 1.

What am I missing?

#test {
  width: 200px;
  height: 200px;
  background-color: #900;
  animation: fadein 2s;
  -moz-animation: fadein 2s;
  -webkit-animation: fadein 2s;
  -o-animation: fadein 2s;
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-moz-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-webkit-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-o-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test"></div></code>```

答:
You need to specify animation-fill-mode: forwards if you want the element's CSS to remain at the last step of the animation.

https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode

Forwards: The target will retain the computed values set by the last keyframe encountered during execution.

#test {
  width: 200px;
  height: 200px;
  background-color: #900;
  animation: fadein 2s forwards;
  -moz-animation: fadein 2s forwards;
  -webkit-animation: fadein 2s forwards;
  -o-animation: fadein 2s forwards;
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-moz-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-webkit-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-o-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test"></div></code>```

Title: Stop CSS3 opacity animation before 1

Body:
You need to specify animation-fill-mode: forwards if you want the element's CSS to remain at the last step of the animation.

https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode

Forwards: The target will retain the computed values set by the last keyframe encountered during execution.

#test {
  width: 200px;
  height: 200px;
  background-color: #900;
  animation: fadein 2s forwards;
  -moz-animation: fadein 2s forwards;
  -webkit-animation: fadein 2s forwards;
  -o-animation: fadein 2s forwards;
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-moz-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-webkit-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-o-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

<div id="test"></div>


问:
PHP preg_replace all matches
I want to replace all matches with using preg_replace but it only works once.

Here is function i used:

```<code>function bbc2html($text) {
    $find = array(
        '~\[spoiler\](.*?)\[/spoiler\]~s'
    );
    $replace = array(
        '<font color="red"><b>ATTENTION: SPOILER ALARM!</b></font><br>$1'
    );
    return preg_replace($find,$replace,$text);
}
</code>```

Input:

```<code>echo bbc2html('[spoiler]Its a spoiler[/spoiler]');
echo bbc2html('[spoiler][spoiler]Its a multiple spoiler[/spoiler][/spoiler]');
</code>```

Output:

```<code><font color="red"><b>ATTENTION: SPOILER ALARM!</b></font><br>Its a spoiler
<font color="red"><b>ATTENTION: SPOILER ALARM!</b></font><br>[spoiler]Its a multiple spoiler[/spoiler]
</code>```

答:
```<code>function bbc2html($text) {
$find = array(
    '~(\[spoiler\])+(.*?)(\[/spoiler\])+~s'
);
$replace = array(
    '<font color="red"><b>ATTENTION: SPOILER ALARM!</b></font><br>$2'
);
return preg_replace($find,$replace,$text);
}
</code>```

Does it work?

Title: PHP preg_replace all matches

Body:
I want to replace all matches with using preg_replace but it only works once.

Here is function i used:

function bbc2html($text) {
    $find = array(
        '~\[spoiler\](.*?)\[/spoiler\]~s'
    );
    $replace = array(
        'ATTENTION: SPOILER ALARM!
$1'
    );
    return preg_replace($find,$replace,$text);
}

Input:

echo bbc2html('[spoiler]Its a spoiler[/spoiler]');
echo bbc2html('[spoiler][spoiler]Its a multiple spoiler[/spoiler][/spoiler]');

Output:

ATTENTION: SPOILER ALARM!
Its a spoiler
ATTENTION: SPOILER ALARM!
[spoiler]Its a multiple spoiler[/spoiler]

Body:
function bbc2html($text) {
$find = array(
    '~(\[spoiler\])+(.*?)(\[/spoiler\])+~s'
);
$replace = array(
    '<font color="red"><b>ATTENTION: SPOILER ALARM!</b></font><br>$2'
);
return preg_replace($find,$replace,$text);
}

Does it work?

ContentLicense: CC BY-SA 4.0


问:
PowerShell / C# SetAuditRuleProtection() Not Working On Some Folders
I've been battling with this for a while now and can't find an explanation. I'm attempting to enable inheritance on a directory for audit rules. In this example, I'm setting the audit rule on c:\Program Files\Microsoft SQL Server\MSSQL12.NEWINSTANCE and propagating to all children. The directory c:\Program Files\Microsoft SQL Server\MSSQL12.NEWINSTANCE\MSSQL\Backup gets the audit rule via inheritance, but the Logs directory does not. Here's a snippet of the code I'm using to enable inheritance:

```<code>$Path = "C:\Program Files\Microsoft SQL Server\MSSQL12.NEWINSTANCE\MSSQL\Log"

[System.IO.DirectoryInfo]$Info = New-Object -TypeName System.IO.DirectoryInfo($Path)

[System.Security.AccessControl.DirectorySecurity]$Acl = $Info.GetAccessControl()

$Acl.SetAuditRuleProtection($false, $false)

$Info.SetAccessControl($Acl)
</code>```

I've tried a number of combinations including Get-Acl, Set-Acl, (Get-Item -Path $Path).GetAccessControl(), etc. It appears I can disable inheritance and remove the rules, but not disable inheritance and preserve the existing rules (via modifying the parameters for SetAuditRuleProtection).

All of this works if I do it via the GUI, so I don't believe it's some issue with the directory or my permissions. Any ideas/thoughts would be welcome.

答:
The trick for me was that you can't do this on a folder or file that does not currently have an SACL (System Access Control List, otherwise known as Audit Rule).  I wrote a function that sets the rule on the parent, then recursively iterates through all the children to set the rule, ensuring its being inherited, then removing the extra rule.</p>

```<code><#
.SYNOPSIS
 Sets auditing on the file or folder.

.DESCRIPTION
 Implements a File System Audit Rule on the file or folder.

.PARAMETER Path (Required)
 Specifies the file or folder on which to apply the audit rule.

.PARAMETER Principal (Required)
 Specifies the NTAccount name.

.PARAMETER Success (Optional, Required if "Failure" not present)
 Specifies to implement an audit rule for successes.

.PARAMETER Failure (Optional, Required if "Success" not present)
 Specifies to implement an audit rule for failures.

.PARAMETER Flags (Required)
 This is an array of two integers that indicate what to apply the audit rule to and what type of recursion should be used.

 Inheritance, Propagation:
 This folder only = 0,0
 This folder, subfolders and files = 3,0
 This folder and subfolders = 1,0
 This folder and files = 2,0
 Subfolders and files only = 3,2
 Subfolders only = 1,2
 Files only = 2,3

.EXAMPLE
 Set-Auditing
#>
function Set-Auditing {
  [CmdletBinding(SupportsShouldProcess=$true)]
  Param([Parameter(Mandatory=$true, ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [string]$Path,
        [Parameter(Mandatory=$true, ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [string]$Principal,
        [Parameter(Mandatory=$true, ValueFromPipeline=$false)] [ValidateSet("AppendData","ChangePermissions","CreateDirectories","CreateFiles","Delete","DeleteSubdirectoriesAndFiles","ExecuteFile","FullControl","ListDirectory","Modify","Read","ReadAndExecute","ReadAttributes","ReadData","ReadExtendedAttributes","ReadPermissions","Synchronize","TakeOwnership","Traverse","Write","WriteAttributes","WriteData","WriteExtendedAttributes")] [string[]]$Rights,
        [Parameter(Mandatory=$true, ValueFromPipeline=$false, ParameterSetName="Both")]
        [Parameter(Mandatory=$true, ValueFromPipeline=$false, ParameterSetName="Success")] [switch]$Success,
        [Parameter(Mandatory=$true, ValueFromPipeline=$false, ParameterSetName="Both")]
        [Parameter(Mandatory=$true, ValueFromPipeline=$false, ParameterSetName="Failure")] [switch]$Failure,
        [Parameter(Mandatory=$true, ValueFromPipeline=$false)] [int[]]$Flags)

  Begin {
    # Determine if audit rule exists
    if ($Success.IsPresent) { $AuditFlags=1 } else { $AuditFlags=0 }
    if ($Failure.IsPresent) { $AuditFlags+=2 }

    # Inheritance Flags
    # This folder only = 0
    # This folder, subfolders and files = 3
    # This folder and subfolders = 1
    # This folder and files = 2
    # Subfolders and files only = 3
    # Subfolders only = 1
    # Files only = 2

    # Propagation Flags
    # This folder only = 0
    # This folder, subfolders and files = 0
    # This folder and subfolders = 0
    # This folder and files = 0
    # Subfolders and files only = 2
    # Subfolders only = 2
    # Files only = 2

    # File System Rights
    $fsrAppendData                  =0x000004
    $fsrChangePermissions           =0x040000
    $fsrCreateDirectories           =0x000004
    $fsrCreateFiles                 =0x000002
    $fsrDelete                      =0x010000
    $fsrDeleteSubdirectoriesAndFiles=0x000040
    $fsrExecuteFile                 =0x000020
    $fsrFullControl                 =0x1F01FF
    $fsrListDirectory               =0x000001
    $fsrModify                      =0x0301BF
    $fsrRead                        =0x020089
    $fsrReadAndExecute              =0x0200A9
    $fsrReadAttributes              =0x000080
    $fsrReadData                    =0x000001
    $fsrReadExtendedAttributes      =0x000008
    $fsrReadPermissions             =0x020000
    $fsrSynchronize                 =0x100000
    $fsrTakeOwnership               =0x080000
    $fsrTraverse                    =0x000020
    $fsrWrite                       =0x000116
    $fsrWriteAttributes             =0x000100
    $fsrWriteData                   =0x000002
    $fsrWriteExtendedAttributes     =0x000010

    $RightValues=0
    for ($i=0; $i -lt $Rights.Count; $i++) {
     switch ($Rights[$i]) {
       "AppendData"                   { $RightValues=$RightValues -bor $fsrAppendData }
       "ChangePermissions"            { $RightValues=$RightValues -bor $fsrChangePermissions }
       "CreateDirectories"            { $RightValues=$RightValues -bor $fsrCreateDirectories }
       "CreateFiles"                  { $RightValues=$RightValues -bor $fsrCreateFiles }
       "Delete"                       { $RightValues=$RightValues -bor $fsrDelete }
       "DeleteSubdirectoriesAndFiles" { $RightValues=$RightValues -bor $fsrDeleteSubdirectoriesAndFiles }
       "ExecuteFile"                  { $RightValues=$RightValues -bor $fsrExecuteFile }
       "FullControl"                  { $RightValues=$RightValues -bor $fsrFullControl }
       "ListDirectory"                { $RightValues=$RightValues -bor $fsrListDirectory }
       "Modify"                       { $RightValues=$RightValues -bor $fsrModify }
       "Read"                         { $RightValues=$RightValues -bor $fsrRead }
       "ReadAndExecute"               { $RightValues=$RightValues -bor $fsrReadAndExecute }
       "ReadAttributes"               { $RightValues=$RightValues -bor $fsrReadAttributes }
       "ReadData"                     { $RightValues=$RightValues -bor $fsrReadData }
       "ReadExtendedAttributes"       { $RightValues=$RightValues -bor $fsrReadExtendedAttributes }
       "ReadPermissions"              { $RightValues=$RightValues -bor $fsrReadPermissions }
       "Synchronize"                  { $RightValues=$RightValues -bor $fsrSynchronize }
       "TakeOwnership"                { $RightValues=$RightValues -bor $fsrTakeOwnership }
       "Traverse"                     { $RightValues=$RightValues -bor $fsrTraverse }
       "Write"                        { $RightValues=$RightValues -bor $fsrWrite }
       "WriteAttributes"              { $RightValues=$RightValues -bor $fsrWriteAttributes }
       "WriteData"                    { $RightValues=$RightValues -bor $fsrWriteData }
       "WriteExtendedAttributes"      { $RightValues=$RightValues -bor $fsrWriteExtendedAttributes }
     }
    }

    Write-Verbose "Acquiring object $($FS.FullName)"
    $FS=Get-Item -Path $Path
    $ACL=Get-Acl -Path $Path -Audit
    $NothingToDo=$false
    for ($i=0; $i -lt $ACL.Audit.Count; $i++) {
      if ($ACL.Audit[$i].IdentityReference.Value -eq $Principal) {
        if ($ACL.Audit[$i].AuditFlags.value__ -eq $AuditFlags) {
          if ($ACL.Audit[$i].PropagationFlags.value__ -eq $Flags[1]) {
            if ($ACL.Audit[$i].InheritanceFlags.value__ -eq $Flags[0]) {
              if ($ACL.Audit[$i].FileSystemRights.value__ -eq $RightValues) { $NothingToDo=$true; Write-Verbose "Nothing to do" }
            }
          }
        }
      }
    }
  }

  Process {
    if (!$NothingToDo) {
      # There is one case where we will not propagage the rules.  This is when $Flags = 0,0
      if (($Flags[0] -eq 0) -and ($Flags[1] -eq 0)) { Write-Verbose "Flags = 0,0; no propagation necessary." }
      else {
        Write-Verbose "Setting Audit Rule"
        if ($Principal.Contains("\")) { $NTAccount=New-Object System.Security.Principal.NTAccount(($Principal.Split("\"))[0],($Principal.Split("\"))[1]) }
        else { $NTAccount=New-Object System.Security.Principal.NTAccount($Principal) }
        $FSAR=New-Object System.Security.AccessControl.FileSystemAuditRule($NTAccount,$RightValues,$Flags[0],$Flags[1],$AuditFlags)
        $FAR=New-Object System.Security.AccessControl.FileSystemAuditRule($NTAccount,$RightValues,$AuditFlags)
        $ACL.AddAuditRule($FSAR)
        $ACL.SetAuditRuleProtection($false, $true)
        Write-Verbose "Applying rule to $($ACL.Path.Replace('Microsoft.PowerShell.Core\FileSystem::',''))"
        $FS.SetAccessControl($ACL)

        # Now, ensure that all folders and files have inheritance enabled.
        $FS=Get-ChildItem -Path $Path -Recurse
        $FS=@($FS)
        for ($i=0; $i -lt $FS.Count; $i++) {
          Write-Verbose "Acquiring object $($FS[$i].FullName)"
          $ACL=Get-Acl -Path $FS[$i].FullName -Audit
          if (Test-Path $ACL.Path -PathType Leaf) { $ACL.AddAuditRule($FAR) } else { $ACL.AddAuditRule($FSAR) }
          $ACL.SetAuditRuleProtection($false, $true)
          $FS[$i].SetAccessControl($ACL)
          Write-Verbose "Applying rule to $($ACL.Path.Replace('Microsoft.PowerShell.Core\FileSystem::',''))"
          if (Test-Path $ACL.Path -PathType Leaf) { $ACL.RemoveAuditRule($FAR) > $null } else { $ACL.RemoveAuditRule($FSAR) > $null }
          Write-Verbose "Removing extra rule from $($ACL.Path)"
          $FS[$i].SetAccessControl($ACL)
        }
      }
    }
    else { Write-Verbose "Nothing to do." }
  }
}
</code>```

Body:
I've been battling with this for a while now and can't find an explanation. I'm attempting to enable inheritance on a directory for audit rules. In this example, I'm setting the audit rule on c:\Program Files\Microsoft SQL Server\MSSQL12.NEWINSTANCE and propagating to all children. The directory c:\Program Files\Microsoft SQL Server\MSSQL12.NEWINSTANCE\MSSQL\Backup gets the audit rule via inheritance, but the Logs directory does not. Here's a snippet of the code I'm using to enable inheritance:

$Path = "C:\Program Files\Microsoft SQL Server\MSSQL12.NEWINSTANCE\MSSQL\Log"

[System.IO.DirectoryInfo]$Info = New-Object -TypeName System.IO.DirectoryInfo($Path)

[System.Security.AccessControl.DirectorySecurity]$Acl = $Info.GetAccessControl()

$Acl.SetAuditRuleProtection($false, $false)

$Info.SetAccessControl($Acl)

I've tried a number of combinations including Get-Acl, Set-Acl, (Get-Item -Path $Path).GetAccessControl(), etc. It appears I can disable inheritance and remove the rules, but not disable inheritance and preserve the existing rules (via modifying the parameters for SetAuditRuleProtection).

All of this works if I do it via the GUI, so I don't believe it's some issue with the directory or my permissions. Any ideas/thoughts would be welcome.

Body:
The trick for me was that you can't do this on a folder or file that does not currently have an SACL (System Access Control List, otherwise known as Audit Rule).  I wrote a function that sets the rule on the parent, then recursively iterates through all the children to set the rule, ensuring its being inherited, then removing the extra rule.

<#
.SYNOPSIS
 Sets auditing on the file or folder.

.DESCRIPTION
 Implements a File System Audit Rule on the file or folder.

.PARAMETER Path (Required)
 Specifies the file or folder on which to apply the audit rule.

.PARAMETER Principal (Required)
 Specifies the NTAccount name.

.PARAMETER Success (Optional, Required if "Failure" not present)
 Specifies to implement an audit rule for successes.

.PARAMETER Failure (Optional, Required if "Success" not present)
 Specifies to implement an audit rule for failures.

.PARAMETER Flags (Required)
 This is an array of two integers that indicate what to apply the audit rule to and what type of recursion should be used.

 Inheritance, Propagation:
 This folder only = 0,0
 This folder, subfolders and files = 3,0
 This folder and subfolders = 1,0
 This folder and files = 2,0
 Subfolders and files only = 3,2
 Subfolders only = 1,2
 Files only = 2,3

.EXAMPLE
 Set-Auditing
#>
function Set-Auditing {
  [CmdletBinding(SupportsShouldProcess=$true)]
  Param([Parameter(Mandatory=$true, ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [string]$Path,
        [Parameter(Mandatory=$true, ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [string]$Principal,
        [Parameter(Mandatory=$true, ValueFromPipeline=$false)] [ValidateSet("AppendData","ChangePermissions","CreateDirectories","CreateFiles","Delete","DeleteSubdirectoriesAndFiles","ExecuteFile","FullControl","ListDirectory","Modify","Read","ReadAndExecute","ReadAttributes","ReadData","ReadExtendedAttributes","ReadPermissions","Synchronize","TakeOwnership","Traverse","Write","WriteAttributes","WriteData","WriteExtendedAttributes")] [string[]]$Rights,
        [Parameter(Mandatory=$true, ValueFromPipeline=$false, ParameterSetName="Both")]
        [Parameter(Mandatory=$true, ValueFromPipeline=$false, ParameterSetName="Success")] [switch]$Success,
        [Parameter(Mandatory=$true, ValueFromPipeline=$false, ParameterSetName="Both")]
        [Parameter(Mandatory=$true, ValueFromPipeline=$false, ParameterSetName="Failure")] [switch]$Failure,
        [Parameter(Mandatory=$true, ValueFromPipeline=$false)] [int[]]$Flags)

  Begin {
    # Determine if audit rule exists
    if ($Success.IsPresent) { $AuditFlags=1 } else { $AuditFlags=0 }
    if ($Failure.IsPresent) { $AuditFlags+=2 }

    # Inheritance Flags
    # This folder only = 0
    # This folder, subfolders and files = 3
    # This folder and subfolders = 1
    # This folder and files = 2
    # Subfolders and files only = 3
    # Subfolders only = 1
    # Files only = 2

    # Propagation Flags
    # This folder only = 0
    # This folder, subfolders and files = 0
    # This folder and subfolders = 0
    # This folder and files = 0
    # Subfolders and files only = 2
    # Subfolders only = 2
    # Files only = 2

    # File System Rights
    $fsrAppendData                  =0x000004
    $fsrChangePermissions           =0x040000
    $fsrCreateDirectories           =0x000004
    $fsrCreateFiles                 =0x000002
    $fsrDelete                      =0x010000
    $fsrDeleteSubdirectoriesAndFiles=0x000040
    $fsrExecuteFile                 =0x000020
    $fsrFullControl                 =0x1F01FF
    $fsrListDirectory               =0x000001
    $fsrModify                      =0x0301BF
    $fsrRead                        =0x020089
    $fsrReadAndExecute              =0x0200A9
    $fsrReadAttributes              =0x000080
    $fsrReadData                    =0x000001
    $fsrReadExtendedAttributes      =0x000008
    $fsrReadPermissions             =0x020000
    $fsrSynchronize                 =0x100000
    $fsrTakeOwnership               =0x080000
    $fsrTraverse                    =0x000020
    $fsrWrite                       =0x000116
    $fsrWriteAttributes             =0x000100
    $fsrWriteData                   =0x000002
    $fsrWriteExtendedAttributes     =0x000010

    $RightValues=0
    for ($i=0; $i -lt $Rights.Count; $i++) {
     switch ($Rights[$i]) {
       "AppendData"                   { $RightValues=$RightValues -bor $fsrAppendData }
       "ChangePermissions"            { $RightValues=$RightValues -bor $fsrChangePermissions }
       "CreateDirectories"            { $RightValues=$RightValues -bor $fsrCreateDirectories }
       "CreateFiles"                  { $RightValues=$RightValues -bor $fsrCreateFiles }
       "Delete"                       { $RightValues=$RightValues -bor $fsrDelete }
       "DeleteSubdirectoriesAndFiles" { $RightValues=$RightValues -bor $fsrDeleteSubdirectoriesAndFiles }
       "ExecuteFile"                  { $RightValues=$RightValues -bor $fsrExecuteFile }
       "FullControl"                  { $RightValues=$RightValues -bor $fsrFullControl }
       "ListDirectory"                { $RightValues=$RightValues -bor $fsrListDirectory }
       "Modify"                       { $RightValues=$RightValues -bor $fsrModify }
       "Read"                         { $RightValues=$RightValues -bor $fsrRead }
       "ReadAndExecute"               { $RightValues=$RightValues -bor $fsrReadAndExecute }
       "ReadAttributes"               { $RightValues=$RightValues -bor $fsrReadAttributes }
       "ReadData"                     { $RightValues=$RightValues -bor $fsrReadData }
       "ReadExtendedAttributes"       { $RightValues=$RightValues -bor $fsrReadExtendedAttributes }
       "ReadPermissions"              { $RightValues=$RightValues -bor $fsrReadPermissions }
       "Synchronize"                  { $RightValues=$RightValues -bor $fsrSynchronize }
       "TakeOwnership"                { $RightValues=$RightValues -bor $fsrTakeOwnership }
       "Traverse"                     { $RightValues=$RightValues -bor $fsrTraverse }
       "Write"                        { $RightValues=$RightValues -bor $fsrWrite }
       "WriteAttributes"              { $RightValues=$RightValues -bor $fsrWriteAttributes }
       "WriteData"                    { $RightValues=$RightValues -bor $fsrWriteData }
       "WriteExtendedAttributes"      { $RightValues=$RightValues -bor $fsrWriteExtendedAttributes }
     }
    }

    Write-Verbose "Acquiring object $($FS.FullName)"
    $FS=Get-Item -Path $Path
    $ACL=Get-Acl -Path $Path -Audit
    $NothingToDo=$false
    for ($i=0; $i -lt $ACL.Audit.Count; $i++) {
      if ($ACL.Audit[$i].IdentityReference.Value -eq $Principal) {
        if ($ACL.Audit[$i].AuditFlags.value__ -eq $AuditFlags) {
          if ($ACL.Audit[$i].PropagationFlags.value__ -eq $Flags[1]) {
            if ($ACL.Audit[$i].InheritanceFlags.value__ -eq $Flags[0]) {
              if ($ACL.Audit[$i].FileSystemRights.value__ -eq $RightValues) { $NothingToDo=$true; Write-Verbose "Nothing to do" }
            }
          }
        }
      }
    }
  }

  Process {
    if (!$NothingToDo) {
      # There is one case where we will not propagage the rules.  This is when $Flags = 0,0
      if (($Flags[0] -eq 0) -and ($Flags[1] -eq 0)) { Write-Verbose "Flags = 0,0; no propagation necessary." }
      else {
        Write-Verbose "Setting Audit Rule"
        if ($Principal.Contains("\")) { $NTAccount=New-Object System.Security.Principal.NTAccount(($Principal.Split("\"))[0],($Principal.Split("\"))[1]) }
        else { $NTAccount=New-Object System.Security.Principal.NTAccount($Principal) }
        $FSAR=New-Object System.Security.AccessControl.FileSystemAuditRule($NTAccount,$RightValues,$Flags[0],$Flags[1],$AuditFlags)
        $FAR=New-Object System.Security.AccessControl.FileSystemAuditRule($NTAccount,$RightValues,$AuditFlags)
        $ACL.AddAuditRule($FSAR)
        $ACL.SetAuditRuleProtection($false, $true)
        Write-Verbose "Applying rule to $($ACL.Path.Replace('Microsoft.PowerShell.Core\FileSystem::',''))"
        $FS.SetAccessControl($ACL)

        # Now, ensure that all folders and files have inheritance enabled.
        $FS=Get-ChildItem -Path $Path -Recurse
        $FS=@($FS)
        for ($i=0; $i -lt $FS.Count; $i++) {
          Write-Verbose "Acquiring object $($FS[$i].FullName)"
          $ACL=Get-Acl -Path $FS[$i].FullName -Audit
          if (Test-Path $ACL.Path -PathType Leaf) { $ACL.AddAuditRule($FAR) } else { $ACL.AddAuditRule($FSAR) }
          $ACL.SetAuditRuleProtection($false, $true)
          $FS[$i].SetAccessControl($ACL)
          Write-Verbose "Applying rule to $($ACL.Path.Replace('Microsoft.PowerShell.Core\FileSystem::',''))"
          if (Test-Path $ACL.Path -PathType Leaf) { $ACL.RemoveAuditRule($FAR) > $null } else { $ACL.RemoveAuditRule($FSAR) > $null }
          Write-Verbose "Removing extra rule from $($ACL.Path)"
          $FS[$i].SetAccessControl($ACL)
        }
      }
    }
    else { Write-Verbose "Nothing to do." }
  }
}


问:
magento 2.1.5 how to get product disabled status programmatically
I am going to get product's enabled/disabled status programmatically.
Now, we got product instance by this code.

```<code> <?php $_product = $_item->getProduct(); ?>
</code>```

Also, using following code part, we can get product stock information.

```<code> <?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
      $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
      $product_is_stock = $StockState->getStockQty($_product->getId(), $_product->getStore()->getWebsiteId()); ?>
</code>```

But, is there any solution to get status of product from $_product on Magento 2.1?

答:
After debugging on few hours, I got a good solution about this issue.

```<code><?php $_product = $_item->getProduct();

 $product_status = $_product->getStatus();
</code>```

In my example, I got deactivated product's status as value using $_product->getStatus().

```<code><?php if (($product_is_stock == 0) || ($_product->getStatus() == 2)): ?>
</code>```

To confirm this operation, I got deactivated products using these sql commands.

```<code>SELECT entity_id FROM `catalog_product_entity_int`
WHERE attribute_id = (
    SELECT attribute_id FROM `eav_attribute`
    WHERE `attribute_code` LIKE 'status'
) AND `catalog_product_entity_int`.value = 2
</code>```

Finally, I confirmed deactivated products' status was just 2, not 0.

Enabled products' status was just 1.

Hope my example will help many developers.

Body:
I am going to get product's enabled/disabled status programmatically.
Now, we got product instance by this code.

 <?php $_product = $_item->getProduct(); ?>

Also, using following code part, we can get product stock information.

 <?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
      $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
      $product_is_stock = $StockState->getStockQty($_product->getId(), $_product->getStore()->getWebsiteId()); ?>

But, is there any solution to get status of product from $_product on Magento 2.1?

Body:
After debugging on few hours, I got a good solution about this issue.

<?php $_product = $_item->getProduct();

 $product_status = $_product->getStatus();

In my example, I got deactivated product's status as value using $_product->getStatus().

<?php if (($product_is_stock == 0) || ($_product->getStatus() == 2)): ?>

To confirm this operation, I got deactivated products using these sql commands.

SELECT entity_id FROM `catalog_product_entity_int`
WHERE attribute_id = (
    SELECT attribute_id FROM `eav_attribute`
    WHERE `attribute_code` LIKE 'status'
) AND `catalog_product_entity_int`.value = 2

Finally, I confirmed deactivated products' status was just 2, not 0.

Enabled products' status was just 1.

Hope my example will help many developers.


问:
next greater element in array
```<code>#include<iostream>
#include <stack>
using namespace std;

void printNextGreaterElement(int input[], int inputSize) {
    stack<int> s;
    s.push(input[0]);
    for (int i = 1; i < inputSize; i++) {
        while (!s.empty() && s.top() < input[i]) {
            cout<<"Next greater element for "<<s.top()<<"\t = "<<input[i]<<"\n";
            s.pop();
        }
        s.push(input[i]);
    }
    while (!s.empty()) {
        int top = (int) s.top();
        s.pop();
        cout<<"Next greater element for "<<top<<"\t = null\n";
    }
}

int main() {
    int input[] = { 98, 23, 54, 12, 20, 7, 27 };
    printNextGreaterElement(input, 7);
    return 0;
}
</code>```

I was learning about NGE in the array and came across this piece of code which I found on geeksforgeeks and other websites, but isn't this gives wrong output for the test case:

14

10 3 12 4 2 9 13 0 8 11 1 7 5 6

答:
Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in array.

Your code seems to be fine and gives the correct output of the input which you told gives wrong output is as following.

The input is as you mentioned

```<code>14
10 3 12 4 2 9 13 0 8 11 1 7 5 6
</code>```

The output is

```<code>Next greater element for 3       = 12
Next greater element for 10      = 12
Next greater element for 2       = 9
Next greater element for 4       = 9
Next greater element for 9       = 13
Next greater element for 12      = 13
Next greater element for 0       = 8
Next greater element for 8       = 11
Next greater element for 1       = 7
Next greater element for 5       = 6
Next greater element for 6       = null
Next greater element for 7       = null
Next greater element for 11      = null
Next greater element for 13      = null
</code>```

For example, the second element in the array is 3, the next greater element in the array is 12 (Which is the output).
The explanation of the algorithm is not given here as it is well written in the post you mentioned.

Title: next greater element in array

Body:
#include<iostream>
#include <stack>
using namespace std;

void printNextGreaterElement(int input[], int inputSize) {
    stack<int> s;
    s.push(input[0]);
    for (int i = 1; i < inputSize; i++) {
        while (!s.empty() && s.top() < input[i]) {
            cout<<"Next greater element for "<<s.top()<<"\t = "<<input[i]<<"\n";
            s.pop();
        }
        s.push(input[i]);
    }
    while (!s.empty()) {
        int top = (int) s.top();
        s.pop();
        cout<<"Next greater element for "<<top<<"\t = null\n";
    }
}

int main() {
    int input[] = { 98, 23, 54, 12, 20, 7, 27 };
    printNextGreaterElement(input, 7);
    return 0;
}

I was learning about NGE in the array and came across this piece of code which I found on geeksforgeeks and other websites, but isn't this gives wrong output for the test case:

14

10 3 12 4 2 9 13 0 8 11 1 7 5 6

Body:
Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in array.

Your code seems to be fine and gives the correct output of the input which you told gives wrong output is as following.

The input is as you mentioned

14
10 3 12 4 2 9 13 0 8 11 1 7 5 6

The output is

Next greater element for 3       = 12
Next greater element for 10      = 12
Next greater element for 2       = 9
Next greater element for 4       = 9
Next greater element for 9       = 13
Next greater element for 12      = 13
Next greater element for 0       = 8
Next greater element for 8       = 11
Next greater element for 1       = 7
Next greater element for 5       = 6
Next greater element for 6       = null
Next greater element for 7       = null
Next greater element for 11      = null
Next greater element for 13      = null

For example, the second element in the array is 3, the next greater element in the array is 12 (Which is the output).
The explanation of the algorithm is not given here as it is well written in the post you mentioned.


问:
Intellij "go to > implementation/declaration" navigation feature not working
I have a maven java project that I would like to use IntelliJ for development on. One of my favorite navigation features of IntelliJ is the 'go to > implementation' feature that appears when you right click on a method or function.

My problem is that this feature is not working for me; when I choose it nothing happens, no error, it just sits right where it is. It also isn't suggesting functions and methods as I type, so it's as if IntelliJ is failing to recognize dependencies and relationships among the various classes in my project.

I know the code is fine because it compiles and runs, has anyone else experienced this? I made sure to open the project as a maven project using the pom.xml file but that made no difference.

答:
It seems that the index is wrong.You need to force reindex the project files.
Just try:
File -> Invalidate caches...
Then restart your IntelliJ</p>


问:
How to shorten Chart.js label
The problem I'm facing is I have 2 charts, made with Chart.js, them contains dynamics labels descriptions, if some label descriptions is too long, chart is turning smaller, but I need that both charts contain same height.

How can I configure Chart.js to shorten labels, and shows complete label like HTML title when mouse hover, to maintain the label area height?

What I need is maintain height of chart area, no matter how long the label is.

var options = {
        //maintainAspectRatio: false,
        responsive:true,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    };

var ctx = document.getElementById("myCanvas1");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue yjfid ", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: options
});

var ctx = document.getElementById("myCanvas2");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: options
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{
  display: inline-block;
  width: 49%;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

    <canvas id="myCanvas1" ></canvas>

    <canvas id="myCanvas2"></canvas>

```

答:
This answer reference from post.On mouse hover you can see tooltip showing full label name

var options = {
  scales: {
    xAxes: [{
      ticks: {
        callback: function(value) {
          if (value.length > 4) {
            return value.substr(0, 4) + '...'; //truncate
          } else {
            return value
          }

        },
      }
    }],
    yAxes: [{}]
  },
  tooltips: {
    enabled: true,
    mode: 'label',
    callbacks: {
      title: function(tooltipItems, data) {
        var idx = tooltipItems[0].index;
        return 'Title:' + data.labels[idx]; //do something with title
      },
      label: function(tooltipItems, data) {
        //var idx = tooltipItems.index;
        //return data.labels[idx] + ' €';
        return tooltipItems.xLabel + ' €';
      }
    }
  },
};

var ctx = document.getElementById("myCanvas1");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue mbkjbjkbjlkbk", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: options
});

var ctx = document.getElementById("myCanvas2");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: options
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  display: inline-block;
  width: 49%;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

    <canvas id="myCanvas1"></canvas>

    <canvas id="myCanvas2"></canvas>

```

Title: How to shorten Chart.js label

Body:
The problem I'm facing is I have 2 charts, made with Chart.js, them contains dynamics labels descriptions, if some label descriptions is too long, chart is turning smaller, but I need that both charts contain same height.

How can I configure Chart.js to shorten labels, and shows complete label like HTML title when mouse hover, to maintain the label area height?

What I need is maintain height of chart area, no matter how long the label is.

var options = {
        //maintainAspectRatio: false,
        responsive:true,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    };

var ctx = document.getElementById("myCanvas1");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue yjfid ", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: options
});

var ctx = document.getElementById("myCanvas2");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: options
});

div{
  display: inline-block;
  width: 49%;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

    <canvas id="myCanvas1" ></canvas>

    <canvas id="myCanvas2"></canvas>

Body:
This answer reference from post.On mouse hover you can see tooltip showing full label name

var options = {
  scales: {
    xAxes: [{
      ticks: {
        callback: function(value) {
          if (value.length > 4) {
            return value.substr(0, 4) + '...'; //truncate
          } else {
            return value
          }

        },
      }
    }],
    yAxes: [{}]
  },
  tooltips: {
    enabled: true,
    mode: 'label',
    callbacks: {
      title: function(tooltipItems, data) {
        var idx = tooltipItems[0].index;
        return 'Title:' + data.labels[idx]; //do something with title
      },
      label: function(tooltipItems, data) {
        //var idx = tooltipItems.index;
        //return data.labels[idx] + ' €';
        return tooltipItems.xLabel + ' €';
      }
    }
  },
};

var ctx = document.getElementById("myCanvas1");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue mbkjbjkbjlkbk", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: options
});

var ctx = document.getElementById("myCanvas2");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: options
});

div {
  display: inline-block;
  width: 49%;
}

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>
  <div>
    <canvas id="myCanvas1"></canvas>
  </div>
  <div>
    <canvas id="myCanvas2"></canvas>
  </div>
</body>

</html>


问:
Direct db connection per http request vs connection pooling- what is the difference
Let's say I am storing data of Person(id, country_id, name). And let's say user just sent the id and country_id and we send back the name.

Now I have one db and 2 webserver and each webserver keeps a connection pool (e.g. c3p0) of 20 connection.

That means db is maintaining 40 connections and each webserver is maintaining 20 connections.

Analyzing the above system we can see that we used connection pool because people say "creating db connection is expensive"

This all make sense

Now let's say I shard table data on country_id, so now there may be 200 db, also assuming our app is popular now and we need to have 50 webserver.

Now the above strategy of connection pooling fails as if each webserver is keeping 20 connections in the pool for each db.

that means each webserver will have 20*200 db = 4000 connection

and each db will have 50 web server *20 = 1000 connection.

This doesn't sound good, so I got the question that why use connection pooling what is the overhead of creating 1 connection per web request?

So I run a test where I saw that DriverManager.getConnection() takes a average of 20 ms on localhost.

20 ms extra per request is not a game killer

Question1: Is there any other downside of using 1 connection per web request ?

Question2: People all over internet say "db connection is expensive". What are the different expenses?

PS: I also see pinterest doing same https://medium.com/@Pinterest_Engineering/sharding-pinterest-how-we-scaled-our-mysql-fleet-3f341e96ca6f

答:
Other than Connection creation & Connection close cycle being a time consuming task ( i.e. being costly ) , pooling is also done to control the number of simultaneous open connections to your database since there is a limit on number of simultaneous connections that a db server can handle. When you do , one connection per request , you loose that control and your application is always at risk of crashing at peak load.

Secondly, you would unnecessarily tie your web server capacity with your database capacity and target is also to treat db connection management not as a developer concern but an infrastructure concern. Would you like to give control to open a database connection for production application to developer as per his/her code?

In traditional monolithic application servers like Weblogic, JBoss, WebSphere etc, Its sys admin who will create a connection pool as per db serer capacity and pass on JNDI name to developers to use to.Developer's job is to only get connection using that JNDI.

Next comes if database is shared among various independent applications then pooling lets you know as what you are giving out to which application. Some apps might be more data intensive and some might not be that intensive.

Traditional problem of resource leak i.e when developers forget to cleanly close their connection is also taken care of with pooling.

All in all - idea behind pooling is to let developers be concerned only about using a connection and do their job and not being worried about opening and closing it. If a connection is not being used for X minutes, it will be returned to pool per configuration.


问:
Seeing how many values in two SparkR columns match
I have two integer columns (x1 and x2) in a SparkR DataFrame named df that are very similar to each other. I want to get a count of how many of the values match and compare it with the total length of the columns. How can I do this? I have tried the following, both of which result in errors.

```<code>agg(df, sum(df$x1==df$x2))
collect(sum(df$x1==df$x2))
</code>```

答:
you can use withColumn to generate the new column populating a value for both x1 and x2 columns being equal.

And you can use count to count the values from new column.

Body:
I have two integer columns (x1 and x2) in a SparkR DataFrame named df that are very similar to each other. I want to get a count of how many of the values match and compare it with the total length of the columns. How can I do this? I have tried the following, both of which result in errors.

agg(df, sum(df$x1==df$x2))
collect(sum(df$x1==df$x2))


问:
R - Remove consecutive values from dataset, subject to condition of second variable
Suppose we have a dataset with a days variable and a condition variable. I want to remove rows that have condition==F, only if they appear consecutively and the corresponding entries for days sum to over 180.

Here is example code:

```<code>data <- data.frame(days = c(0, 30, 60, 60, 70, 60, 40, 30, 30, 30, 30),
                   condition = c(F, T, F, F, F, T, F, T, F, F, F))

> data
  days condition
1     0     FALSE
2    30      TRUE
3    60     FALSE
4    60     FALSE
5    70     FALSE
6    60      TRUE
7    40     FALSE
8    30      TRUE
9    30     FALSE
10   30     FALSE
11   30     FALSE
</code>```

I would want to remove rows 3,4,5, but not rows 9,10,11 (since the days don't sum to over 180 in this case). Is there a simple way to do this?

答:
We can do this with data.table.  Convert the 'data.frame' to 'data.table' (setDT(data)), grouped by the run-length-id of 'condition', we check the condition if the sum of 'days' is less than 180 and the 'condition' is FALSE or (|), the TRUE values, get the column of index and subset the data

```<code>library(data.table)
setDT(data)[data[,  (sum(days) < 180) & !condition |condition, .(grp = rleid(condition))]$V1]
#   days condition
#1:    0     FALSE
#2:   30      TRUE
#3:   60      TRUE
#4:   40     FALSE
#5:   30      TRUE
#6:   30     FALSE
#7:   30     FALSE
#8:   30     FALSE
</code>```

Body:
Suppose we have a dataset with a days variable and a condition variable. I want to remove rows that have condition==F, only if they appear consecutively and the corresponding entries for days sum to over 180.

Here is example code:

data <- data.frame(days = c(0, 30, 60, 60, 70, 60, 40, 30, 30, 30, 30),
                   condition = c(F, T, F, F, F, T, F, T, F, F, F))

> data
  days condition
1     0     FALSE
2    30      TRUE
3    60     FALSE
4    60     FALSE
5    70     FALSE
6    60      TRUE
7    40     FALSE
8    30      TRUE
9    30     FALSE
10   30     FALSE
11   30     FALSE

I would want to remove rows 3,4,5, but not rows 9,10,11 (since the days don't sum to over 180 in this case). Is there a simple way to do this?

Body:
We can do this with data.table.  Convert the 'data.frame' to 'data.table' (setDT(data)), grouped by the run-length-id of 'condition', we check the condition if the sum of 'days' is less than 180 and the 'condition' is FALSE or (|), the TRUE values, get the column of index and subset the data

library(data.table)
setDT(data)[data[,  (sum(days) < 180) & !condition |condition, .(grp = rleid(condition))]$V1]
#   days condition
#1:    0     FALSE
#2:   30      TRUE
#3:   60      TRUE
#4:   40     FALSE
#5:   30      TRUE
#6:   30     FALSE
#7:   30     FALSE
#8:   30     FALSE


问:
*ngFor not working and no error in console
I went through most of the questions where "ngFor is not working". below are the details.

app.modules.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TweetComponent } from './tweet.component';
import { AppComponent } from './app.component';

@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent, TweetComponent],
    bootstrap: [AppComponent]
    })

export class AppModule { }
</code>```

app.components.ts

```<code>import { Component } from '@angular/core';
import { CommonModule } from "@angular/common";

@Component({
  selector: 'my-app',
  template: `<h1>List of tweets</h1>
            <tweets><tweets>`,
 })

export class AppComponent  { name = 'Angular'; }
</code>```

tweet.component.ts

```<code>import { Component } from "@angular/core"
@Component({
   selector: 'tweets',
   template: `<ul>
                <li *ngFor="let item of myList">
                     <span> {{ item}}</span>
                  </li>
              </ul> `
})

export class TweetComponent {
        myList: ['.net', 'C#', 'web services'];
}
</code>```

Output:

Elements:

And there are errors in console.

答:
It should've been

```<code>myList = ['.net', 'C#', 'web services'];
</code>```

if you use : it will try to declare the fields type.

Example:

```<code>myList: Array<string> = ['.net', 'C#', 'web services'];
</code>```

Body:
I went through most of the questions where "ngFor is not working". below are the details.

app.modules.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TweetComponent } from './tweet.component';
import { AppComponent } from './app.component';

@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent, TweetComponent],
    bootstrap: [AppComponent]
    })

export class AppModule { }

app.components.ts

import { Component } from '@angular/core';
import { CommonModule } from "@angular/common";

@Component({
  selector: 'my-app',
  template: `
List of tweets

            <tweets><tweets>`,
 })

export class AppComponent  { name = 'Angular'; }

tweet.component.ts

import { Component } from "@angular/core"
@Component({
   selector: 'tweets',
   template: `

                      {{ item}}

 `
})

export class TweetComponent {
        myList: ['.net', 'C#', 'web services'];
}

Output:

Elements:

And there are errors in console.

Body:
It should've been

myList = ['.net', 'C#', 'web services'];

if you use : it will try to declare the fields type.

Example:

myList: Array<string> = ['.net', 'C#', 'web services'];


问:
Getting the binary value of a character string in Powershell
```<code>$getInput = Read-Host "ASCII or Binary? `n"
$getInput = $getInput.toLower()

if($getInput -eq "ascii"){

    ""

    #Write-Host "Type In Your ASCII" -backgroundcolor "black"
    $getAscii = Read-Host "Type In Your ASCII`n"
    ""
    ""
    $readAscii = @($getAscii)
    [byte[]]$outBytes = $readAscii

}
elseif($getInput -eq "binary"){

}
else{
    Write-Host "Wrong Input... [ASCII] or [BINARY]" -backgroundcolor "red" -foregroundcolor "white"
}
</code>```

I want to be able to get a users paragraph or whatever string they put in and convert it to binary. The [conver]::toString($getAscii,2) only works for integers.

答:
Try this

```<code>$string = "ABCDEF"
[system.Text.Encoding]::Default.GetBytes($String) | %{[System.Convert]::ToString($_,2).PadLeft(8,'0') }
</code>```

[system.Text.Encoding]::Default.GetBytes($String)

This turns a string into a byte array. You can change Default to another Encoding

| %{[System.Convert]::ToString($_,2).PadLeft(8,'0') }

This turns each byte in the byte array into a binary representation.
ToString([object],[Enum]), in this case the byte will have a number value like 65 if converted to string the 2 will say turn the 65 into base 2. You could also use 8(octo), 10(which is the same as none aka base 10) and 16(Hex). Then it pads the left till its 8 char long with char 0's

Body:
$getInput = Read-Host "ASCII or Binary? `n"
$getInput = $getInput.toLower()

if($getInput -eq "ascii"){

    ""

    #Write-Host "Type In Your ASCII" -backgroundcolor "black"
    $getAscii = Read-Host "Type In Your ASCII`n"
    ""
    ""
    $readAscii = @($getAscii)
    [byte[]]$outBytes = $readAscii

}
elseif($getInput -eq "binary"){

}
else{
    Write-Host "Wrong Input... [ASCII] or [BINARY]" -backgroundcolor "red" -foregroundcolor "white"
}

I want to be able to get a users paragraph or whatever string they put in and convert it to binary. The [conver]::toString($getAscii,2) only works for integers.

Body:
Try this

$string = "ABCDEF"
[system.Text.Encoding]::Default.GetBytes($String) | %{[System.Convert]::ToString($_,2).PadLeft(8,'0') }

[system.Text.Encoding]::Default.GetBytes($String)

This turns a string into a byte array. You can change Default to another Encoding

| %{[System.Convert]::ToString($_,2).PadLeft(8,'0') }

This turns each byte in the byte array into a binary representation.
ToString([object],[Enum]), in this case the byte will have a number value like 65 if converted to string the 2 will say turn the 65 into base 2. You could also use 8(octo), 10(which is the same as none aka base 10) and 16(Hex). Then it pads the left till its 8 char long with char 0's


问:
How to enable query logger in rom-sql (rom-rb)?
In rom-sql I want to enable logging, so that I can see all the sql queries that are produced.

How can I achieve that?

Because it uses sequel underneath, I guest it may be somehow possible through sequel logger.

Body: Got it: ROM::SQL::Gateway#use_logger


问:
How to check a SSL certificate expiration date with aiohttp?
I know how to get certificate information such as expiration date using pyopenssl for instance, but is it possible to do it with a aiohttp response object?</p>

答: Check this repo called check-tls-certs. It's not really aiohttp, but it's based on asyncio and so it works asynchronously.</p>


问:
Check if column value exists in another column in SQL
I need a SQL query that compares two values and returns an ID.

I have this table:

```<code>ID  Calling_ID  Called_ID
1   27          10
2   15          20
3   80          90
4   90          88
5   60          30
6   88          40
7   15          60
8   30          40
9   27          95
10  40          30
</code>```

How do I check if each value in the Calling_ID column exists in the Called_ID column and then return the ID? The above data would return 88, 30, 40.

答:
Based on your statement, "The above data would return 88, 30, 40," it seems you were looking for Calling_ID / Called_ID to be returned, not ID.  Here are two fully correct ways to do that:

Using JOIN

```<code>SELECT DISTINCT t1.Calling_ID FROM [Table] AS t1
JOIN [Table] AS t2 ON t1.Calling_ID = t2.Called_Id
</code>```

Using IN

```<code>SELECT DISTINCT Calling_ID FROM [Table]
WHERE Calling_ID IN (SELECT Called_ID FROM [Table])
</code>```

Body:
I need a SQL query that compares two values and returns an ID.

I have this table:

ID  Calling_ID  Called_ID
1   27          10
2   15          20
3   80          90
4   90          88
5   60          30
6   88          40
7   15          60
8   30          40
9   27          95
10  40          30

How do I check if each value in the Calling_ID column exists in the Called_ID column and then return the ID? The above data would return 88, 30, 40.

Body:
Based on your statement, "The above data would return 88, 30, 40," it seems you were looking for Calling_ID / Called_ID to be returned, not ID.  Here are two fully correct ways to do that:

Using JOIN

SELECT DISTINCT t1.Calling_ID FROM [Table] AS t1
JOIN [Table] AS t2 ON t1.Calling_ID = t2.Called_Id

Using IN

SELECT DISTINCT Calling_ID FROM [Table]
WHERE Calling_ID IN (SELECT Called_ID FROM [Table])


问:
IntelliJ Gradle "Unable to find Method"

The Error:

Failed to sync Gradle project '-'
Error:Unable to find method 'org.gradle.internal.logging.progress.DefaultProgressLoggerFactory.(Lorg/gradle/internal/logging/progress/ProgressListener;Lorg/gradle/internal/time/TimeProvider;)V'.

You can see, a constructor inside a class, which is found in the logging jar (gradle_home/lib/grade-logging-version.jar) is missing.
So, I think the Class-Path does not contain this jar file.

Gradle Version: 3.5

Running using the Command Line works.

I have already tried this:

Gradle sync failed: Unable to find method

to-find-method, it does not work for me.

I have tried to use different versions.

I can't see any difference when enabling

"Use default gradle wrapper"

"Use gradle wrapper task configuration"

"Use local gradle distribution".

答:
I had the exact same problem today.
The only way I was able to get it to work was to remove my IntelliJ IDEA IDE, get the latest from the website (with JDK) and put it in a new folder (i.e. no overwriting existing files).
After that, I deleted the .idea folder from the project and reimported it cleanly into the "new" IntelliJ.

I suspect upgrading IntelliJ from Version <= 2016.x caused the issue, since a new installation / clean extraction from archive caused it to work on the fly.

Title: IntelliJ Gradle "Unable to find Method"


问:
Angular2,Ionic2: How to do 2way binding for radio button in nested *ngfor using ngModel?
I've my API in JSON in the following format.

I want to display this in the form of question & choices format. I'm trying to display the choices using radio buttons. But my ngModel is not working. I want to access the whole object of the selected choice using ngModel in my .ts file.

Here is my ts code

```<code>export class Quiz implements OnInit {
    testcontents: Array<any>=[];
    choiceObj:any;

 constructor(public navCtrl: NavController, public navParams: NavParams,public http:Http) {}
     ngOnInit()
     {
       this.launchfunc();
     }
     launchfunc()
     {
    this.http.post('launchtest/getTestContent',this.launchtestobj).subscribe(resp=>{
         this.testcontents = resp.data.questions;
    });
     }

    selectChoice($event)
    {
      console.log("12312341234",event);
      console.log("obj",this.choiceObj);
    }
</code>```

Here is my html code

```<code><ion-content padding>
<div *ngFor="let qContent of testcontents; let i = index">
    {{i+1}} {{qContent.questionText}}
    <div *ngFor="let choiceObj of qContent.choice">
        <input name='options' type='radio' [value]='choiceObj' [(ngModel)]='choiceObj.choice' (ngModelChange)="selectChoice(choiceObj)" />
        <label [for]='choiceObj'>{{choiceObj.choiceText}}</label>
    </div>
</div>
</code>```

This is the output for the above code.
I don't understand why is obj undefined.
I've a problem with the ngModel. I'm not understanding what should I put my ngModel as and how should I access the "choiceObj" in typescript file.Can someone please help me.

答:
the model is choiceObj.choice which is not exist in object of choice.
you need to replace it with 'choiceObj.choiceId'</p>

```<code><ion-content padding>
<div *ngFor="let qContent of testcontents; let i = index">
    {{i+1}} {{qContent.questionText}}
    <div *ngFor="let choiceObj of qContent.choice">
        <input name='options' type='radio' [value]='choiceObj' [(ngModel)]='choiceObj.choiceId' (ngModelChange)="selectChoice(choiceObj)" />
        <label [for]='choiceObj'>{{choiceObj.choiceText}}</label>
    </div>
</div>
</code>```

Body:
I've my API in JSON in the following format.

I want to display this in the form of question & choices format. I'm trying to display the choices using radio buttons. But my ngModel is not working. I want to access the whole object of the selected choice using ngModel in my .ts file.

Here is my ts code

export class Quiz implements OnInit {
    testcontents: Array<any>=[];
    choiceObj:any;

 constructor(public navCtrl: NavController, public navParams: NavParams,public http:Http) {}
     ngOnInit()
     {
       this.launchfunc();
     }
     launchfunc()
     {
    this.http.post('launchtest/getTestContent',this.launchtestobj).subscribe(resp=>{
         this.testcontents = resp.data.questions;
    });
     }

    selectChoice($event)
    {
      console.log("12312341234",event);
      console.log("obj",this.choiceObj);
    }

Here is my html code

<ion-content padding>

    {{i+1}} {{qContent.questionText}}

        <input name='options' type='radio' [value]='choiceObj' [(ngModel)]='choiceObj.choice' (ngModelChange)="selectChoice(choiceObj)" />
        {{choiceObj.choiceText}}

This is the output for the above code.
I don't understand why is obj undefined.
I've a problem with the ngModel. I'm not understanding what should I put my ngModel as and how should I access the "choiceObj" in typescript file.Can someone please help me.

Body:
the model is choiceObj.choice which is not exist in object of choice.
you need to replace it with 'choiceObj.choiceId'

<ion-content padding>
<div *ngFor="let qContent of testcontents; let i = index">
    {{i+1}} {{qContent.questionText}}
    <div *ngFor="let choiceObj of qContent.choice">
        <input name='options' type='radio' [value]='choiceObj' [(ngModel)]='choiceObj.choiceId' (ngModelChange)="selectChoice(choiceObj)" />
        <label [for]='choiceObj'>{{choiceObj.choiceText}}</label>
    </div>
</div>


问:
using a jquery if condition on a span tag to show hide a div element
I am trying the following script to detect changes on a span tag and then show or hide a div element. For some reason the if statement is not working. I don't get any errors in my browser and not much information on what can be wrong with it.

```<code>$('#ch1').on('change',function(){
if('#ch1' > 6) {

        $('#box1').hide(2000);
} else {
        $('#box1').show(2000);
}
</code>```

});

答:
```<code>At first, create a javascript ready function where you can put the span click code to show/hide div.
</code>```

var temp = 1;
$(document).ready(function(){
   $("span").click(function(){
        if(temp == 1)
        {
         $('#tempdiv').hide(2000);
            temp = 2;
        }
        else
        {
         $('#tempdiv').show(2000);
            temp = 1;
        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

<span>If you click on me, then....</span>
<div id="tempdiv">This is a div that you can show and hide on span.</div>

</body>
</html></code>```

Body:
I am trying the following script to detect changes on a span tag and then show or hide a div element. For some reason the if statement is not working. I don't get any errors in my browser and not much information on what can be wrong with it.

$('#ch1').on('change',function(){
if('#ch1' > 6) {

        $('#box1').hide(2000);
} else {
        $('#box1').show(2000);
}

});

Body:
At first, create a javascript ready function where you can put the span click code to show/hide div.

var temp = 1;
$(document).ready(function(){
   $("span").click(function(){
        if(temp == 1)
        {
         $('#tempdiv').hide(2000);
            temp = 2;
        }
        else
        {
         $('#tempdiv').show(2000);
            temp = 1;
        }
    });
});

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

<span>If you click on me, then....</span>
<div id="tempdiv">This is a div that you can show and hide on span.</div>

</body>
</html>