问:
JavaFX Sorting a TreeView by SubDirectories and Files
I try to sort directories and files in a JavaFX Treeview (using SceneBuilder)

So far im getting a tree in a unsorted way ...

All I want is to have the Root-Item on Top, then get all SubDirectories (not expanded) of the selected Folder and then list all Files.

```<code>public void createTreeView(String dbpath) {

    TreeItem<Object> ROOTTREE = new TreeItem<>(dbpath.substring(dbpath.lastIndexOf("\\")));

    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(dbpath))) {
        for(Path path: directoryStream) {
            if (Files.isDirectory(path)) {
                TreeItem<Object> leafs = new TreeItem<>(strPath.substring(1 + strPath.lastIndexOf("\\")));
                parent.getChildren().add(leafs);
                return leafs;
            } else {
                getLeafs(path, tree);
            }

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    tree.setExpanded(ROOTTREE);
    TreeView_DBDirectory.setRoot(ROOTTREE);
    TreeView_DBDirectory.setShowRoot(true);
}
</code>```

I tried to use a Comparator at the createTreeView(), but I#m not sure how to compare TreeItem as Folder and Files.

Maybe there is a more suitable solution? :/

答:
Store the directories in an list.  Store the files in another list.  Add all of the items in directory list to the tree children first.  Then add all items of file list to the tree children.

```<code>TreeItem<Object> tree = new TreeItem<>(dbPath.substring(dbPath.lastIndexOf(File.separator)));

List<TreeItem<Object>> dirs = new ArrayList<>();
List<TreeItem<Object>> files = new ArrayList<>();

try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(dbPath))) {
    for(Path path: directoryStream) {
        if (Files.isDirectory(path)) {
            TreeItem<Object> subDirectory = new TreeItem<>(path);
            getSubLeafs(path, subDirectory);
            dirs.add(subDirectory);
        } else {
            files.add(getLeafs(path));
        }
    }

    tree.getChildren().addAll(dirs);
    tree.getChildren().addAll(files);
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

Example running on the following directory structure:

```<code>$ tree /tmp/test
/tmp/test
├── a1.txt
├── d1
│   ├── b1.txt
│   └── b2.txt
├── d2
│   └── c1.txt
└── f1.txt
</code>```

I clicked on the tree nodes to expand them, so you can see their values (by default the tree nodes are not expanded).

Executable Sample

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;

public class MenuClickSample extends Application {
    TreeView<Object> treeView = new TreeView<>();

    @Override public void start(Stage stage) throws IOException {
        createTreeView("/tmp/test");
        Scene scene = new Scene(treeView);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    private void createTreeView(String dbPath) {
        TreeItem<Object> tree = new TreeItem<>(dbPath.substring(dbPath.lastIndexOf(File.separator)));

        List<TreeItem<Object>> dirs = new ArrayList<>();
        List<TreeItem<Object>> files = new ArrayList<>();

        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(dbPath))) {
            for(Path path: directoryStream) {
                if (Files.isDirectory(path)) {
                    TreeItem<Object> subDirectory = new TreeItem<>(path);
                    getSubLeafs(path, subDirectory);
                    dirs.add(subDirectory);
                } else {
                    files.add(getLeafs(path));
                }
            }

            tree.getChildren().addAll(dirs);
            tree.getChildren().addAll(files);
        } catch (IOException e) {
            e.printStackTrace();
        }

        tree.setExpanded(true);
        treeView.setRoot(tree);
        treeView.setShowRoot(true);
    }

    private TreeItem<Object> getLeafs(Path subPath) {
        String strPath = subPath.toString();
        TreeItem<Object> leafs = new TreeItem<>(strPath.substring(1 + strPath.lastIndexOf(File.separator)));
        return leafs;
    }

    private void getSubLeafs(Path subPath, TreeItem<Object> parent) {
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(subPath.toString()))) {
            for(Path subDir: directoryStream) {
                // explicit search for files because we dont want to get sub-sub-directories
                if (!Files.isDirectory(subDir)) {
                    String subTree = subDir.toString();
                    TreeItem<Object> subLeafs = new TreeItem<>(subTree.substring(1 + subTree.lastIndexOf(File.separator)));
                    parent.getChildren().add(subLeafs);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
I try to sort directories and files in a JavaFX Treeview (using SceneBuilder)

So far im getting a tree in a unsorted way ...

All I want is to have the Root-Item on Top, then get all SubDirectories (not expanded) of the selected Folder and then list all Files.

public void createTreeView(String dbpath) {

    TreeItem<Object> ROOTTREE = new TreeItem<>(dbpath.substring(dbpath.lastIndexOf("\\")));

    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(dbpath))) {
        for(Path path: directoryStream) {
            if (Files.isDirectory(path)) {
                TreeItem<Object> leafs = new TreeItem<>(strPath.substring(1 + strPath.lastIndexOf("\\")));
                parent.getChildren().add(leafs);
                return leafs;
            } else {
                getLeafs(path, tree);
            }

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    tree.setExpanded(ROOTTREE);
    TreeView_DBDirectory.setRoot(ROOTTREE);
    TreeView_DBDirectory.setShowRoot(true);
}

I tried to use a Comparator at the createTreeView(), but I#m not sure how to compare TreeItem as Folder and Files.

Maybe there is a more suitable solution? :/

Body:
Store the directories in an list.  Store the files in another list.  Add all of the items in directory list to the tree children first.  Then add all items of file list to the tree children.

TreeItem<Object> tree = new TreeItem<>(dbPath.substring(dbPath.lastIndexOf(File.separator)));

List<TreeItem<Object>> dirs = new ArrayList<>();
List<TreeItem<Object>> files = new ArrayList<>();

try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(dbPath))) {
    for(Path path: directoryStream) {
        if (Files.isDirectory(path)) {
            TreeItem<Object> subDirectory = new TreeItem<>(path);
            getSubLeafs(path, subDirectory);
            dirs.add(subDirectory);
        } else {
            files.add(getLeafs(path));
        }
    }

    tree.getChildren().addAll(dirs);
    tree.getChildren().addAll(files);
} catch (IOException e) {
    e.printStackTrace();
}

Example running on the following directory structure:

$ tree /tmp/test
/tmp/test
├── a1.txt
├── d1
│   ├── b1.txt
│   └── b2.txt
├── d2
│   └── c1.txt
└── f1.txt

I clicked on the tree nodes to expand them, so you can see their values (by default the tree nodes are not expanded).

Executable Sample

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;

public class MenuClickSample extends Application {
    TreeView<Object> treeView = new TreeView<>();

    @Override public void start(Stage stage) throws IOException {
        createTreeView("/tmp/test");
        Scene scene = new Scene(treeView);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    private void createTreeView(String dbPath) {
        TreeItem<Object> tree = new TreeItem<>(dbPath.substring(dbPath.lastIndexOf(File.separator)));

        List<TreeItem<Object>> dirs = new ArrayList<>();
        List<TreeItem<Object>> files = new ArrayList<>();

        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(dbPath))) {
            for(Path path: directoryStream) {
                if (Files.isDirectory(path)) {
                    TreeItem<Object> subDirectory = new TreeItem<>(path);
                    getSubLeafs(path, subDirectory);
                    dirs.add(subDirectory);
                } else {
                    files.add(getLeafs(path));
                }
            }

            tree.getChildren().addAll(dirs);
            tree.getChildren().addAll(files);
        } catch (IOException e) {
            e.printStackTrace();
        }

        tree.setExpanded(true);
        treeView.setRoot(tree);
        treeView.setShowRoot(true);
    }

    private TreeItem<Object> getLeafs(Path subPath) {
        String strPath = subPath.toString();
        TreeItem<Object> leafs = new TreeItem<>(strPath.substring(1 + strPath.lastIndexOf(File.separator)));
        return leafs;
    }

    private void getSubLeafs(Path subPath, TreeItem<Object> parent) {
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(subPath.toString()))) {
            for(Path subDir: directoryStream) {
                // explicit search for files because we dont want to get sub-sub-directories
                if (!Files.isDirectory(subDir)) {
                    String subTree = subDir.toString();
                    TreeItem<Object> subLeafs = new TreeItem<>(subTree.substring(1 + subTree.lastIndexOf(File.separator)));
                    parent.getChildren().add(subLeafs);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


来源: stackexchange

问:
How can I search for an object property value in an array if I only know a different property?
In this array I would like to find the id of the object by querying on the property name. Given I know the name is NV, how can I get the id?

I already tried different loops and other thing like GetObject, but it gives no return.

```<code>{
  "items": [
    {
      "id": 1,
      "name": "BV",
    },
    {
      "id": 2,
      "name": "NV"
    }
  ],
}
</code>```

答:
Simply use array.find:

var data = {
  "items": [{
      "id": 1,
      "name": "BV",
    },
    {
      "id": 2,
      "name": "NV"
    }
  ],
};

console.log(data.items.find(item => item.name == "NV").id)```

ContentLicense: CC BY-SA 3.0

Body:
In this array I would like to find the id of the object by querying on the property name. Given I know the name is NV, how can I get the id?

I already tried different loops and other thing like GetObject, but it gives no return.

{
  "items": [
    {
      "id": 1,
      "name": "BV",
    },
    {
      "id": 2,
      "name": "NV"
    }
  ],
}


问:
PHP to search a string
I'm trying to use PHP to search a string and store certain elements in an array and then display the answers at the end. I'm trying to use the $match variable, but every time I do it, I get an undefined error for it.

My code:

```<code>    <html>
    <head>
        <meta charset="UTF-8">
        <title>states</title>
    </head>
    <body>
        <?php
        $states = ('Mississippi Alabama Texas Massachusetts Kansas');
        $statesArray = [];

        //end in xas
        if (preg_match("/\b([a-zA-Z]*xas)\b/i", $states)) {
            $statesArray[0] = $match[1];
        }

        //begins with k ends in s. case sensitive comparison
        if (preg_match("/\b(K[[:alpha:]]*s$)\b/", $states)) {
            $statesArray[1] = $match[2];
        }

        // word start with m end in s
//        if(preg_match("/M/[[:alpha:]]*s", $subject))
        if (preg_match("/\b(M[[:alpha:]]*s)\b/", $states)) {
            $statesArray[2] = $match[3];
        }
        //ends in a
        if (preg_match("/\b([a-zA-Z]*a)\b/i", $states)) {
            $statesArray[3] = $match[4];
        }
        //starts with m
        if (preg_match("/\b(M[[:alpha:]]+)\b/i", $states, $match)) {
            $statesArray[4] = $match[5];
        }

        $print = print($statesArray[0]);
        print($statesArray[1]);
        print($statesArray[2]);
        print($statesArray[3]);
        print($statesArray[4]);

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

答:
You are using preg_match() incorrectly. See the reference at http://php.net/manual/en/function.preg-match.php You need to pass the $match array and capture first or all matches you are interested in. The code below captures first match.

```<code>    $match = [];

    //end in xas
    if (preg_match("/\b([a-zA-Z]*xas)\b/i", $states, $match)) {
        $statesArray[0] = $match[0];
    }

    //begins with k ends in s. case sensitive comparison
    if (preg_match("/\b(K[[:alpha:]]*s$)\b/", $states, $match)) {
        $statesArray[1] = $match[0];
    }
</code>```

Title: PHP to search a string

Body:
I'm trying to use PHP to search a string and store certain elements in an array and then display the answers at the end. I'm trying to use the $match variable, but every time I do it, I get an undefined error for it.

My code:

        <meta charset="UTF-8">
        <title>states</title>

        <?php
        $states = ('Mississippi Alabama Texas Massachusetts Kansas');
        $statesArray = [];

        //end in xas
        if (preg_match("/\b([a-zA-Z]*xas)\b/i", $states)) {
            $statesArray[0] = $match[1];
        }

        //begins with k ends in s. case sensitive comparison
        if (preg_match("/\b(K[[:alpha:]]*s$)\b/", $states)) {
            $statesArray[1] = $match[2];
        }

        // word start with m end in s
//        if(preg_match("/M/[[:alpha:]]*s", $subject))
        if (preg_match("/\b(M[[:alpha:]]*s)\b/", $states)) {
            $statesArray[2] = $match[3];
        }
        //ends in a
        if (preg_match("/\b([a-zA-Z]*a)\b/i", $states)) {
            $statesArray[3] = $match[4];
        }
        //starts with m
        if (preg_match("/\b(M[[:alpha:]]+)\b/i", $states, $match)) {
            $statesArray[4] = $match[5];
        }

        $print = print($statesArray[0]);
        print($statesArray[1]);
        print($statesArray[2]);
        print($statesArray[3]);
        print($statesArray[4]);

        ?>

Body:
You are using preg_match() incorrectly. See the reference at http://php.net/manual/en/function.preg-match.php You need to pass the $match array and capture first or all matches you are interested in. The code below captures first match.

    $match = [];

    //end in xas
    if (preg_match("/\b([a-zA-Z]*xas)\b/i", $states, $match)) {
        $statesArray[0] = $match[0];
    }

    //begins with k ends in s. case sensitive comparison
    if (preg_match("/\b(K[[:alpha:]]*s$)\b/", $states, $match)) {
        $statesArray[1] = $match[0];
    }


问:
Differences between apostrophe-attachments and apostrophe-files?
What are the main differences between the attachments and files modules, and are there specific use cases for each? Can permissions be applied to both? I'm very new to the platform, so trying to get up to speed on the hows and whys of how apostrophe accomplishes things.</p>

答:
I am the architect of Apostrophe at P'unk Avenue.

These modules are not alternatives, exactly. In fact, apostrophe-files and apostrophe-images are both built on top of apostrophe-attachments.

What is an apostrophe-file? It's a "piece" — an Apostrophe document with a title, some metadata, and in this case, an attachment field. Since it's a piece, just like any blog post or event, you can manage all of your files via the admin bar, you can use apostrophe-files-widgets to display download links around your site, and so on.

So what is an attachment? It's a schema field — a type of field you can include in the schema of any type of doc in Apostrophe, such as a piece or page.

Most schema field types are very simple. The string field type, for instance, consists of a string. The boolean field type is either true or false, and so on.

But attachments are a little tricky. In an ideal world... from a database design standpoint... the actual contents of the file would live right in your document; doc.headshot could be the actual JPEG data (or that, plus some metadata, perhaps).

But we can't do that, because files are very big, and even if they fit in a MongoDB doc (they don't always), it would be very, very inefficient especially when we're not interested in them right now.

So instead, here's what a typical apostrophe-file piece looks like in MongoDB if you use findOne to display it in the mongo shell. I've pared it down a little for simplicity. Notice the attachment property:

```<code>{
    "_id" : "xyz",
    "type" : "apostrophe-file",
    "title" : "Field Trip Permission Slip",
    "slug" : "file-field-trip-permission-slip",
    "attachment" : {
        "type" : "attachment",
        "_id" : "qqq",
        "name" : "permission-form",
        "extension" : "pdf"
    },
}
</code>```

The attachment field has its own _id. And between that _id, the name property, and the extension property, the apos.attachments.url() method can put together a URL to download it.

So what does this buy us? Flexibility. Want to reuse a single library of PDFs all over your site? Use apostrophe-files, and use apostrophe-files-widgets to display download links around the site.

Want to attach a resume property to a specific person's profile piece and keep it out of the shared library? Use an attachment field in the schema for your piece type instead:

```<code>// in lib/modules/people
module.exports = {
  extend: 'apostrophe-pieces',
  addFields: [
    {
      type: 'attachment',
      name: 'resume'
    }
  ]
}
</code>```

We could have used a widget to pick a file, but we didn't want to clutter the shared library of files with thousands of resumes. So we just added an attachment property directly to resumes instead.

So in your templates, how do you get a URL for an attachment that is part of a piece? Like this:

apos.attachments.url(data.piece.resume)

See the documentation for more information about what you can do with apostrophe-files, apostrophe-images and apostrophe-attachments. There are plenty of examples in the tutorial, especially for apostrophe-images-widgets. Hopefully this answer gives you a sense of how and when to use attachment fields directly.

Hope this is helpful!

Body:
I am the architect of Apostrophe at P'unk Avenue.

These modules are not alternatives, exactly. In fact, apostrophe-files and apostrophe-images are both built on top of apostrophe-attachments.

What is an apostrophe-file? It's a "piece" — an Apostrophe document with a title, some metadata, and in this case, an attachment field. Since it's a piece, just like any blog post or event, you can manage all of your files via the admin bar, you can use apostrophe-files-widgets to display download links around your site, and so on.

So what is an attachment? It's a schema field — a type of field you can include in the schema of any type of doc in Apostrophe, such as a piece or page.

Most schema field types are very simple. The string field type, for instance, consists of a string. The boolean field type is either true or false, and so on.

But attachments are a little tricky. In an ideal world... from a database design standpoint... the actual contents of the file would live right in your document; doc.headshot could be the actual JPEG data (or that, plus some metadata, perhaps).

But we can't do that, because files are very big, and even if they fit in a MongoDB doc (they don't always), it would be very, very inefficient especially when we're not interested in them right now.

So instead, here's what a typical apostrophe-file piece looks like in MongoDB if you use findOne to display it in the mongo shell. I've pared it down a little for simplicity. Notice the attachment property:

{
    "_id" : "xyz",
    "type" : "apostrophe-file",
    "title" : "Field Trip Permission Slip",
    "slug" : "file-field-trip-permission-slip",
    "attachment" : {
        "type" : "attachment",
        "_id" : "qqq",
        "name" : "permission-form",
        "extension" : "pdf"
    },
}

The attachment field has its own _id. And between that _id, the name property, and the extension property, the apos.attachments.url() method can put together a URL to download it.

So what does this buy us? Flexibility. Want to reuse a single library of PDFs all over your site? Use apostrophe-files, and use apostrophe-files-widgets to display download links around the site.

Want to attach a resume property to a specific person's profile piece and keep it out of the shared library? Use an attachment field in the schema for your piece type instead:

// in lib/modules/people
module.exports = {
  extend: 'apostrophe-pieces',
  addFields: [
    {
      type: 'attachment',
      name: 'resume'
    }
  ]
}

We could have used a widget to pick a file, but we didn't want to clutter the shared library of files with thousands of resumes. So we just added an attachment property directly to resumes instead.

So in your templates, how do you get a URL for an attachment that is part of a piece? Like this:

apos.attachments.url(data.piece.resume)

See the documentation for more information about what you can do with apostrophe-files, apostrophe-images and apostrophe-attachments. There are plenty of examples in the tutorial, especially for apostrophe-images-widgets. Hopefully this answer gives you a sense of how and when to use attachment fields directly.

Hope this is helpful!


问:
I can't figure out this F# error message
The error messages generated by the F# compiler are sometimes confusing. For example:

```<code>open Deedle
let inds = [1;   2;  6;  8; 11; 12]
let vals = [10; 20; 30; 40; 50; 60]
let siv = Series(inds, vals)
let fbminmax b (s: Series<float, float>) =
    if b then (Seq.min s.Values) else (Seq.max s.Values)
let sgi =
    siv
    |> Series.groupInto (fun i _ -> i % 2 = 0) fbminmax
printfn "%A" <| sgi
// error FS0001: Type mismatch. Expecting a
//    'bool -> Series<int,int> -> 'a'
// but given a
//    'bool -> Series<int,int> -> float'
// The type 'float' does not match the type 'int'
</code>```

I understand there is an error (the code works fine with Series<int,int> replacing Series<float,float> in the definition of fbminmax). And I understand that a

'bool -> Series<int,int> -> 'a'

was expected. But I do not understand why the compiler says that it was given a

'bool -> Series<int,int> -> float'

when it was given fbminmax, which is a

'bool -> Series<float,float> -> float'

Moreover, if the compiler had indeed been given a

'bool -> Series<int,int> -> float'

as it claimed it did that should have been Ok with float playing the role of 'a.

Can someone provide some insight on what is going on?

答:
The compiler error messages can indeed be somewhat cryptic. The solution: maket it generic :-)

```<code>let fbminmax b (s: Series<'T, 'T>) =
    if b then (Seq.min s.Values) else (Seq.max s.Values)
</code>```

The problem in the end is that you specify fbminmax b (s: Series<float, float>) but feed a series of ints into it.

Body:
The error messages generated by the F# compiler are sometimes confusing. For example:

open Deedle
let inds = [1;   2;  6;  8; 11; 12]
let vals = [10; 20; 30; 40; 50; 60]
let siv = Series(inds, vals)
let fbminmax b (s: Series<float, float>) =
    if b then (Seq.min s.Values) else (Seq.max s.Values)
let sgi =
    siv
    |> Series.groupInto (fun i _ -> i % 2 = 0) fbminmax
printfn "%A" <| sgi
// error FS0001: Type mismatch. Expecting a
//    'bool -> Series<int,int> -> 'a'
// but given a
//    'bool -> Series<int,int> -> float'
// The type 'float' does not match the type 'int'

I understand there is an error (the code works fine with Series<int,int> replacing Series<float,float> in the definition of fbminmax). And I understand that a

'bool -> Series<int,int> -> 'a'

was expected. But I do not understand why the compiler says that it was given a

'bool -> Series<int,int> -> float'

when it was given fbminmax, which is a

'bool -> Series<float,float> -> float'

Moreover, if the compiler had indeed been given a

'bool -> Series<int,int> -> float'

as it claimed it did that should have been Ok with float playing the role of 'a.

Can someone provide some insight on what is going on?

Body:
The compiler error messages can indeed be somewhat cryptic. The solution: maket it generic :-)

let fbminmax b (s: Series<'T, 'T>) =
    if b then (Seq.min s.Values) else (Seq.max s.Values)

The problem in the end is that you specify fbminmax b (s: Series<float, float>) but feed a series of ints into it.


问:
Displaying sub values in rails view
I'm working on a pretty large rails application and one of the tasks is to display a very large list of clients. Each client has multiple servers. I'm able to display all of the clients via the @client_name loop in the view. However, I'm unable to display each clients respective servers. (I hope this makes sense). To give a bit more context, when you access the clients index page, you can select on a client and a dropdown list of servers tied to that client is supposed to show up. The user can then select from that dropdown and will be redirected to that individual servers show page.

My controller looks like this

```<code>def index
 @nodes = Node.all.paginate(page: params[:page], per_page: 40
end

def node_filter
  @client_name =  @nodes.distinct.pluck(:client_name)
  @hostname = @nodes.pluck(:hostname)
end
</code>```

The index (view) looks like this (styling removed for clarity)

```<code><% @client_name.each do |cn| %>
  <tr>
    <td>
     <p><%= cn %></p>
     <p><%=@hostname %></p> <!-- displaying ALL servers regardless of client ownership -->
    </td>
  </tr>
<% end %>
</code>```

This is acting exactly how you'd expect. Each dropdown has a list of all of the hosts. I tried creating a helper method that would iterate through the @hostname array, trying to match it to "cn" and displaying it but that didn't work out at all. I know there's an easy way to do this, I'm certain that I'm overthinking it and it's driving me crazy so I'm reaching out to the pros. Any advice, or help would be greatly appreciated.

Also, To make things easier this is a single table with client_name and hostname.

答: This turned out to be a relationship issue. Storing everything in a single table then trying to display the information the way I was required me to try to do silly parsing to get things to display how I needed them. Instead, splitting the tables and creating the appropriate relationships between them allowed me to easily query and display what I needed. </p>

Title: Displaying sub values in rails view

Body:
I'm working on a pretty large rails application and one of the tasks is to display a very large list of clients. Each client has multiple servers. I'm able to display all of the clients via the @client_name loop in the view. However, I'm unable to display each clients respective servers. (I hope this makes sense). To give a bit more context, when you access the clients index page, you can select on a client and a dropdown list of servers tied to that client is supposed to show up. The user can then select from that dropdown and will be redirected to that individual servers show page.

My controller looks like this

def index
 @nodes = Node.all.paginate(page: params[:page], per_page: 40
end

def node_filter
  @client_name =  @nodes.distinct.pluck(:client_name)
  @hostname = @nodes.pluck(:hostname)
end

The index (view) looks like this (styling removed for clarity)

<% @client_name.each do |cn| %>

<%= cn %>

<%=@hostname %>

<% end %>

This is acting exactly how you'd expect. Each dropdown has a list of all of the hosts. I tried creating a helper method that would iterate through the @hostname array, trying to match it to "cn" and displaying it but that didn't work out at all. I know there's an easy way to do this, I'm certain that I'm overthinking it and it's driving me crazy so I'm reaching out to the pros. Any advice, or help would be greatly appreciated.

Also, To make things easier this is a single table with client_name and hostname.


问:
Trouble using attach() in R
I am having trouble assigning columns to the strings above them.  I believe the proper way to do this is use the attach() function.  I have a csv file loaded with columns of data on Flight, O.ring, and Temp.  I have tried to clear previously attached data by using the detach() function, but have not had any luck.

```<code>### Files saved in the directory below
setwd("/Users/newUser/desktop/programming")
data <- read.table("Challenger.csv", header=TRUE)
attach(data)
O.ring
Error: object 'O.ring' not found
Flight
Error: object 'Flight' not found
Temp
Error: object 'Temp' not found
fit1 <- glm(O.ring ~ Temp + Pressure, family=binomial(logit))
Error in eval(expr, envir, enclos) : object 'O.ring' not found
fit1
Error: object 'fit1' not found
</code>```

Edit:  I also need help accessing the columns stored in data to use them to model.  Any idea what the problem is with my fit1?

答:
Don't use attach().  Ever.  Forget it exists.

glm() has a data argument.  Using that proves much less stressful.

```<code>glm(O.ring ~ Temp + Pressure, family = binomial(logit), data = data)
</code>```

If you want to know why attach() is not advisable, see Why is it not advisable to use attach() in R and what should I use instead?

Title: Trouble using attach() in R

Body:
I am having trouble assigning columns to the strings above them.  I believe the proper way to do this is use the attach() function.  I have a csv file loaded with columns of data on Flight, O.ring, and Temp.  I have tried to clear previously attached data by using the detach() function, but have not had any luck.

### Files saved in the directory below
setwd("/Users/newUser/desktop/programming")
data <- read.table("Challenger.csv", header=TRUE)
attach(data)
O.ring
Error: object 'O.ring' not found
Flight
Error: object 'Flight' not found
Temp
Error: object 'Temp' not found
fit1 <- glm(O.ring ~ Temp + Pressure, family=binomial(logit))
Error in eval(expr, envir, enclos) : object 'O.ring' not found
fit1
Error: object 'fit1' not found

Edit:  I also need help accessing the columns stored in data to use them to model.  Any idea what the problem is with my fit1?

Body:
Don't use attach().  Ever.  Forget it exists.

glm() has a data argument.  Using that proves much less stressful.

glm(O.ring ~ Temp + Pressure, family = binomial(logit), data = data)

If you want to know why attach() is not advisable, see Why is it not advisable to use attach() in R and what should I use instead?


问:
Deploying outlook add-in as an admin removes iOS support
I have a simple task-pane Outlook add-in. When I install it manually (uploading the manifest file) to one account, it works well : on Outlook Desktop, Outlook online, OWA, and the iOS Outlook app.

When I install it to the whole organization through the Microsoft Exchange Admin Center (Organization --> Add-ins --> Add), two stranges behaviors occur :

1) It is immediately deployed to all accounts ; except for the administrator himself (~3 hours of delay before it is deployed !). Why ?

2) Once deployed, the Outlook iOS app support disappears, whereas the uploaded manifest is the exact same file. Desktop, Web, and OWA apps works well. The add-in indeed appears in the "Parameters > Manage add-ins > My add-ins" of each user.

I can't find or explain this problem. Did anyone find a solution or an explanation ?

答:
The delay can actually affect all users. We cache installed add-ins server side for performance improvements.

In terms of the add-in on ios, the scenario of admin installing add-in to mobile is currently not supported. This is in our backlog, and we'll be getting to this soon.


问:
Google chrome extension error when debugger open only
I am trying to send a ajax request to a server inside a google chrome extension. I am using angular with it too and the code is inside the controller. The request works fine generally, but when I have the the DevTools open it throws an error. This is the relevant part of the code:

```<code>    $scope.sendLink = function (){
        chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
            var url = tabs[0].url;
            var date = new Date();
            var xPost = new XMLHttpRequest();
            xPost.open("POST", **URL HERE*",true);
            xPost.setRequestHeader("Content-type", "application/json");
            xPost.send(JSON.stringify({"name":$scope.name,"url":url,"date":date}));
        });

    }
</code>```

When I hit inspect element on the extension, and then do the request, the tabs array come back as empty. It works fine if the devTools window is closed. I can't figure out why that is the case. Any explanation would be appreciated!

答:
You could have changed the javascript engine behavior via chrome-dev-tools. This would get activated only when the dev-tools are open.

For instance, once I found that a mate of mine had turned-off javascript using the chrome-dev-tools. His app wasn't executing when the chrome-dev-tools were open...

Body:
I am trying to send a ajax request to a server inside a google chrome extension. I am using angular with it too and the code is inside the controller. The request works fine generally, but when I have the the DevTools open it throws an error. This is the relevant part of the code:

    $scope.sendLink = function (){
        chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
            var url = tabs[0].url;
            var date = new Date();
            var xPost = new XMLHttpRequest();
            xPost.open("POST", **URL HERE*",true);
            xPost.setRequestHeader("Content-type", "application/json");
            xPost.send(JSON.stringify({"name":$scope.name,"url":url,"date":date}));
        });

    }

When I hit inspect element on the extension, and then do the request, the tabs array come back as empty. It works fine if the devTools window is closed. I can't figure out why that is the case. Any explanation would be appreciated!


问:
Is there an API to force Facebook to scrape a page again?
I'm aware you can force update a page's cache by entering the URL on Facebook's debugger tool while been logged in as admin for that app/page:
https://developers.facebook.com/tools/debug

But what I need is a way to automatically call an API endpoint or something from our internal app whenever somebody from our Sales department updates the main image of one of our pages. It is not an option to ask thousands of sales people to login as an admin and manually update a page's cache whenever they update one of our item's description or image.

We can't afford to wait 24 hours for Facebook to update its cache because we're getting daily complaints from our clients whenever they don't see a change showing up as soon as we change it on our side.

答: I'm the author of Facebook Object Debugger CLI, a command-line interface written in PHP, aim to refresh the Facebook cache for a single URL or a bunch of URLS using as input a text file. The package is also available on Packagist and can be installed using Composer.</p>


问:
Ruby on Rails in OS X Snow Leopard - what versions do I have installed?
I've been trying to get Ruby on Rails working on my Snow Leopard 64-bit MacBook Pro. I followed the instructions in Agile Web Development with Rails and everything seemed to install fine (and allows me to create a demo site), but I got an error to do with sqlite3 when trying to start the web server on my simple demo site (see this question for details of the error I get). I suspect at some point I've managed to install the wrong version or achitecture of a package (I'm using MacPorts) which is causing the problems.

Note: I'm not re-asking that previous question, what I want to know is Is there a way I can determine exactly which versions of each ruby package I have installed, and for what architecture they were built?

I've (foolishly) lost track of the sudo port install lines I've typed so I'm not sure what's currently on my system to try to diagnose how to fix it.

I'd like a list of something like:

```<code>Ruby v.1.9.2 - 64bit
Rails v 2.1 - 32bit
... etc.
</code>```

Alternatively can I do something (short of reinstalling OS X and XCode) to remove all traces of Ruby from my system and start again?

If you have advice on how to fix the sqlite3 error I'm getting, please answer on the question linked to above, not here.

答:
sudo port list installed  will show you what ports you have installed

I would look at installing RVM (http://rvm.beginrescueend.com/)   as well (as it allows you to keep all the rubies separate). and makes it easy to totally remove a ruby and all its gems/etc..

Did you install ruby from ports or are you using the system ruby?

What does ruby -v or which ruby  show ?

ContentLicense: CC BY-SA 2.5

Body:
I've been trying to get Ruby on Rails working on my Snow Leopard 64-bit MacBook Pro. I followed the instructions in Agile Web Development with Rails and everything seemed to install fine (and allows me to create a demo site), but I got an error to do with sqlite3 when trying to start the web server on my simple demo site (see this question for details of the error I get). I suspect at some point I've managed to install the wrong version or achitecture of a package (I'm using MacPorts) which is causing the problems.

Note: I'm not re-asking that previous question, what I want to know is Is there a way I can determine exactly which versions of each ruby package I have installed, and for what architecture they were built?

I've (foolishly) lost track of the sudo port install lines I've typed so I'm not sure what's currently on my system to try to diagnose how to fix it.

I'd like a list of something like:

Ruby v.1.9.2 - 64bit
Rails v 2.1 - 32bit
... etc.

Alternatively can I do something (short of reinstalling OS X and XCode) to remove all traces of Ruby from my system and start again?

If you have advice on how to fix the sqlite3 error I'm getting, please answer on the question linked to above, not here.


问:
Failed to "push origin master"
Im trying to commit my files to GitHub.
My commands :

```<code>git status
git add -A
git commit -m 'message'
git push master origin
</code>```

Then these errors showed up

```<code>error: src refspec origin does not match any.
error: failed to push some refs to 'master'
</code>```

What should I do to fix this ?
Thank you.

答:
You have git push master origin...please try the following command:

git push origin master

Title: Failed to "push origin master"

Body:
Im trying to commit my files to GitHub.
My commands :

git status
git add -A
git commit -m 'message'
git push master origin

Then these errors showed up

error: src refspec origin does not match any.
error: failed to push some refs to 'master'

What should I do to fix this ?
Thank you.


问:
Dagger2 one module for two different scopes
In my app i have an ApplicationScope which provides me with stuff like context and shared prefs.
2 sub components, LoggedInComponent and LoggedOutComponent.
Those 2 subcomponents have other subcomponents which are less relevant to the issue.

I have a NetworkModule which creates my retrofit instance.
Both subcomponents need the NetworkModule but the retrofit might change during the login because the base url and other settings might change.

I was wondering which approach it is better to take:
1. Give both LoggedIn and LoggedOut sub components and the NetworkModule the same scope so both sub components can use this module. Feels a bit hacky and wrong usage of scopes.
2. Put network module in the AppComponent with ApplicationScope. Also wrong usage of scope because network module is recreated so it cannot have same scope and also each recreation will cause the AppComponent and its subcomponents to be recreated.

What would you do? maybe there is a better solution?

答:
You don't want LoggedInComponent and LoggedOutComponent to have differing network behavior, and you don't necessarily need network behavior to be consistent across the lifetime of LoggedInComponent or LoggedOutComponent, so it doesn't make sense for you to have them bind NetworkModule separately. I think it makes sense to make them available through AppComponent. Remember that not everything in AppComponent needs to have ApplicationScope: You can make unscoped bindings in AppComponent, which instructs Dagger to re-fetch or re-create the requested object every time.

Specifically, I would bind NetworkModule into a subcomponent of AppComponent, which you can recreate every time the NetworkModule configuration changes. Not only would this let you encapsulate some of the network details (see "subcomponents for encapsulation" in the Dagger User's Guide), but it would also let you take advantage of dependency injection throughout your network bindings if that's what you're looking for.

To ensure that you're getting the correct current NetworkComponent, you could create a NetworkManager that is singleton-bound (ApplicationScope). You can use that to hold the latest NetworkComponent.

```<code>@Module(subcomponents={NetworkComponent.class})
public abstract class ApplicationModule {
  /** Unscoped. Fetch this fresh from NetworkComponentHolder each time. */
  @Provides Retrofit provideRetrofit(NetworkManager manager) {
    return manager.getNetworkComponent().getRetrofit();
  }
}

@ApplicationScope public class NetworkManager {
  private final Provider<NetworkComponent.Builder> builderProvider;
  private NetworkComponent currentComponent;

  @Inject public NetworkComponentHolder(
      Provider<NetworkComponent.Builder> builderProvider) {
    this.builderProvider = builderProvider;
    currentComponent = builderProvider.get()
        .withNetworkModule(getDefault())
        .build();
  }

  public void updateSettings(String baseUrl) {
    currentComponent = builderProvider.get()
        .withNetworkModule(new NetworkModule(baseUrl))
        .build();
  }

  public NetworkComponent getNetworkComponent() {
    return currentComponent;
  }
}
</code>```

With this, most of your code in AppComponent, LoggedInComponent, and LoggedOutComponent can just inject a Retrofit (or Provider<Retrofit>) whenever they need to make a request. When a response comes back that tells you to update your base URL, you can inject a NetworkManager, call updateSettings, and suddenly new requests for Retrofit will return your new instance. (Note however that old instances to Retrofit may still stick around, but you'll have that problem any time you're changing a dependency belonging to an existing instance.)

p.s. If NetworkModule is lightweight enough, or has consistent-enough bindings, you might opt to put NetworkModule directly onto ApplicationComponent and simply have NetworkManager hold the current Retrofit instance etc. You'll have to make that judgment call based on the number of bindings you want to pass through as provideRetrofit does, compared to the number of bindings you'd want to encapsulate or hide away in a subcomponent.

Body:
You don't want LoggedInComponent and LoggedOutComponent to have differing network behavior, and you don't necessarily need network behavior to be consistent across the lifetime of LoggedInComponent or LoggedOutComponent, so it doesn't make sense for you to have them bind NetworkModule separately. I think it makes sense to make them available through AppComponent. Remember that not everything in AppComponent needs to have ApplicationScope: You can make unscoped bindings in AppComponent, which instructs Dagger to re-fetch or re-create the requested object every time.

Specifically, I would bind NetworkModule into a subcomponent of AppComponent, which you can recreate every time the NetworkModule configuration changes. Not only would this let you encapsulate some of the network details (see "subcomponents for encapsulation" in the Dagger User's Guide), but it would also let you take advantage of dependency injection throughout your network bindings if that's what you're looking for.

To ensure that you're getting the correct current NetworkComponent, you could create a NetworkManager that is singleton-bound (ApplicationScope). You can use that to hold the latest NetworkComponent.

@Module(subcomponents={NetworkComponent.class})
public abstract class ApplicationModule {
  /** Unscoped. Fetch this fresh from NetworkComponentHolder each time. */
  @Provides Retrofit provideRetrofit(NetworkManager manager) {
    return manager.getNetworkComponent().getRetrofit();
  }
}

@ApplicationScope public class NetworkManager {
  private final Provider<NetworkComponent.Builder> builderProvider;
  private NetworkComponent currentComponent;

  @Inject public NetworkComponentHolder(
      Provider<NetworkComponent.Builder> builderProvider) {
    this.builderProvider = builderProvider;
    currentComponent = builderProvider.get()
        .withNetworkModule(getDefault())
        .build();
  }

  public void updateSettings(String baseUrl) {
    currentComponent = builderProvider.get()
        .withNetworkModule(new NetworkModule(baseUrl))
        .build();
  }

  public NetworkComponent getNetworkComponent() {
    return currentComponent;
  }
}

With this, most of your code in AppComponent, LoggedInComponent, and LoggedOutComponent can just inject a Retrofit (or Provider<Retrofit>) whenever they need to make a request. When a response comes back that tells you to update your base URL, you can inject a NetworkManager, call updateSettings, and suddenly new requests for Retrofit will return your new instance. (Note however that old instances to Retrofit may still stick around, but you'll have that problem any time you're changing a dependency belonging to an existing instance.)

p.s. If NetworkModule is lightweight enough, or has consistent-enough bindings, you might opt to put NetworkModule directly onto ApplicationComponent and simply have NetworkManager hold the current Retrofit instance etc. You'll have to make that judgment call based on the number of bindings you want to pass through as provideRetrofit does, compared to the number of bindings you'd want to encapsulate or hide away in a subcomponent.


问:
How to replace string in files recursively via sed or awk?
I would like to know how to search from the command line for a string in various files of type .rb.

And replace:

```<code>.delay([ANY OPTIONAL TEXT FOR DELETION]).
</code>```

with

```<code>.delay.
</code>```

Besides sed an awk are there any other command line tools included in the OS that are better for the task?

Status

So far I have the following regular expression:

```<code>.delay\(*.*\)\.
</code>```

I would like to know how to match only the expression ending on the first closing parenthesis? And avoid replacing:

```<code>.delay([ANY OPTIONAL TEXT FOR DELETION]).sometext(param)
</code>```

Thanks in advance!

答:
If you need to find and replace text in files - sed seems to be the best command line solution.

Search for a string in the text file and replace:

```<code>sed -i 's/PATTERN/REPLACEMENT/' file.name
</code>```

Or, if you need to process multiple occurencies of PATTERN in file, add g key

```<code>sed -i 's/PATTERN/REPLACEMENT/g' file.name
</code>```

For multiple files processing - redirect list of files to sed:

```<code>echo "${filesList}" | xargs sed -i ...
</code>```

Body:
I would like to know how to search from the command line for a string in various files of type .rb.

And replace:

.delay([ANY OPTIONAL TEXT FOR DELETION]).

with

.delay.

Besides sed an awk are there any other command line tools included in the OS that are better for the task?

Status

So far I have the following regular expression:

.delay\(*.*\)\.

I would like to know how to match only the expression ending on the first closing parenthesis? And avoid replacing:

.delay([ANY OPTIONAL TEXT FOR DELETION]).sometext(param)

Thanks in advance!

Body:
If you need to find and replace text in files - sed seems to be the best command line solution.

Search for a string in the text file and replace:

sed -i 's/PATTERN/REPLACEMENT/' file.name

Or, if you need to process multiple occurencies of PATTERN in file, add g key

sed -i 's/PATTERN/REPLACEMENT/g' file.name

For multiple files processing - redirect list of files to sed:

echo "${filesList}" | xargs sed -i ...


问:
Finding multi-line string in PHP file
I am working on a program in which an addon needs to modify a system file.

I have a small method in which I am finding the beginning of the string in the file like this:

```<code>     /**
     * @param $fileName
     * @param $str
     *
     * @return int
     */
    private function getLineWithString($fileName, $str)
    {
        $lines = file($fileName);
        foreach ($lines as $lineNumber => $line) {
            if (strpos($line, $str) !== false) {
                return $line;
            }
        }
        return -1;
    }
</code>```

I am calling that from within the method where I need to pull that string out to replace it like this:

```<code>//  Set our file to use
$originalFile = 'file.php';

// Find The array['key'] string
$myString = "\$array['key']";

// Process - Find it
$lineNo = $this->getLineWithString($originalFile, $myString);
</code>```

Then echo $lineNo; returns $array['key'] = array(.

However, I need it to return the entire multi-line array/string up until the next ; (semicolon).

How would I go about this?

Thanks

* EDIT *

My PHP file contents are like this:

```<code><?php
    /**
     * Comment here
    */
     $first_array = array(
         'key1' => 'val1',
         'key2' => 'val2',
         'key3' => 'val3',
         'key4' => 'val4',
         'key5' => 'val5'
    );

    $second_array = array(
        'key1' => 'val1',
        'key2' => 'val2'
    );
    ...
</code>```

I have tried the suggestion from @Scuzzy

This is in my method now:

```<code>// Open Existing File And Get Contents
$myFile = file_get_contents('myFile.php');

$tokens = token_get_all($myFile);

foreach ( $tokens as $token ) {
    if (is_array($token)) {
        if( $token[0] === T_CONSTANT_ENCAPSED_STRING and strpos( $token[1], "\n" ) !== false )
        {
            var_dump( $token );
        }
    }
}
</code>```

However, this doesn't return anything.

I need to return something like:

```<code>$second_array = array(
    'key1' => 'val1',
    'key2' => 'val2'
);
</code>```

As a string I can manipulate and rewrite.

答:
Rather than trying to parse a PHP file in PHP, depending on what you're needing to do, you might be able to use var_export().

require_once($filename);

// variables are now in global scope
// manipulate as necessary
$first_array['this_key'] = 'that value';

$str = '$first_array = '.var_export($first_array, TRUE).";\n\n";
$str .= '$second_array = '.var_export($second_array, TRUE).';';

// output the updated arrays back to the file
file_put_contents($filename, $str);
```

Title: Finding multi-line string in PHP file

Body:
I am working on a program in which an addon needs to modify a system file.

I have a small method in which I am finding the beginning of the string in the file like this:

     /**
     * @param $fileName
     * @param $str
     *
     * @return int
     */
    private function getLineWithString($fileName, $str)
    {
        $lines = file($fileName);
        foreach ($lines as $lineNumber => $line) {
            if (strpos($line, $str) !== false) {
                return $line;
            }
        }
        return -1;
    }

I am calling that from within the method where I need to pull that string out to replace it like this:

//  Set our file to use
$originalFile = 'file.php';

// Find The array['key'] string
$myString = "\$array['key']";

// Process - Find it
$lineNo = $this->getLineWithString($originalFile, $myString);

Then echo $lineNo; returns $array['key'] = array(.

However, I need it to return the entire multi-line array/string up until the next ; (semicolon).

How would I go about this?

Thanks

* EDIT *

My PHP file contents are like this:

<?php
    /**
     * Comment here
    */
     $first_array = array(
         'key1' => 'val1',
         'key2' => 'val2',
         'key3' => 'val3',
         'key4' => 'val4',
         'key5' => 'val5'
    );

    $second_array = array(
        'key1' => 'val1',
        'key2' => 'val2'
    );
    ...

I have tried the suggestion from @Scuzzy

This is in my method now:

// Open Existing File And Get Contents
$myFile = file_get_contents('myFile.php');

$tokens = token_get_all($myFile);

foreach ( $tokens as $token ) {
    if (is_array($token)) {
        if( $token[0] === T_CONSTANT_ENCAPSED_STRING and strpos( $token[1], "\n" ) !== false )
        {
            var_dump( $token );
        }
    }
}

However, this doesn't return anything.

I need to return something like:

$second_array = array(
    'key1' => 'val1',
    'key2' => 'val2'
);

As a string I can manipulate and rewrite.


问:
Azure Metrics for Virtual Machine
I am trying to obtain metrics for an Azure Virtual Machine. The standard Insights API provided doesn't provide all the metrics. Upon more reading I found that these metrics are stored in Azure Storage Accounts under different tables. Is there a way to make an API call to these tables and retrieve the metrics ?</p>

答:
There are two categories of metrics for Azure Virtual Machine -- host level metrics that are derived from Hyper V performance counters and the guest level metrics that come from within the VM itself.

For host level metrics, the Insights REST API provides access to this data.

https://learn.microsoft.com/en-us/azure/monitoring-and-diagnostics/monitoring-overview-metrics

For guest metrics such as Memory metrics, you need to install the diagnostics agent to collect this data to one of the supported sink types such as storage account, event hub, or Application Insights. If you collect this data to storage account or event hub, you need to use the standard storage API or event hub API to access this data.  Specifically for storage, the data will be stored in WADPerformanceCountersTable in Azure table storage. There is no additional REST API to retrieve this data outside of the existing storage API.

https://learn.microsoft.com/en-us/azure/monitoring-and-diagnostics/azure-diagnostics

Title: Azure Metrics for Virtual Machine


问:
ASP.NET DATA TABLE Traverse Problem
I am getting the Data table a output from my DataAccess Layer.

In My Datatable I am getting users Name,Number,Qualification

I want to assign a users name,number,qualification to a textbox for a particular user id,

How can i do that.

Help

答:
You have to pay attention to NULL values and number of rows.

```<code>if (table.Rows.Count == 1)
{
  DataRow row = table.Rows[0];

  NameTextBox.Text = row.IsNull("name") ? string.Empty : row["name"];
  NumberTextBox.Text = row.IsNull("number") ? string.Empty : row["number"];
}
else
{
// Deal with no rows from DL
}
</code>```

Using ternary operator makes you sure, you delete content of TextBoxes in case you reload row within already filled up page.

Also you may consider to used typed dataset, and access to columns will be generated by xsd.exe.

Title: ASP.NET DATA TABLE Traverse Problem

Body:
You have to pay attention to NULL values and number of rows.

if (table.Rows.Count == 1)
{
  DataRow row = table.Rows[0];

  NameTextBox.Text = row.IsNull("name") ? string.Empty : row["name"];
  NumberTextBox.Text = row.IsNull("number") ? string.Empty : row["number"];
}
else
{
// Deal with no rows from DL
}

Using ternary operator makes you sure, you delete content of TextBoxes in case you reload row within already filled up page.

Also you may consider to used typed dataset, and access to columns will be generated by xsd.exe.


答:
programming in JSON

What? JSON is always just a string - it is the string representation of various forms of data; nothing more.

If you have some JSON and you want to read some data from it, or manipulate it, first you will want to convert the JSON to usable data

But before that you have to fix your BROKEN JSON – you have trailing commas that are not valid

```<code>var brokenjson = '{"items": [{"id": 1, "name": "BV",},{"id": 2,"name": "NV"}],}'

var goodjson   = '{"items": [{"id": 1, "name": "BV"},{"id": 2,"name": "NV"}]}'
</code>```

Now that your JSON is fixed, we can get what you're looking for

var json = '{"items": [{"id": 1, "name": "BV"},{"id": 2,"name": "NV"}]}'

var data = JSON.parse(json)

// get id from items where name is 'NV'
console.log(data.items.find(x => x.name === 'NV').id) // 2```
</div>
</div>
</p>

<hr>

<p>If you don't have <code>Array.prototype.find</code>, just make it</p>

```Array.prototype.find = function find (f, context) {
  for (var i = 0; i < this.length; i++)
    if (f.call(context || window, this[i], i, this))
      return this[i]
}
```

Title: How can I search for an object property value in an array if I only know a different property?

Body:
In this array I would like to find the id of the object by querying on the property name. Given I know the name is NV, how can I get the id?

I already tried different loops and other thing like GetObject, but it gives no return.

{
  "items": [
    {
      "id": 1,
      "name": "BV",
    },
    {
      "id": 2,
      "name": "NV"
    }
  ],
}

Body:
programming in JSON

What? JSON is always just a string - it is the string representation of various forms of data; nothing more.

If you have some JSON and you want to read some data from it, or manipulate it, first you will want to convert the JSON to usable data

But before that you have to fix your BROKEN JSON – you have trailing commas that are not valid

var brokenjson = '{"items": [{"id": 1, "name": "BV",},{"id": 2,"name": "NV"}],}'

var goodjson   = '{"items": [{"id": 1, "name": "BV"},{"id": 2,"name": "NV"}]}'

Now that your JSON is fixed, we can get what you're looking for

var json = '{"items": [{"id": 1, "name": "BV"},{"id": 2,"name": "NV"}]}'

var data = JSON.parse(json)

// get id from items where name is 'NV'
console.log(data.items.find(x => x.name === 'NV').id) // 2

If you don't have Array.prototype.find, just make it

Array.prototype.find = function find (f, context) {
  for (var i = 0; i < this.length; i++)
    if (f.call(context || window, this[i], i, this))
      return this[i]
}


问:
Trouble getting total count using .Take() and .Skip()
I'm having some trouble implementing some paging using Linq and I've read the various questions (this and this for example) on here but I'm still getting the error;

System.InvalidOperationException: The result of a query cannot be enumerated more than once.

My (slightly obfuscated) code is;

```<code>public List<Thing> GetThings(ObjectParameter[] params, int count, int pageIndex)
{
    var things = from t in Context.ExecuteFunction<Something>("function", params)
                 select new Thing
                 {
                     ID = t.ID
                 });

    var pagedThings = things;

    if (pageIndex == 0)
        pagedThings = things.Take(count);
    else if (pageIndex > 0)
        pagedThings = things.Skip(count * pageIndex).Take(count);

    var countOfThings = things.Count();

    return pagedThings.ToList();
}
</code>```

As soon as the final .ToList() is called, the error is thrown but I can't see why - are the calls to things.Count() and pagedThings.ToList() enumerating the same thing?

Edit: I'm using Entity Framework if that makes any difference

答:
ExecuteFunction actually returns an ObjectResult if I'm not mistaken, which is... more complicated. You may get different results if you make the function composable (which would execute a separate query when you Count()), but it's been a while since I worked with low level EF so I'm not 100% sure that would work.

Since you can't get out of executing what are effectively two queries, the safest bet is to make a completely separate one for counting - and by completely separate I mean a separate function or stored procedure, which just does the count, otherwise you may end up (depending on your function) returning rows to EF and counting them in memory. Or rewrite the function as a view if at all possible, which may make it more straightforward.

Body:
I'm having some trouble implementing some paging using Linq and I've read the various questions (this and this for example) on here but I'm still getting the error;

System.InvalidOperationException: The result of a query cannot be enumerated more than once.

My (slightly obfuscated) code is;

public List<Thing> GetThings(ObjectParameter[] params, int count, int pageIndex)
{
    var things = from t in Context.ExecuteFunction<Something>("function", params)
                 select new Thing
                 {
                     ID = t.ID
                 });

    var pagedThings = things;

    if (pageIndex == 0)
        pagedThings = things.Take(count);
    else if (pageIndex > 0)
        pagedThings = things.Skip(count * pageIndex).Take(count);

    var countOfThings = things.Count();

    return pagedThings.ToList();
}

As soon as the final .ToList() is called, the error is thrown but I can't see why - are the calls to things.Count() and pagedThings.ToList() enumerating the same thing?

Edit: I'm using Entity Framework if that makes any difference


问:
How to create an array of references
Create an array of references

I've read the link above and known how to create an array of references in Java. But it doesn't seem to work...

Here is my test:

```<code>Character []c1 = {'a', 'x'};
Character []c2 = new Character[1];
c2[0] = c1[0]; // I try to make c2[0] as the reference of c1[0]
c1[0] = 'b';

System.out.println(c1[0]);    // b
System.out.println(c2[0]);    // a
</code>```

Is there any way such that I can make c2[0] as a reference of c1[0] so that any change in c1[0] will update the value in c2[0].

答:
Check below two examples to get the understanding.</p>

```<code>//1st example
Emp emp1 = new Emp("Emp1");
Emp emp2 = new Emp("Emp2");

Emp []c1 = {emp1, emp2};
Emp []c2 = new Emp[1];
c2[0] = c1[0];
c1[0].setName("test");

System.out.println(c1[0].getName()); // Prints test
System.out.println(c2[0].getName()); // Prints test

//2nd example
Character []c1 = {'a', 'x'};
Character []c2 = new Character[2];
c2 = c1; // I try to make c2[0] as the reference of c1[0]
c1[0] = 'b';

System.out.println(c1[0]);    // b
System.out.println(c2[0]);    // b
</code>```

Title: How to create an array of references

Body:
Create an array of references

I've read the link above and known how to create an array of references in Java. But it doesn't seem to work...

Here is my test:

Character []c1 = {'a', 'x'};
Character []c2 = new Character[1];
c2[0] = c1[0]; // I try to make c2[0] as the reference of c1[0]
c1[0] = 'b';

System.out.println(c1[0]);    // b
System.out.println(c2[0]);    // a

Is there any way such that I can make c2[0] as a reference of c1[0] so that any change in c1[0] will update the value in c2[0].

Body:
Check below two examples to get the understanding.

//1st example
Emp emp1 = new Emp("Emp1");
Emp emp2 = new Emp("Emp2");

Emp []c1 = {emp1, emp2};
Emp []c2 = new Emp[1];
c2[0] = c1[0];
c1[0].setName("test");

System.out.println(c1[0].getName()); // Prints test
System.out.println(c2[0].getName()); // Prints test

//2nd example
Character []c1 = {'a', 'x'};
Character []c2 = new Character[2];
c2 = c1; // I try to make c2[0] as the reference of c1[0]
c1[0] = 'b';

System.out.println(c1[0]);    // b
System.out.println(c2[0]);    // b


问:
Android/Xamarin: How to launch dialog with broadcast receiver
I want my app to listen for intends broadcasted by the call application, and when a call intend is broadcasted for a specific number I want to launch a dialog. I read that "A broadcast receiver may not display dialogs, and it is strongly discouraged to start an activity from within a broadcast receiver" https://developer.xamarin.com/guides/android/application_fundamentals/broadcast-receivers/ so I am assuming I should instead make the broadcast receiver launch a service that then launches a dialog. Can anyone confirm this? Also any simplified examples would be highly appreciated

Thanks!

答:
In the example below, the app uses a BroadcastReceiver to detect a phone call number and decide whether it should answer or not:

How to reject incoming call programatically in android?

So using a BroadcastReceiver for that isn't that bad.

If you just want to show information about the phone call, you can display an Notification, as suggested by Jon Douglas in the comments. Displaying Dialogs from BroadcastReceivers isn't allowed (also disencouraged).


问:
Train OpenNMT with pytorch and `TypeError: NoneType object is not callable`
I was trying to train OpenNMT example on mac with cpu with the following steps:

Env: python3.5, Pytorch 0.1.10.1

Step 1

preprocess data and shrink src and tgt to have only the first 100 sentences by inserting the following lines after line133 in preprocess.py

    shrink = True
    if shrink:
        src = src[0:100]
        tgt = tgt[0:100]

then, I ran

```<code>python preprocess.py -train_src data/src-train.txt -train_tgt data/tgt-train.txt -valid_src data/src-val.txt -valid_tgt data/tgt-val.txt -save_data data/demo
</code>```

Step 2

then I train using python train.py -data data/demo.train.pt -save_model demo_model

Then it rans ok for a while before an error appeared:

```<code>(dlnd-tf-lab)  ->python train.py -data data/demo.train.pt -save_model demo_model
Namespace(batch_size=64, brnn=False, brnn_merge='concat', curriculum=False, data='data/demo.train.pt', dropout=0.3, epochs=13, extra_shuffle=False, gpus=[], input_feed=1, layers=2, learning_rate=1.0, learning_rate_decay=0.5, log_interval=50, max_generator_batches=32, max_grad_norm=5, optim='sgd', param_init=0.1, pre_word_vecs_dec=None, pre_word_vecs_enc=None, rnn_size=500, save_model='demo_model', start_decay_at=8, start_epoch=1, train_from='', train_from_state_dict='', word_vec_size=500)
Loading data from 'data/demo.train.pt'
 * vocabulary size. source = 24999; target = 35820
 * number of training sentences. 100
 * maximum batch size. 64
Building model...
* number of parameters: 58121320
NMTModel (
  (encoder): Encoder (
    (word_lut): Embedding(24999, 500, padding_idx=0)
    (rnn): LSTM(500, 500, num_layers=2, dropout=0.3)
  )
  (decoder): Decoder (
    (word_lut): Embedding(35820, 500, padding_idx=0)
    (rnn): StackedLSTM (
      (dropout): Dropout (p = 0.3)
      (layers): ModuleList (
        (0): LSTMCell(1000, 500)
        (1): LSTMCell(500, 500)
      )
    )
    (attn): GlobalAttention (
      (linear_in): Linear (500 -> 500)
      (sm): Softmax ()
      (linear_out): Linear (1000 -> 500)
      (tanh): Tanh ()
    )
    (dropout): Dropout (p = 0.3)
  )
  (generator): Sequential (
    (0): Linear (500 -> 35820)
    (1): LogSoftmax ()
  )
)

Train perplexity: 29508.9
Train accuracy: 0.0216306
Validation perplexity: 4.50917e+08
Validation accuracy: 3.57853

Train perplexity: 1.07012e+07
Train accuracy: 0.06198
Validation perplexity: 103639
Validation accuracy: 0.944334

Train perplexity: 458795
Train accuracy: 0.031198
Validation perplexity: 43578.2
Validation accuracy: 3.42942

Train perplexity: 144931
Train accuracy: 0.0432612
Validation perplexity: 78366.8
Validation accuracy: 2.33598
Decaying learning rate to 0.5

Train perplexity: 58696.8
Train accuracy: 0.0278702
Validation perplexity: 14045.8
Validation accuracy: 3.67793
Decaying learning rate to 0.25

Train perplexity: 10045.1
Train accuracy: 0.0457571
Validation perplexity: 26435.6
Validation accuracy: 4.87078
Decaying learning rate to 0.125

Train perplexity: 10301.5
Train accuracy: 0.0490849
Validation perplexity: 24243.5
Validation accuracy: 3.62823
Decaying learning rate to 0.0625

Train perplexity: 7927.77
Train accuracy: 0.062812
Validation perplexity: 7180.49
Validation accuracy: 5.31809
Decaying learning rate to 0.03125

Train perplexity: 4573.5
Train accuracy: 0.047421
Validation perplexity: 6545.51
Validation accuracy: 5.6163
Decaying learning rate to 0.015625

Train perplexity: 3995.7
Train accuracy: 0.0549085
Validation perplexity: 6316.25
Validation accuracy: 5.4175
Decaying learning rate to 0.0078125

Train perplexity: 3715.81
Train accuracy: 0.0540765
Validation perplexity: 6197.91
Validation accuracy: 5.86481
Decaying learning rate to 0.00390625

Train perplexity: 3672.46
Train accuracy: 0.0540765
Validation perplexity: 6144.18
Validation accuracy: 6.01392
Decaying learning rate to 0.00195312

Train perplexity: 3689.7
Train accuracy: 0.0528286
Validation perplexity: 6113.55
Validation accuracy: 6.31213
Decaying learning rate to 0.000976562
Exception ignored in: <function WeakValueDictionary.__init__.<locals>.remove at 0x118b19b70>
Traceback (most recent call last):
  File "/Users/Natsume/miniconda2/envs/dlnd-tf-lab/lib/python3.5/weakref.py", line 117, in remove
TypeError: 'NoneType' object is not callable
</code>```

Could you tell me how to fix it? Thanks!

答:
There are two solutions posted here

After trying these and error seems gone

Body:
I was trying to train OpenNMT example on mac with cpu with the following steps:

Env: python3.5, Pytorch 0.1.10.1

Step 1

preprocess data and shrink src and tgt to have only the first 100 sentences by inserting the following lines after line133 in preprocess.py

    shrink = True
    if shrink:
        src = src[0:100]
        tgt = tgt[0:100]

then, I ran

python preprocess.py -train_src data/src-train.txt -train_tgt data/tgt-train.txt -valid_src data/src-val.txt -valid_tgt data/tgt-val.txt -save_data data/demo

Step 2

then I train using python train.py -data data/demo.train.pt -save_model demo_model

Then it rans ok for a while before an error appeared:

(dlnd-tf-lab)  ->python train.py -data data/demo.train.pt -save_model demo_model
Namespace(batch_size=64, brnn=False, brnn_merge='concat', curriculum=False, data='data/demo.train.pt', dropout=0.3, epochs=13, extra_shuffle=False, gpus=[], input_feed=1, layers=2, learning_rate=1.0, learning_rate_decay=0.5, log_interval=50, max_generator_batches=32, max_grad_norm=5, optim='sgd', param_init=0.1, pre_word_vecs_dec=None, pre_word_vecs_enc=None, rnn_size=500, save_model='demo_model', start_decay_at=8, start_epoch=1, train_from='', train_from_state_dict='', word_vec_size=500)
Loading data from 'data/demo.train.pt'
 * vocabulary size. source = 24999; target = 35820
 * number of training sentences. 100
 * maximum batch size. 64
Building model...
* number of parameters: 58121320
NMTModel (
  (encoder): Encoder (
    (word_lut): Embedding(24999, 500, padding_idx=0)
    (rnn): LSTM(500, 500, num_layers=2, dropout=0.3)
  )
  (decoder): Decoder (
    (word_lut): Embedding(35820, 500, padding_idx=0)
    (rnn): StackedLSTM (
      (dropout): Dropout (p = 0.3)
      (layers): ModuleList (
        (0): LSTMCell(1000, 500)
        (1): LSTMCell(500, 500)
      )
    )
    (attn): GlobalAttention (
      (linear_in): Linear (500 -> 500)
      (sm): Softmax ()
      (linear_out): Linear (1000 -> 500)
      (tanh): Tanh ()
    )
    (dropout): Dropout (p = 0.3)
  )
  (generator): Sequential (
    (0): Linear (500 -> 35820)
    (1): LogSoftmax ()
  )
)

Train perplexity: 29508.9
Train accuracy: 0.0216306
Validation perplexity: 4.50917e+08
Validation accuracy: 3.57853

Train perplexity: 1.07012e+07
Train accuracy: 0.06198
Validation perplexity: 103639
Validation accuracy: 0.944334

Train perplexity: 458795
Train accuracy: 0.031198
Validation perplexity: 43578.2
Validation accuracy: 3.42942

Train perplexity: 144931
Train accuracy: 0.0432612
Validation perplexity: 78366.8
Validation accuracy: 2.33598
Decaying learning rate to 0.5

Train perplexity: 58696.8
Train accuracy: 0.0278702
Validation perplexity: 14045.8
Validation accuracy: 3.67793
Decaying learning rate to 0.25

Train perplexity: 10045.1
Train accuracy: 0.0457571
Validation perplexity: 26435.6
Validation accuracy: 4.87078
Decaying learning rate to 0.125

Train perplexity: 10301.5
Train accuracy: 0.0490849
Validation perplexity: 24243.5
Validation accuracy: 3.62823
Decaying learning rate to 0.0625

Train perplexity: 7927.77
Train accuracy: 0.062812
Validation perplexity: 7180.49
Validation accuracy: 5.31809
Decaying learning rate to 0.03125

Train perplexity: 4573.5
Train accuracy: 0.047421
Validation perplexity: 6545.51
Validation accuracy: 5.6163
Decaying learning rate to 0.015625

Train perplexity: 3995.7
Train accuracy: 0.0549085
Validation perplexity: 6316.25
Validation accuracy: 5.4175
Decaying learning rate to 0.0078125

Train perplexity: 3715.81
Train accuracy: 0.0540765
Validation perplexity: 6197.91
Validation accuracy: 5.86481
Decaying learning rate to 0.00390625

Train perplexity: 3672.46
Train accuracy: 0.0540765
Validation perplexity: 6144.18
Validation accuracy: 6.01392
Decaying learning rate to 0.00195312

Train perplexity: 3689.7
Train accuracy: 0.0528286
Validation perplexity: 6113.55
Validation accuracy: 6.31213
Decaying learning rate to 0.000976562
Exception ignored in: <function WeakValueDictionary.__init__.<locals>.remove at 0x118b19b70>
Traceback (most recent call last):
  File "/Users/Natsume/miniconda2/envs/dlnd-tf-lab/lib/python3.5/weakref.py", line 117, in remove
TypeError: 'NoneType' object is not callable

Could you tell me how to fix it? Thanks!


问:
Using reactive PHP in a blocking application
I'm currently working on a PHP application that will be using some websocket connections to talk to another service.

To talk to this websocket service, we are using Ratchet - which is a PHP library based on react PHP.

This piece of code needs to send and respond to a couple of requests, and after that, should return the information to the "main thread".

Example flow:

HTTP request -> controller -> Starts a service which opens a websocket client -> websocket client is talking to server -> once its done it should return the outcome to the controller code -> controller outputs to user

The issue I'm having is that I'm not familiar with Reactive PHP and am not sure how to handle this.

I've tried;

```<code>    $service = new WebsocketService();
    $startTimer = time();
    $service->getList(44);
    while($service->getResponse() == null) {
        usleep(500);
        if (time() > $startTimer + 10) {
            continue; //Timeout on 10 seconds
        }
    }
    var_dump($service->getResponse());
</code>```

The service code would set its "response" variable to something other than null once its done. This obviously fails, because the sleep method is blocking the thread. Also without, it seems like the while loop is blocking I/O and the reactive code fails.

A solution would be to open up a new thread and run the websocket code there, but I wouldn't be happy with that.

I feel like I need to implement some sort of "watcher" around the websocket process, but I'm not sure how to do that.

Our Websocket service client code looks like this;

```<code>private $response = null;

/**
 * @return null|object
 */
public function getResponse() {
    return $this->response;
}

public function getList($accountId) {
    $this->response = null;
    \Ratchet\Client\connect('ws://192.168.56.1:8080')->then(function(\Ratchet\Client\WebSocket $conn) use ($accountId) {
        $login = new \stdClass();
        $login->action = 'login';
        $conn->on('message', function($msg) use ($conn, $login, $accountId) {
            try {
                $response = json_decode($msg);
                if ($response->result_id == 100) {
                    //Succesfully logged in to websocket server

                    //Do our request now.
                    $message = new \stdClass();
                    $message->target = 'test';
                    $conn->send(json_encode($message));
                }

                if (isset($response->reply) && $response->reply == 'list') {
                    $this->response = $response; //This is the content I need returned in the controller
                    $conn->close(); //Dont need it anymore
                }

            } catch (\Exception $e) {
                echo 'response exception!';
                //Do nothing for now
            }
        });

        $conn->send(json_encode($login));
    }, function ($e) {
        echo "Could not connect: {$e->getMessage()}\n";
    });
}
</code>```

Running the code like this also does not work;

```<code>    $service = new WebsocketService();
    $service->getList(44);
    echo 'Test';
    var_dump($service->getResponse());
</code>```

because the "test" echo comes before I even get a response from the websocket server.

Please, enlighten me! I'm not sure what to search for.

答: Are you extending class with WsServer, This might be issue, if you are getting fatal errors. I am not sure whether you are getting fatal errors or warnings. Also i notice the public function onOpen() opens a connection. Please try referring this document http://socketo.me/api/class-Ratchet.WebSocket.WsServer.html might be useful.</p>

Body:
I'm currently working on a PHP application that will be using some websocket connections to talk to another service.

To talk to this websocket service, we are using Ratchet - which is a PHP library based on react PHP.

This piece of code needs to send and respond to a couple of requests, and after that, should return the information to the "main thread".

Example flow:

HTTP request -> controller -> Starts a service which opens a websocket client -> websocket client is talking to server -> once its done it should return the outcome to the controller code -> controller outputs to user

The issue I'm having is that I'm not familiar with Reactive PHP and am not sure how to handle this.

I've tried;

    $service = new WebsocketService();
    $startTimer = time();
    $service->getList(44);
    while($service->getResponse() == null) {
        usleep(500);
        if (time() > $startTimer + 10) {
            continue; //Timeout on 10 seconds
        }
    }
    var_dump($service->getResponse());

The service code would set its "response" variable to something other than null once its done. This obviously fails, because the sleep method is blocking the thread. Also without, it seems like the while loop is blocking I/O and the reactive code fails.

A solution would be to open up a new thread and run the websocket code there, but I wouldn't be happy with that.

I feel like I need to implement some sort of "watcher" around the websocket process, but I'm not sure how to do that.

Our Websocket service client code looks like this;

private $response = null;

/**
 * @return null|object
 */
public function getResponse() {
    return $this->response;
}

public function getList($accountId) {
    $this->response = null;
    \Ratchet\Client\connect('ws://192.168.56.1:8080')->then(function(\Ratchet\Client\WebSocket $conn) use ($accountId) {
        $login = new \stdClass();
        $login->action = 'login';
        $conn->on('message', function($msg) use ($conn, $login, $accountId) {
            try {
                $response = json_decode($msg);
                if ($response->result_id == 100) {
                    //Succesfully logged in to websocket server

                    //Do our request now.
                    $message = new \stdClass();
                    $message->target = 'test';
                    $conn->send(json_encode($message));
                }

                if (isset($response->reply) && $response->reply == 'list') {
                    $this->response = $response; //This is the content I need returned in the controller
                    $conn->close(); //Dont need it anymore
                }

            } catch (\Exception $e) {
                echo 'response exception!';
                //Do nothing for now
            }
        });

        $conn->send(json_encode($login));
    }, function ($e) {
        echo "Could not connect: {$e->getMessage()}\n";
    });
}

Running the code like this also does not work;

    $service = new WebsocketService();
    $service->getList(44);
    echo 'Test';
    var_dump($service->getResponse());

because the "test" echo comes before I even get a response from the websocket server.

Please, enlighten me! I'm not sure what to search for.


问:
How do I shift categorical scatter markers to left and right above xticks (multiple data sets per category)?
I have a simple pandas dataframe that I want to plot with matplotlib:

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

df = pd.read_excel('SAT_data.xlsx', index_col = 'State')

plt.figure()
plt.scatter(df['Year'], df['Reading'], c = 'blue', s = 25)
plt.scatter(df['Year'], df['Math'], c = 'orange', s = 25)
plt.scatter(df['Year'], df['Writing'], c = 'red', s = 25)
</code>```

Here is what my plot looks like:

I'd like to shift the blue data points a bit to the left, and the red ones a bit to the right, so each year on the x-axis has three mini-columns of scatter data above it instead of all three datasets overlapping.  I tried and failed to use the 'verts' argument properly.  Is there a better way to do this?

答:
Using an offset transform would allow to shift the scatter points by some amount in units of points instead of data units. The advantage is that they would then always sit tight against each other, independent of the figure size, zoom level etc.

```<code>import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)
import matplotlib.transforms as transforms

year = np.random.choice(np.arange(2006,2017), size=(300) )
values = np.random.rand(300, 3)

plt.figure()

offset = lambda p: transforms.ScaledTranslation(p/72.,0, plt.gcf().dpi_scale_trans)
trans = plt.gca().transData

sc1 = plt.scatter(year, values[:,0], c = 'blue', s = 25, transform=trans+offset(-5))
plt.scatter(year, values[:,1], c = 'orange', s = 25)
plt.scatter(year, values[:,2], c = 'red', s = 25, transform=trans+offset(5))

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

Broad figure:

Normal figure:

Zoom

Some explanation:

The problem is that we want to add an offset in points to some data in data coordinates. While data coordinates are automatically transformed to display coordinates using the transData (which we normally don't even see on the surface), adding some offset requires us to change the transform.

We do this by adding an offset.  While we could just add an offset in pixels (display coordinates), it is more convenient to add the offset in points and thereby using the same unit as the size of the scatter points is given in (their size is points squared actually).
So we want to know how many pixels are p points? This is found out by dividing p by the ppi (points per inch) to obtain inches, and then by multiplying by the dpi (dots per inch) to obtain the display pixel. This calculation in done in the ScaledTranslation.
While the dots per inch are in principle variable (and taken care of by the dpi_scale_trans transform), the points per inch are fixed. Matplotlib uses 72 ppi, which is kind of a typesetting standard.

Body:
I have a simple pandas dataframe that I want to plot with matplotlib:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_excel('SAT_data.xlsx', index_col = 'State')

plt.figure()
plt.scatter(df['Year'], df['Reading'], c = 'blue', s = 25)
plt.scatter(df['Year'], df['Math'], c = 'orange', s = 25)
plt.scatter(df['Year'], df['Writing'], c = 'red', s = 25)

Here is what my plot looks like:

I'd like to shift the blue data points a bit to the left, and the red ones a bit to the right, so each year on the x-axis has three mini-columns of scatter data above it instead of all three datasets overlapping.  I tried and failed to use the 'verts' argument properly.  Is there a better way to do this?

Body:
Using an offset transform would allow to shift the scatter points by some amount in units of points instead of data units. The advantage is that they would then always sit tight against each other, independent of the figure size, zoom level etc.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)
import matplotlib.transforms as transforms

year = np.random.choice(np.arange(2006,2017), size=(300) )
values = np.random.rand(300, 3)

plt.figure()

offset = lambda p: transforms.ScaledTranslation(p/72.,0, plt.gcf().dpi_scale_trans)
trans = plt.gca().transData

sc1 = plt.scatter(year, values[:,0], c = 'blue', s = 25, transform=trans+offset(-5))
plt.scatter(year, values[:,1], c = 'orange', s = 25)
plt.scatter(year, values[:,2], c = 'red', s = 25, transform=trans+offset(5))

plt.show()

Broad figure:

Normal figure:

Zoom

Some explanation:

The problem is that we want to add an offset in points to some data in data coordinates. While data coordinates are automatically transformed to display coordinates using the transData (which we normally don't even see on the surface), adding some offset requires us to change the transform.

We do this by adding an offset.  While we could just add an offset in pixels (display coordinates), it is more convenient to add the offset in points and thereby using the same unit as the size of the scatter points is given in (their size is points squared actually).
So we want to know how many pixels are p points? This is found out by dividing p by the ppi (points per inch) to obtain inches, and then by multiplying by the dpi (dots per inch) to obtain the display pixel. This calculation in done in the ScaledTranslation.
While the dots per inch are in principle variable (and taken care of by the dpi_scale_trans transform), the points per inch are fixed. Matplotlib uses 72 ppi, which is kind of a typesetting standard.


问:
Serial versus SPI
What is the difference between SPI and serial? In reading an article talking about inter-processor communications, it states that serial interfaces are being replaced with SPI for better/faster comms? What exactly is the difference?</p>

答:
The previous answer is somewhat misleading.

SPI and UART both transfer binary data as bytes and/or words, depending on the hardware. As explained above, one is synchronous and one is asynchronous. Both require an extra data line to be bidirectional. ASCII is an agreed upon interpretation of the binary data and is not actually a factor in either.

Title: Serial versus SPI


答:
You can use find to generate your list of files, and xargs to run sed over the result:

```<code>find . -type f -print | xargs sed -i 's/\.delay.*/.delay./'
</code>```

find will generate a list of files contained in your current directory (., although you can of course pass a different directory), xargs will read that list and then run sed with the list of files as an argument.

Instead of find, which here generates a list of all files, you could use something like grep to generate a list of files that contain a specific term.  E.g.:

```<code>grep -rl '\.delay' | xargs sed -i ...
</code>```

Title: How to replace string in files recursively via sed or awk?

Body:
You can use find to generate your list of files, and xargs to run sed over the result:

find . -type f -print | xargs sed -i 's/\.delay.*/.delay./'

find will generate a list of files contained in your current directory (., although you can of course pass a different directory), xargs will read that list and then run sed with the list of files as an argument.

Instead of find, which here generates a list of all files, you could use something like grep to generate a list of files that contain a specific term.  E.g.:

grep -rl '\.delay' | xargs sed -i ...


问:
How to save Date Time without the time?
How would i save the date time, with no time or preferably with a time stamp of 12:00, no matter what the time is at that moment?

I dont want to use .ToString("dd/MM/yyyy");, because it will open up a whole lot of new  possible errors.

答:
This will do the trick with a preference to ts.Date</p>

```<code>var ts = DateTime.Now;
var dateAtMidnight = ts.Date;
var dateAtNoon = ts.Date.AddHours(12);
</code>```

Title: How to save Date Time without the time?

Body:
This will do the trick with a preference to ts.Date

var ts = DateTime.Now;
var dateAtMidnight = ts.Date;
var dateAtNoon = ts.Date.AddHours(12);


问:
How to make a copy of hibernate collection with cascade="all,delete-orphan"
I am trying to make a copy of a hibernate entity A like this:

```<code>A a = (A) session.get(A.class, id);
session.evict(a);
a.setId(null);
session.save(a);
</code>```

This however does not work and i get the following expetion:

```<code>org.hibernate.HibernateException: Don't change the reference to a collection with cascade="all-delete-orphan": com.test.A.B
</code>```

Its safe to assume this error happens because of i have a collection of B entity defined in entity A:

```<code><list name="B"  table="B" lazy="false" cascade="all,delete-orphan">
    <key column="A_ID" not-null="true"/>
    <index column="X"/>
    <one-to-many class="com.test.B"/>
</list>
</code>```

How is it possible to make a copy of entity A, including its collection of entitys B without hibernate being unhappy about it?

答:
There is no automatic way to copy objects like that. In general, the copied object could be associated with other objects which are further associated with other objects, etc, so you could end up copying a large portion of the database. Any tool you use for copying needs to be aware where in the object graph to stop copying, what not to copy (in terms of Hibernate entities those are ids, version columns and similar), and so on.

You can however utilize frameworks like Dozer to avoid most of boilerplate code you would need to write manually.

Regarding collection reassignment issue, you cannot have the same collection of B instances being assigned to two different As, as it would logically be a many-to-many association then. It is also something you would need to take care of manually, as it is specific to your business use case.

Also, make sure you don't reuse the same collection proxies from one entity instance in others, as Hibernate ties them to their original parents internally - always create a new collection in new instances (which may or may not contain the same elements).

Body:
I am trying to make a copy of a hibernate entity A like this:

A a = (A) session.get(A.class, id);
session.evict(a);
a.setId(null);
session.save(a);

This however does not work and i get the following expetion:

org.hibernate.HibernateException: Don't change the reference to a collection with cascade="all-delete-orphan": com.test.A.B

Its safe to assume this error happens because of i have a collection of B entity defined in entity A:

<list name="B"  table="B" lazy="false" cascade="all,delete-orphan">
    <key column="A_ID" not-null="true"/>
    <index column="X"/>
    <one-to-many class="com.test.B"/>
</list>

How is it possible to make a copy of entity A, including its collection of entitys B without hibernate being unhappy about it?


问:
Given a non-empty list of strings each of which represents a date, return the two dates in it that are closest to each other
The date in each string is expressed like "30/3/17@11:30 pm"; i.e. one or
    two digits for the day followed by a slash followed by one or two digits
    for the month followed by a slash followed by 2 or 4 digits for the year.
    The time has one or two digits for the hour followed by a colon followed
    by exactly two digits for the minute followed by one space followed by
    am or pm in upper, lower, or mixed case. The date and time are delimited
    by the @ character.

```<code>The return is a chronologically sorted list of two date objects. If any of
the incoming strings is invalid, return null. And if the list has more than
one pair of dates that are equally close, return the pair that occurs first.
</code>```

Example: if the given list is:
    [30/3/17@11:30 pm, 31/12/2016@11:10 PM, 1/4/2017@6:00 am, 8/8/2016@12:00 aM, 1/1/2017@5:45 AM, 31/3/17@4:30 aM]
    then the return would be the list:
    [Thu Mar 30 23:30:00 EDT 2017, Fri Mar 31 04:30:00 EDT 2017]

答:
I suppose there is no direct java component to address your problem.
Its better to convert your Date Times to java.util.Date and Write a logic from there rather than dealing with strings.

java.util.Date class has following methods which you can use to build a logic.

```<code>boolean after(Date when)
</code>```

Checks if the invoking Date object is later than the specified date.

```<code>boolean before(Date when)
</code>```

Checks if the invoking Date object is earlier than the specified date.

```<code>int compareTo(Date date)
</code>```

Compares the invoking Date object with the specified date and returns 0 if the two values are equal, negative value if the invoking object is earlier than the specified date and positive value if the invoking object is later than the specified date.

```<code> boolean equals(Object date)
</code>```

Check if the invoking Date object and the specified date are equal.

Refer here more details

Body:
The date in each string is expressed like "30/3/17@11:30 pm"; i.e. one or
    two digits for the day followed by a slash followed by one or two digits
    for the month followed by a slash followed by 2 or 4 digits for the year.
    The time has one or two digits for the hour followed by a colon followed
    by exactly two digits for the minute followed by one space followed by
    am or pm in upper, lower, or mixed case. The date and time are delimited
    by the @ character.

The return is a chronologically sorted list of two date objects. If any of
the incoming strings is invalid, return null. And if the list has more than
one pair of dates that are equally close, return the pair that occurs first.

Example: if the given list is:
    [30/3/17@11:30 pm, 31/12/2016@11:10 PM, 1/4/2017@6:00 am, 8/8/2016@12:00 aM, 1/1/2017@5:45 AM, 31/3/17@4:30 aM]
    then the return would be the list:
    [Thu Mar 30 23:30:00 EDT 2017, Fri Mar 31 04:30:00 EDT 2017]

Body:
I suppose there is no direct java component to address your problem.
Its better to convert your Date Times to java.util.Date and Write a logic from there rather than dealing with strings.

java.util.Date class has following methods which you can use to build a logic.

boolean after(Date when)

Checks if the invoking Date object is later than the specified date.

boolean before(Date when)

Checks if the invoking Date object is earlier than the specified date.

int compareTo(Date date)

Compares the invoking Date object with the specified date and returns 0 if the two values are equal, negative value if the invoking object is earlier than the specified date and positive value if the invoking object is later than the specified date.

 boolean equals(Object date)

Check if the invoking Date object and the specified date are equal.

Refer here more details