问:
How to return multiple values from a function in Kotlin like we do in Swift?
How to return 3 separate data values of the same type (Int) from a function in Kotlin?

I'm attempting to return the time of day, I need to return the Hour, Minute and Second as separate integers, but all in one go from the same function, is this possible?

In swift we do it like following,

```<code>func getTime() -> (Int, Int, Int) {
    ...
    return ( hour, minute, second)
}
</code>```

can we achieve this in Kotlin?

P.S: I know I can use Array or Hashmap for this but I want to know if there exists something in Kotlin like it is in Swift.

答:
It seems that you are aware of the obvious answer of creating a specific class to handle time. So I guess you are trying to avoid the small hassle of creating a class, or accessing each element of an array, etc. and are looking for the shortest solution in terms of extra code. I would suggest:

```<code>fun getTime(): Triple<Int, Int, Int> {
    ...
    return Triple( hour, minute, second)
}
</code>```

and use it with deconstruction:

```<code>var (a, b, c) = getTime()
</code>```

If you need 4 or 5 return values (you cannot deconstruct more than 5), go with Array:

```<code>fun getTime(): Array<Int> {
    ...
    return arrayOf( hour, minute, second, milisec)
}
</code>```

and

```<code>var (a, b, c, d) = getTime()
</code>```

P.S.: you can use less variables than there are values when deconstructing, like var (a, b) = getTime() but you cannot use more or you'll get an ArrayIndexOutOfBoundsException

Body:
How to return 3 separate data values of the same type (Int) from a function in Kotlin?

I'm attempting to return the time of day, I need to return the Hour, Minute and Second as separate integers, but all in one go from the same function, is this possible?

In swift we do it like following,

func getTime() -> (Int, Int, Int) {
    ...
    return ( hour, minute, second)
}

can we achieve this in Kotlin?

P.S: I know I can use Array or Hashmap for this but I want to know if there exists something in Kotlin like it is in Swift.

Body:
It seems that you are aware of the obvious answer of creating a specific class to handle time. So I guess you are trying to avoid the small hassle of creating a class, or accessing each element of an array, etc. and are looking for the shortest solution in terms of extra code. I would suggest:

fun getTime(): Triple<Int, Int, Int> {
    ...
    return Triple( hour, minute, second)
}

and use it with deconstruction:

var (a, b, c) = getTime()

If you need 4 or 5 return values (you cannot deconstruct more than 5), go with Array:

fun getTime(): Array<Int> {
    ...
    return arrayOf( hour, minute, second, milisec)
}

and

var (a, b, c, d) = getTime()

P.S.: you can use less variables than there are values when deconstructing, like var (a, b) = getTime() but you cannot use more or you'll get an ArrayIndexOutOfBoundsException


来源: stackexchange

问:
Why isn't 'gets' working in my Ruby script when I run from TextMate?
When running the following ruby script:

puts gets.inspect

On the terminal I am prompted for input and then the inspect output is shown, but if I run the same script from inside TextMate using the CMD+R shortcut then it just outputs nil as if there is no gets method.

Why is this? From what I've read TextMate is supposed to show an input dialog when input from STDIN is requested by the script, but that isn't happening in this case.

答:
See this blog entry; presumably you're on Snow Leopard?

From the comments, some users say that this file has worked for them on Snow Leopard. Per @dmarkow's answer, copy this file to:

/Applications/TextMate.app/Contents/SharedSupport/Support/lib/

You may want to keep a copy of the file around as updates to TextMate may replace it.

ContentLicense: CC BY-SA 2.5


问:
How do I cover the entire page with 3 images?
I want to cover my entire page with 3 images but I can't seem to figure out how make them cover the bottom of the screen while still being responsive.

This is how I want it to look: https://imgur.com/a/HN18b (while still being responsive)

```<code><style>

html, body {
  margin: 0;
  padding: 0;
}

img {
  position: relative;
  float: left;
  width: calc(100%/3);
  height: 100%;
}

</style>

<body>

<div class="container">
  <div id="box">
    <img src="1.jpg" />
    <img src="2.jpg" />
    <img src="3.jpg" />
  </div>
</div>

</body>
</code>```

Fiddle: https://jsfiddle.net/zkcjg51f/

答:
If you'd like full height, responsive images, use the images as background-images and then size the container as you need.

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

.container {
  height: 100%;
}

.img-div {
  position: relative;
  float: left;
  width: calc(100%/3);
  height: 100%;
  background-size: cover;
  background-position: center;
}

.img-frodo {
  background-image: url('https://i.imgur.com/9bYOn81.jpg');
}

.img-hp {
  background-image: url('https://i.imgur.com/pwG5Bch.png');
}

.img-avatar {
  background-image: url('https://i.imgur.com/KZ96Xsx.png');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div class="img-div img-frodo"></div>
    <div class="img-div img-hp"></div>
    <div class="img-div img-avatar"></div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to cover my entire page with 3 images but I can't seem to figure out how make them cover the bottom of the screen while still being responsive.

This is how I want it to look: https://imgur.com/a/HN18b (while still being responsive)

Fiddle: https://jsfiddle.net/zkcjg51f/

Body:
If you'd like full height, responsive images, use the images as background-images and then size the container as you need.

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

.container {
  height: 100%;
}

.img-div {
  position: relative;
  float: left;
  width: calc(100%/3);
  height: 100%;
  background-size: cover;
  background-position: center;
}

.img-frodo {
  background-image: url('https://i.imgur.com/9bYOn81.jpg');
}

.img-hp {
  background-image: url('https://i.imgur.com/pwG5Bch.png');
}

.img-avatar {
  background-image: url('https://i.imgur.com/KZ96Xsx.png');
}

<div class="container">
    <div class="img-div img-frodo"></div>
    <div class="img-div img-hp"></div>
    <div class="img-div img-avatar"></div>
</div>


问:
How to monitor changes to a particular website CSS?
I wish to monitor the CSS of a few websites (these websites aren't my own) for changes and receive a notification of some sort when they do. If you could please share any experience you've had with this to point me in the right direction for how to code it I'd appreciate it greatly.

I'd like this script/app to notify a Slack group on change, which I assume will require a webhook.

Not asking for code, just any advice about particular APIs and other tools that may be of benefit.

答: I would suggest using Github in your workflow. That gives you a good idea of changes and ways to revert back to older versions.</p>


问:
passing a json data object from php to javascript
I has probaly been asked a lot of times and i ve read lots of threads about it, but simple cant figure it out how to pass a json data pbject from php to java script.

I am am trying to get two single-dimensional json data object arrays(?) from a database and merge them into a two dinemsional json data object array which is then further passed to sigma.js for further processing.

Reading data from database:

```<code><?php
require 'sort.php';
$db = db();
$rawNodes = $db->select('node', '*', ['ico_id' => $_GET['id']]);
$rawEdges = $db->select("edge", "*", ["ico_id" => $_GET['id']]);

$nodes = array();
foreach ($rawNodes as $node) {
    array_push($out, $node);
}

$edges = array();
foreach ($rawEdges as $edge) {
    array_push($out, $edge);
}

?>
</code>```

now accessing it in Java Script:

```<code><html>
    <head>
        <title>Dynamic Transaction Visualization </title>
        <style type="text/css">
            #container {
                max-width: 1200px;
                height: 800px;
                margin: auto;
            }
        </style>
        <script src="build/sigma.min.js"></script>
        <script src="build/plugins/sigma.parsers.json.min.js"></script>
        <script src="build/plugins/sigma.renderers.edgeLabels.min.js"></script>
        <script>
            function getData () {
                var gnodes = <?php echo json_encode($nodes); ?>;
                var gedges = <?php echo json_encode($edges); ?>;

                alert(gnodes[0].adress); // <- Doesnt work? Why?

                var g = {nodes: [], edges: []}; //<- i think this sytanx is correct for making a 2 dim json data object array- is it?

                var xpos = 0;
                var ypos = 0;

                var n;

                for (n in gnodes) { //<- Does not iterate through any Elements
                    alert(gnodes[n].adress); //<- Doest work either? Why?
                    xpos = n.block_number - 4400000;
                    ypos += 100;
                    if (ypos > 10000) { ypos = 0 }
                    g.nodes.push(
                        {
                            "id": n.adress,
                            "label": n.adress,
                            "size": 1, //n.size,
                            "x": xpos,
                            "y": ypos
                        }
                    )
                }

                var edgecount = 0;

                var m;
                for (m in gedges) {
                    g.edges.push(
                        {
                            "id": edgecount++,
                            "source": m.node_adress1,
                            "target": m.node_adress2,
                            "label": m.erc20_value,
                            "type": "arrow"
                        }
                    )
                }
                //g.nodes = gnodes; geht nicht benennung nicht passend
                //g.edges = gedges;

                return g;
            }

            function dispGraph() {
                var gdata = getData();
                s = new sigma({
                    graph: gdata,
                    container: 'container',
                    renderer: {
                        container: "container",
                        type: "canvas"
                    },
                    settings: {
                        edgeLabelSize: 'fixed',
                        nodeLabelSize: 'fixed',
                        defaultNodeColor: '#ec5148',
                        maxNodeSize: 15,
                        minNodeSize: 5,
                        minEdgeSize: 4,
                        maxEdgeSize: 4,
                        minArrowSize: 4,
                        //edgeLabelSize: 'fixed',
                        // {string} The opposite power ratio between the font size of the label and
                        // the edge size:
                        // Math.pow(size, -1 / edgeLabelSizePowRatio) * size * defaultEdgeLabelSize
                        edgeLabelSizePowRatio: 1,
                        // {number} The minimum size an edge must have to see its label displayed.
                        edgeLabelThreshold: 1,
                    }
                });
            }
        </script>
    </head>
    <body>
    <div id="container"></div>
        <script>dispGraph()</script>
    </body>
</html>
</code>```

答:
I think it is easy. In the html file (with .php extension):</p>

```<code><?php $json = json_encode($data); ?>
<script>
    var json = <?=$json?>;
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I has probaly been asked a lot of times and i ve read lots of threads about it, but simple cant figure it out how to pass a json data pbject from php to java script.

I am am trying to get two single-dimensional json data object arrays(?) from a database and merge them into a two dinemsional json data object array which is then further passed to sigma.js for further processing.

Reading data from database:

<?php
require 'sort.php';
$db = db();
$rawNodes = $db->select('node', '*', ['ico_id' => $_GET['id']]);
$rawEdges = $db->select("edge", "*", ["ico_id" => $_GET['id']]);

$nodes = array();
foreach ($rawNodes as $node) {
    array_push($out, $node);
}

$edges = array();
foreach ($rawEdges as $edge) {
    array_push($out, $edge);
}

?>

now accessing it in Java Script:

        <title>Dynamic Transaction Visualization </title>

Body:
I think it is easy. In the html file (with .php extension):

<?php $json = json_encode($data); ?>
<script>
    var json = <?=$json?>;
</script>


问:
Vue one or multiple instances?
I'm quite new to Vue (in combination with Laravel). I'm not sure what's the best vue (file) structure.

For example: I have a vue chat application and a sidebar that slides out. At this moment I have made one vue instance (at the #app element). All the code is now in this one vue instance. How should I seperate the data and code in the instance for my chatapp and sidebar?

```<code> Vue.component('chat-message', require('./components/ChatMessage.vue'));
 Vue.component('chat-log', require('./components/ChatLog.vue'));
 Vue.component('chat-composer', require('./components/ChatComposer.vue'));

    new Vue({
        el: "#app",
        data: {

**//Data for the chatapp**

            messages : [],

**//Data for the sidebar**

            showSidebar: false
        },

**//Code for the chatapp**

        methods:{
            addMessage(message) {
                this.messages.push(message);
                axios.post('messages', message)
            }
        },
        created() {
            axios.get('messages').then(response => {
                this.messages = response.data;
        });

            Echo.join('chatroom')
                .listen('MessagePosted', (e) =>{
                this.messages.push({
                message: e.message.message,
                user: e.user,
            })
        });
        }
    });
</code>```

I prefere to seperate this code to two seperate files (especially the methods and other code for the chatapp, e.g. chatroom.vue and sidebar.vue) and only load a clean vue instance e.g:

```<code>//Import components...
...
...
    new Vue({
        el: "#app"
    });
</code>```

. Can I put this code into components? And how would this look like?

Thanks.

答:
You are right, you can and should separate it into two different components.

chatroom.vue

```<code>import ChatMessage from './components/ChatMessage.vue';
import ChatLog from './components/ChatLog.vue';
import ChatComposer from './components/ChatComposer.vue';

export default {
    components: {
        ChatMessage,
        ChatLog,
        ChatComposer,
    },
    data: {
        // Data for the chatapp
        messages : [],
    },
    // Code for the chatapp
    methods:{
        addMessage(message) {}
    },
    created() {}
}
</code>```

sidebar.vue

```<code>export default {
    data: {
        // Data for the sidebar
        showSidebar: false,
    },
    // Code for the sidebar
}
</code>```

app.js

```<code>import ChatRoom from './chatroom.vue';
import SideBar from './sidebar.vue';

new Vue({
    el: "#app",
    components: {
        ChatRoom,
        SideBar,
    },
});
</code>```

Title: Vue one or multiple instances?

Body:
I'm quite new to Vue (in combination with Laravel). I'm not sure what's the best vue (file) structure.

For example: I have a vue chat application and a sidebar that slides out. At this moment I have made one vue instance (at the #app element). All the code is now in this one vue instance. How should I seperate the data and code in the instance for my chatapp and sidebar?

 Vue.component('chat-message', require('./components/ChatMessage.vue'));
 Vue.component('chat-log', require('./components/ChatLog.vue'));
 Vue.component('chat-composer', require('./components/ChatComposer.vue'));

    new Vue({
        el: "#app",
        data: {

**//Data for the chatapp**

            messages : [],

**//Data for the sidebar**

            showSidebar: false
        },

**//Code for the chatapp**

        methods:{
            addMessage(message) {
                this.messages.push(message);
                axios.post('messages', message)
            }
        },
        created() {
            axios.get('messages').then(response => {
                this.messages = response.data;
        });

            Echo.join('chatroom')
                .listen('MessagePosted', (e) =>{
                this.messages.push({
                message: e.message.message,
                user: e.user,
            })
        });
        }
    });

I prefere to seperate this code to two seperate files (especially the methods and other code for the chatapp, e.g. chatroom.vue and sidebar.vue) and only load a clean vue instance e.g:

//Import components...
...
...
    new Vue({
        el: "#app"
    });

. Can I put this code into components? And how would this look like?

Thanks.

Body:
You are right, you can and should separate it into two different components.

chatroom.vue

import ChatMessage from './components/ChatMessage.vue';
import ChatLog from './components/ChatLog.vue';
import ChatComposer from './components/ChatComposer.vue';

export default {
    components: {
        ChatMessage,
        ChatLog,
        ChatComposer,
    },
    data: {
        // Data for the chatapp
        messages : [],
    },
    // Code for the chatapp
    methods:{
        addMessage(message) {}
    },
    created() {}
}

sidebar.vue

export default {
    data: {
        // Data for the sidebar
        showSidebar: false,
    },
    // Code for the sidebar
}

app.js

import ChatRoom from './chatroom.vue';
import SideBar from './sidebar.vue';

new Vue({
    el: "#app",
    components: {
        ChatRoom,
        SideBar,
    },
});


问:
Excel hyperlink to web page location with id or named anchor
In Excel, I can create a hyperlink to a web page. However, if the URL contains a # character, Excel always converts the hash sign to space-hyphen-space so the link no longer works. The URL http://www.example.com/page#location becomes http://www.example.com/page%20-%20location

I have tried three ways

manually, right-click a cell, click "hyperlink" and type the URL in the address box

programatically, providing the full URL:

Worksheets(1).Hyperlinks.Add Address:="http://www.example.com/page#location"

programatically, giving the location as a "subaddress":

Worksheets(1).Hyperlinks.Add Address:="http://www.example.com/page", SubAddress:="location"

All three give the same problem. Is it possible to create a link to a specific location (id or named anchor) not just to a web page? I would be grateful for any help.

Note: the code examples are incomplete; for clarity, I have omitted the parameters Anchor and TextToDisplay.

Excel version: 2010 (14.0.6126.5003) SP1

答:
This is not a browser problem. MS Office applications are mangling URLs with a # being replaced with ' - ' (the %20 is a space).

This annoying problem is admitted to exist by Microsoft themselves.  To quote from that page:

These problems may occur when the name of file to which you create the hyperlink contains a pound sign (#).

NOTE: The pound sign is a valid character to use in a file name but is not accepted in hyperlinks in Office documents.

Their only workarounds are to remove the offending # or to copy and paste the URL from the document ... utterly ridiculous considering the reason most people would be using the # is to make it easier for users to find content.

Request that Microsoft improve this behavior by voting here: https://office365.uservoice.com/forums/264636-general/suggestions/32273917-stop-mangling-urls-containing-a-so-we-can-link-t


问:
SET/RESET command in ALTER DATABASE is not supported
Encountered this issue when trying to modify the search_path to my new Redshift db.

Presently, I've migrated the contents of my MySQL db into a redshift cluster via AWS' Data Migration Service. The data was imported into a schema lets call my_schema. When I try to execute queries against the cluster it requires me to prefix table names with the schema name

i.e.

select * from my_schema.my_table

I wanted to change the setup so that I can reference the table directly without needing the prefix. After a bit of looking around I found out that this was possible by modifying the search_path attribute.

First I tried doing this by running

set search_path = "$user", my_schema;

This appeared to work but then I realized that this was simply setting my_schema as the default schema in the context of the current session, I wanted it set on a database level. I found several sources saying that the way to do this was to use the alter command like so...

alter database my_db set search_path = "$user", public, my_schema

However, running this command results in the following error which somehow shows up in 0 google results:

SET/RESET commmand in ALTER DATABASE is not supported

I'm pretty baffled by how the above error hasn't ever had a post made about it but I'm also pretty interested in figuring out how to resolve my initial issue of setting a global default schema for my redshift cluster.

答:
ALTER DATABASE SET is not supported in Redshift. However you can SET/RESET configuration parameters at USER level using the ALTER USER SET SEARCH_PATH TO <SCHEMA1>,<SCHMEA2>;

Please check: http://docs.aws.amazon.com/redshift/latest/dg/r_ALTER_USER.html
http://docs.aws.amazon.com/redshift/latest/dg/r_search_path.html

When you set the search_path to <SCHEMA1>,<SCHMEA2> in db1 for a user it is not for just current session, it will be set for all future sessions.


问:
Scenario on Selecting Records
I have a scenario to fetch few records out of multiple records in database.
Source records below pertains to One account holder.

```<code>PrimaryOrSecondary  Duplicate_Account_ID    Account_ID  START_DATE  END_DATE
------------------  --------------------  ------------  ----------  --------
Primary     1000    1000    26/05/2017    NULL

Primary     1000    1000    10/03/2014    25/05/2017

Secondary   2000    1000    26/05/2017    NULL

Secondary   3000    1000    10/03/2014    25/05/2017
</code>```

Out of these 4 records I have to apply below rules to get only one target record.

If Duplicate_Account_ID=Account_ID(then it is PRIMARY record) and if its END_DATE IS NULL then populate that record in target and look no further.

If END_DATE IS NULL in Step 1 , then go to Secondary record where Duplicate_Account_ID<>Account_ID and see if any record has NULL END_DATE. If found then populate that record in target.

If no records found in Step 2, then go back to Primary record and get the record that has the Maximum START_DATE and populate that record in target.

Ultimately I need one record in target table from these 4 records in source.

Any help pls.

答:
You haven't tagged your DBMS but here is the SQL Server solution</p>

```<code>INSERT  INTO yourothertable
SELECT  TOP 1
        PrimaryOrSecondary,
        Duplicate_Account_ID,
        Account_ID,
        START_DATE,
        END_DATE
FROM    (
            SELECT  *,
                    MAX(START_DATE) OVER (PARTITION BY PrimaryOrSecondary) AS MaxDate
            FROM    yourtable
        ) a
WHERE   (Duplicate_Account_ID = Account_ID AND END_DATE IS NULL) OR
        (PrimaryOrSecondary = 'Secondary' AND Duplicate_Account_ID<>Account_ID AND END_DATE IS NULL) OR
        (PrimaryOrSecondary = 'Primary' AND MaxDate = START_DATE)
ORDER BY
        CASE
            WHEN Duplicate_Account_ID = Account_ID AND END_DATE IS NULL
            THEN 1
            WHEN PrimaryOrSecondary = 'Secondary' AND Duplicate_Account_ID<>Account_ID AND END_DATE IS NULL
            THEN 2
            WHEN PrimaryOrSecondary = 'Primary' AND MaxDate = START_DATE
            THEN 3
        END
</code>```

Title: Scenario on Selecting Records

Body:
I have a scenario to fetch few records out of multiple records in database.
Source records below pertains to One account holder.

PrimaryOrSecondary  Duplicate_Account_ID    Account_ID  START_DATE  END_DATE
------------------  --------------------  ------------  ----------  --------
Primary     1000    1000    26/05/2017    NULL

Primary     1000    1000    10/03/2014    25/05/2017

Secondary   2000    1000    26/05/2017    NULL

Secondary   3000    1000    10/03/2014    25/05/2017

Out of these 4 records I have to apply below rules to get only one target record.

If Duplicate_Account_ID=Account_ID(then it is PRIMARY record) and if its END_DATE IS NULL then populate that record in target and look no further.

If END_DATE IS NULL in Step 1 , then go to Secondary record where Duplicate_Account_ID<>Account_ID and see if any record has NULL END_DATE. If found then populate that record in target.

If no records found in Step 2, then go back to Primary record and get the record that has the Maximum START_DATE and populate that record in target.

Ultimately I need one record in target table from these 4 records in source.

Any help pls.

Body:
You haven't tagged your DBMS but here is the SQL Server solution

INSERT  INTO yourothertable
SELECT  TOP 1
        PrimaryOrSecondary,
        Duplicate_Account_ID,
        Account_ID,
        START_DATE,
        END_DATE
FROM    (
            SELECT  *,
                    MAX(START_DATE) OVER (PARTITION BY PrimaryOrSecondary) AS MaxDate
            FROM    yourtable
        ) a
WHERE   (Duplicate_Account_ID = Account_ID AND END_DATE IS NULL) OR
        (PrimaryOrSecondary = 'Secondary' AND Duplicate_Account_ID<>Account_ID AND END_DATE IS NULL) OR
        (PrimaryOrSecondary = 'Primary' AND MaxDate = START_DATE)
ORDER BY
        CASE
            WHEN Duplicate_Account_ID = Account_ID AND END_DATE IS NULL
            THEN 1
            WHEN PrimaryOrSecondary = 'Secondary' AND Duplicate_Account_ID<>Account_ID AND END_DATE IS NULL
            THEN 2
            WHEN PrimaryOrSecondary = 'Primary' AND MaxDate = START_DATE
            THEN 3
        END


问:
Parsing Json; Write data to the TreeView branch
I have a large json file, in which the data is arranged like this:

id - item id

parent - parent id

name - name

...
{
id: "2859",
parent: "5853",
name: "Moscow"
},
...

I need to throw it in TreeView.
Help please = (

Now I do it this way:

```<code>RootObject data = JsonConvert.DeserializeObject<RootObject>(content);

        foreach (var _data in data.data)
        {
            bool find = false;

            foreach(TreeNode n in Regions.Nodes)
            {
                if (n.Name == _data.parent)
                {
                    bool find2 = false;
                    n.Nodes.Add(_data.id, _data.name);
                    find = true;
                }
            }

            if (find != true)
            {
                Regions.Nodes.Add(_data.id, _data.name);
            }

        }
</code>```

Json File

答:
Your code does not work correctly for two reasons:

You assume that if an item has a parent, that parent will come first in the data, and therefore it will have been added to the tree when you try to find it.  However, this does not hold true.  If you follow the chain of ids in the data, there are cases for which the parent item appears after the child.

You do not handle the case where an item's parent is not at the root level.
If an item's parent was previously added to the tree as a child of a root level node, then it will not be found in the root node list, so you will end up adding the item to the root instead of to the correct parent.

What you need to do is process the data in two passes using a dictionary lookup:

First, create all the individual TreeNodes from the data and add them to a dictionary, keyed by ID.

Then, iterate over the data a second time, and for each item, look up the corresponding node and its parent node in the dictionary using their respective IDs.  If the parent is found, add the node to the parent's node list, otherwise add it to the root node list.

Here is what it would look like in code:

```<code>void PopulateTreeViewFromJson(TreeView treeView, string json)
{
    RootObject root = JsonConvert.DeserializeObject<RootObject>(json);

    var dict = root.data.ToDictionary(n => n.id,
        n => new TreeNode(n.name.Trim()) { Name = n.id });

    foreach (var item in root.data)
    {
        TreeNode node = dict[item.id];
        TreeNode parentNode;
        if (dict.TryGetValue(item.parent, out parentNode))
        {
            parentNode.Nodes.Add(node);
        }
        else
        {
            treeView.Nodes.Add(node);
        }
    }
}
</code>```

Body:
I have a large json file, in which the data is arranged like this:

id - item id

parent - parent id

name - name

...
{
id: "2859",
parent: "5853",
name: "Moscow"
},
...

I need to throw it in TreeView.
Help please = (

Now I do it this way:

RootObject data = JsonConvert.DeserializeObject<RootObject>(content);

        foreach (var _data in data.data)
        {
            bool find = false;

            foreach(TreeNode n in Regions.Nodes)
            {
                if (n.Name == _data.parent)
                {
                    bool find2 = false;
                    n.Nodes.Add(_data.id, _data.name);
                    find = true;
                }
            }

            if (find != true)
            {
                Regions.Nodes.Add(_data.id, _data.name);
            }

        }

Json File

Body:
Your code does not work correctly for two reasons:

You assume that if an item has a parent, that parent will come first in the data, and therefore it will have been added to the tree when you try to find it.  However, this does not hold true.  If you follow the chain of ids in the data, there are cases for which the parent item appears after the child.

You do not handle the case where an item's parent is not at the root level.
If an item's parent was previously added to the tree as a child of a root level node, then it will not be found in the root node list, so you will end up adding the item to the root instead of to the correct parent.

What you need to do is process the data in two passes using a dictionary lookup:

First, create all the individual TreeNodes from the data and add them to a dictionary, keyed by ID.

Then, iterate over the data a second time, and for each item, look up the corresponding node and its parent node in the dictionary using their respective IDs.  If the parent is found, add the node to the parent's node list, otherwise add it to the root node list.

Here is what it would look like in code:

void PopulateTreeViewFromJson(TreeView treeView, string json)
{
    RootObject root = JsonConvert.DeserializeObject<RootObject>(json);

    var dict = root.data.ToDictionary(n => n.id,
        n => new TreeNode(n.name.Trim()) { Name = n.id });

    foreach (var item in root.data)
    {
        TreeNode node = dict[item.id];
        TreeNode parentNode;
        if (dict.TryGetValue(item.parent, out parentNode))
        {
            parentNode.Nodes.Add(node);
        }
        else
        {
            treeView.Nodes.Add(node);
        }
    }
}


答:
One possible solution:

Crawl website for .css files, save change dates and/or filesize.

After each crawl compare information and if changes detected use slack API to notify. I haven't worked with slack that, for this part of the solution maybe someone else can give advice.

Title: How to monitor changes to a particular website CSS?

Body:
I wish to monitor the CSS of a few websites (these websites aren't my own) for changes and receive a notification of some sort when they do. If you could please share any experience you've had with this to point me in the right direction for how to code it I'd appreciate it greatly.

I'd like this script/app to notify a Slack group on change, which I assume will require a webhook.

Not asking for code, just any advice about particular APIs and other tools that may be of benefit.


问:
How do I sort a Laravel Collection by multiple properties with both asc and desc?
If I have an Illuminate\Support\Collection, how do I sort by multiple properties with both asc and desc?  (This is a simple hypothetical - not at all looking for tips on query building.)</p>

```<code>$collection = User::all(); // not looking for User::orderBy()->get() solutions.  Read the question.
$sorting_insructions = [
    ['column'=>'first_name', 'order'=>'asc'],
    ['column'=>'date_of_birth', 'order'=>'desc'],
];
$collection->sort(function($a,$b) use ($sorting_instructions){
    // something...
});
</code>```

答:
If you are using Eloquent to get your collection instance, It would be much better to use orderBy method in your query, especially if columns were indexed:

```<code>$sorting_insructions = [
    ['column'=>'first_name', 'order'=>'asc'],
    ['column'=>'date_of_birth', 'order'=>'desc'],
];

$collection = App\User::query();

foreach ($sorting_insructions as $value) {

    $collection->orderBy($value['column'], $value['order']);

}

$users = $collection->get();
</code>```

EDIT Since the question was edited telling that sort should be used outside the query builder, I think chaining sortBy and sortByDesc in reverse order from $sorting_insructions gives the same result:

```<code>$collection = App\User::all();

$sorting_insructions = [
    ['column'=>'first_name', 'order'=>'asc'],
    ['column'=>'date_of_birth', 'order'=>'desc'],
];

for ($i = count($sorting_insructions) - 1; $i >= 0 ; $i--) {

    extract($sorting_insructions[i]);

    if ( $order === 'asc') {
        $collection = $collection->sortBy( $column );
    } else {
        $collection = $collection->sortByDesc( $column );
    }

}
</code>```

Body:
If I have an Illuminate\Support\Collection, how do I sort by multiple properties with both asc and desc?  (This is a simple hypothetical - not at all looking for tips on query building.)

$collection = User::all(); // not looking for User::orderBy()->get() solutions.  Read the question.
$sorting_insructions = [
    ['column'=>'first_name', 'order'=>'asc'],
    ['column'=>'date_of_birth', 'order'=>'desc'],
];
$collection->sort(function($a,$b) use ($sorting_instructions){
    // something...
});

Body:
If you are using Eloquent to get your collection instance, It would be much better to use orderBy method in your query, especially if columns were indexed:

$sorting_insructions = [
    ['column'=>'first_name', 'order'=>'asc'],
    ['column'=>'date_of_birth', 'order'=>'desc'],
];

$collection = App\User::query();

foreach ($sorting_insructions as $value) {

    $collection->orderBy($value['column'], $value['order']);

}

$users = $collection->get();

EDIT Since the question was edited telling that sort should be used outside the query builder, I think chaining sortBy and sortByDesc in reverse order from $sorting_insructions gives the same result:

$collection = App\User::all();

$sorting_insructions = [
    ['column'=>'first_name', 'order'=>'asc'],
    ['column'=>'date_of_birth', 'order'=>'desc'],
];

for ($i = count($sorting_insructions) - 1; $i >= 0 ; $i--) {

    extract($sorting_insructions[i]);

    if ( $order === 'asc') {
        $collection = $collection->sortBy( $column );
    } else {
        $collection = $collection->sortByDesc( $column );
    }

}


问:
ExtJS 6 - Stop Event Delegation while hiding component?
I have to hide same field on it's blur event.

Extjs 6 calls event delegation on component hide method.Event delegation revert focus to last field which had focus.

And, I don't want this revert focus. Is there any way I can stop event delegation while hiding elements in extjs ?

Event delegation comes with extjs 5 - Delegated Events and Gestures in Ext JS 5

Method using for hide  - https://docs.sencha.com/extjs/6.0/6.0.1-classic/#!/api/Ext.Component-method-onHide

onHide() method from ExtJS source code - check revertFocus()

```<code>onHide: function(animateTarget, cb, scope) {
    var me = this,
        ghostPanel, fromSize, toBox;
    if (!me.ariaStaticRoles[me.ariaRole]) {
        me.ariaEl.dom.setAttribute('aria-hidden', true);
    }
    // Part of the Focusable mixin API.
    // If we have focus now, move focus back to whatever had it before.
    me.revertFocus(); // this revert focus making probelm
    // Default to configured animate target if none passed
    animateTarget = me.getAnimateTarget(animateTarget);
    // Need to be able to ghost the Component
    if (!me.ghost) {
        animateTarget = null;
    }
    // If we're animating, kick off an animation of the ghost down to the target
    if (animateTarget) {
        toBox = {
            x: animateTarget.getX(),
            y: animateTarget.getY(),
            width: animateTarget.dom.offsetWidth,
            height: animateTarget.dom.offsetHeight
        };
        ghostPanel = me.ghost();
        ghostPanel.el.stopAnimation();
        fromSize = me.getSize();
        ghostPanel.el.animate({
            to: toBox,
            listeners: {
                afteranimate: function() {
                    delete ghostPanel.componentLayout.lastComponentSize;
                    ghostPanel.el.hide();
                    ghostPanel.setHiddenState(true);
                    ghostPanel.el.setSize(fromSize);
                    me.afterHide(cb, scope);
                }
            }
        });
    }
    me.el.hide();
    if (!animateTarget) {
        me.afterHide(cb, scope);
    }
},
</code>```

答:
I got the same problem. (extjs 6.5.1 - using a modal window with closeAction: 'hide')

I was debugging the code and seems it happened because the latest field focused was in a panel and my modal window was not child of that panel.
(seems the extjs get the ancestor of the modal window to find the latest focused field, then, set the focus)

When I added the window to that panel, it worked fine. (when the modal window was closed, the focus was on the latest field focused before open the window).

Debugging the Ext.util.Focusable class, I saw a config called preventRefocus. If you add that config with value true to your modal window, the content of the revertFocus function won't be executed and you won't get the error.

```<code>revertFocus: function() {
        var me = this,
            focusEvent = me.focusEnterEvent,
            activeElement = Ext.Element.getActiveElement(),
            focusTarget, fromComponent, reverted;

        // If we have a record of where focus arrived from,
        //  and have not been told to avoid refocusing,
        //  and we contain the activeElement.
        // Then, before hiding, restore focus to what was focused before we were focused.

        // --->>> THE IF BELOW: !me.preventRefocus <<<---

        if (focusEvent && !me.preventRefocus && me.el.contains(activeElement)) {
</code>```

I hope it also can help somebody in the future.

Body:
I have to hide same field on it's blur event.

Extjs 6 calls event delegation on component hide method.Event delegation revert focus to last field which had focus.

And, I don't want this revert focus. Is there any way I can stop event delegation while hiding elements in extjs ?

Event delegation comes with extjs 5 - Delegated Events and Gestures in Ext JS 5

Method using for hide  - https://docs.sencha.com/extjs/6.0/6.0.1-classic/#!/api/Ext.Component-method-onHide

onHide() method from ExtJS source code - check revertFocus()

onHide: function(animateTarget, cb, scope) {
    var me = this,
        ghostPanel, fromSize, toBox;
    if (!me.ariaStaticRoles[me.ariaRole]) {
        me.ariaEl.dom.setAttribute('aria-hidden', true);
    }
    // Part of the Focusable mixin API.
    // If we have focus now, move focus back to whatever had it before.
    me.revertFocus(); // this revert focus making probelm
    // Default to configured animate target if none passed
    animateTarget = me.getAnimateTarget(animateTarget);
    // Need to be able to ghost the Component
    if (!me.ghost) {
        animateTarget = null;
    }
    // If we're animating, kick off an animation of the ghost down to the target
    if (animateTarget) {
        toBox = {
            x: animateTarget.getX(),
            y: animateTarget.getY(),
            width: animateTarget.dom.offsetWidth,
            height: animateTarget.dom.offsetHeight
        };
        ghostPanel = me.ghost();
        ghostPanel.el.stopAnimation();
        fromSize = me.getSize();
        ghostPanel.el.animate({
            to: toBox,
            listeners: {
                afteranimate: function() {
                    delete ghostPanel.componentLayout.lastComponentSize;
                    ghostPanel.el.hide();
                    ghostPanel.setHiddenState(true);
                    ghostPanel.el.setSize(fromSize);
                    me.afterHide(cb, scope);
                }
            }
        });
    }
    me.el.hide();
    if (!animateTarget) {
        me.afterHide(cb, scope);
    }
},

Body:
I got the same problem. (extjs 6.5.1 - using a modal window with closeAction: 'hide')

I was debugging the code and seems it happened because the latest field focused was in a panel and my modal window was not child of that panel.
(seems the extjs get the ancestor of the modal window to find the latest focused field, then, set the focus)

When I added the window to that panel, it worked fine. (when the modal window was closed, the focus was on the latest field focused before open the window).

Debugging the Ext.util.Focusable class, I saw a config called preventRefocus. If you add that config with value true to your modal window, the content of the revertFocus function won't be executed and you won't get the error.

revertFocus: function() {
        var me = this,
            focusEvent = me.focusEnterEvent,
            activeElement = Ext.Element.getActiveElement(),
            focusTarget, fromComponent, reverted;

        // If we have a record of where focus arrived from,
        //  and have not been told to avoid refocusing,
        //  and we contain the activeElement.
        // Then, before hiding, restore focus to what was focused before we were focused.

        // --->>> THE IF BELOW: !me.preventRefocus <<<---

        if (focusEvent && !me.preventRefocus && me.el.contains(activeElement)) {

I hope it also can help somebody in the future.


问:
Need help improving my c++ and class creation 2
i wanna know where i can improve my program as well as i have run into a problem with my code.

this is my hero class and source, it is telling me i have hero h; calling a deleted function as well as how do i pass stats through this function? until i have this figured out i had // out the classes constructor.

```<code> class hero : public Stats {
    //protected:

public:

    void raceAndClass() {

        Stats S(10,10,10,10,10,10);
        race c_race(race::orc, S);
        //classes c_classes(classes::fighter, modStats, sneak, bluff, deplomacy, swim, mana, run);
        using namespace std;
        }
};

int main()
{
        hero H;
        H.raceAndClass();
        while (true);

}
</code>```

here is my next class stats

```<code>   class Stats {
    public:
        int //default stats
            Str = 10,
            Dex = 10,
            Con = 10,
            Int = 10,
            Wis = 10,
            Chr = 10;

    Stats(int STR, int DEX, int CON, int INT, int WIS, int CHR) :
        Str(STR), Dex(DEX), Con(CON), Int(INT), Wis(WIS), Chr(CHR) {
    }
};
</code>```

my race cpp and header

```<code>  #include"stats.h"

class race {
public:
    enum raceOpt { orc, elf, human };

    race(raceOpt c_raceOpt, Stats &stats);

    //race opt outcomes
    void ORC(Stats& stats) {
        stats.Str += 2;
        stats.Int -= 2;
        stats.Chr -= 2;
    }
    void ELF(Stats &stats) {
        //elf code and stat changes
    }

    void HUMAN(Stats &stats) {

}
    };

#include"race.h"

race::race(raceOpt c_raceOpt, Stats &stats) {
    switch (c_raceOpt) {
    case orc:
        ORC(stats);
        break;
    case human:
        //human code
        break;
    case elf:
        //elf code
        break;
    }
}
</code>```

and finally my classes cpp & header.(not currently being called)

```<code>#include"stats.h"

class classes {
public:
    enum classOpt { fighter, mage, soccerPlayer };

    classes(classOpt c_classOpt, double ModStats[_MAX_PATH], int& Sneak, int& Bluff, int& Deplomacy, int& Swim, int& Mana, int& Run);

    void Fighter(int& SWIM, int& RUN, int& BLUFF, double ModStats[_MAX_PATH]) {
        SWIM = static_cast<int>(SWIM + std::round(((ModStats[1] * 2.3))));
        RUN = static_cast<int>(RUN + (std::round(((ModStats[1] * 2)))));
        BLUFF = static_cast<int>(BLUFF + std::round(((ModStats[0] * 2.5))));

    }
    void Mage(int& MANA, int& DEPLOMACY, int& BLUFF, double ModStats[_MAX_PATH]) {
        //code to be added

    }
    void SoccerPlayer(int& RUN, int& SWIM, int& DEPLOMACY, int& SNEAK, double ModStats[_MAX_PATH]) {
        //code to be added

    }
};

#include"classes.h"

classes::classes(classOpt c_classOpt, double ModStats[_MAX_PATH], int& Sneak, int& Bluff, int& Deplomacy, int& Swim, int& Mana, int& Run) {
    switch (c_classOpt) {
    case fighter:
        Fighter(Swim, Run, Bluff, ModStats);
        break;
    case mage:
        Mage(Mana, Deplomacy, Bluff, ModStats);
        break;
    case soccerPlayer:
        SoccerPlayer(Run, Swim, Deplomacy, Sneak, ModStats);
        break;
    }

}
</code>```

答: Your hero class derives from Stats. Your Stats class requires a constructor call with a bunch of arguments; there is no default constructor. Therefore, you cannot call the default hero constructor with just hero H;, because there isn't one (that's where the compiler tells you that you can't reference a deleted method). You will need to implement a no-argument constructor for hero, which calls the Stats constructor with suitable arguments.

Body:
i wanna know where i can improve my program as well as i have run into a problem with my code.

this is my hero class and source, it is telling me i have hero h; calling a deleted function as well as how do i pass stats through this function? until i have this figured out i had // out the classes constructor.

 class hero : public Stats {
    //protected:

public:

    void raceAndClass() {

        Stats S(10,10,10,10,10,10);
        race c_race(race::orc, S);
        //classes c_classes(classes::fighter, modStats, sneak, bluff, deplomacy, swim, mana, run);
        using namespace std;
        }
};

int main()
{
        hero H;
        H.raceAndClass();
        while (true);

}

here is my next class stats

   class Stats {
    public:
        int //default stats
            Str = 10,
            Dex = 10,
            Con = 10,
            Int = 10,
            Wis = 10,
            Chr = 10;

    Stats(int STR, int DEX, int CON, int INT, int WIS, int CHR) :
        Str(STR), Dex(DEX), Con(CON), Int(INT), Wis(WIS), Chr(CHR) {
    }
};

my race cpp and header

  #include"stats.h"

class race {
public:
    enum raceOpt { orc, elf, human };

    race(raceOpt c_raceOpt, Stats &stats);

    //race opt outcomes
    void ORC(Stats& stats) {
        stats.Str += 2;
        stats.Int -= 2;
        stats.Chr -= 2;
    }
    void ELF(Stats &stats) {
        //elf code and stat changes
    }

    void HUMAN(Stats &stats) {

}
    };

#include"race.h"

race::race(raceOpt c_raceOpt, Stats &stats) {
    switch (c_raceOpt) {
    case orc:
        ORC(stats);
        break;
    case human:
        //human code
        break;
    case elf:
        //elf code
        break;
    }
}

and finally my classes cpp & header.(not currently being called)

#include"stats.h"

class classes {
public:
    enum classOpt { fighter, mage, soccerPlayer };

    classes(classOpt c_classOpt, double ModStats[_MAX_PATH], int& Sneak, int& Bluff, int& Deplomacy, int& Swim, int& Mana, int& Run);

    void Fighter(int& SWIM, int& RUN, int& BLUFF, double ModStats[_MAX_PATH]) {
        SWIM = static_cast<int>(SWIM + std::round(((ModStats[1] * 2.3))));
        RUN = static_cast<int>(RUN + (std::round(((ModStats[1] * 2)))));
        BLUFF = static_cast<int>(BLUFF + std::round(((ModStats[0] * 2.5))));

    }
    void Mage(int& MANA, int& DEPLOMACY, int& BLUFF, double ModStats[_MAX_PATH]) {
        //code to be added

    }
    void SoccerPlayer(int& RUN, int& SWIM, int& DEPLOMACY, int& SNEAK, double ModStats[_MAX_PATH]) {
        //code to be added

    }
};

#include"classes.h"

classes::classes(classOpt c_classOpt, double ModStats[_MAX_PATH], int& Sneak, int& Bluff, int& Deplomacy, int& Swim, int& Mana, int& Run) {
    switch (c_classOpt) {
    case fighter:
        Fighter(Swim, Run, Bluff, ModStats);
        break;
    case mage:
        Mage(Mana, Deplomacy, Bluff, ModStats);
        break;
    case soccerPlayer:
        SoccerPlayer(Run, Swim, Deplomacy, Sneak, ModStats);
        break;
    }

}


问:
Maintain object references through Serialize/Deserialize
When serializing, I would like to serialize an object only once, then any references to that object should be serialized as a reference to the object. This is because, when I later deserialize the objects, I would like to maintain those references. To illustrate my goal, the code below should output "After Serialization: true".</p>

```<code>class Program
{
    static void Main(string[] args)
    {
        MyObject obj = new MyObject() { Name = "obj" };
        MyObject[] myObjs = new MyObject[]
        {
            obj, obj
        };

        Console.WriteLine("Object Refs Equal?");
        Console.WriteLine(string.Format("Before Serialization: {0}",
            object.ReferenceEquals(myObjs[0], myObjs[1])));

        XmlSerializer toXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream toFile = File.Create(@"C:\foo.xml"))
        {
            toXml.Serialize(toFile, myObjs);
        }

        XmlSerializer fromXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream fromFile = File.OpenRead(@"C:\foo.xml"))
        {
            MyObject[] deserialized = (MyObject[])fromXml.Deserialize(fromFile);

            Console.WriteLine(string.Format("After Serialization: {0}",
            object.ReferenceEquals(deserialized[0], deserialized[1])));
        }

        Console.ReadLine();
    }
}

[Serializable]
public class MyObject
{
    public string Name { get; set; }
}
</code>```

答:
You will have to do that by giving the objects identifiers other than their object reference.

An object's reference is essentially it's pointer. Since you cannot manipulate pointers directly in safe code must give the object some other unique name.

OwnerDisplayName: CodeChef

Body:
When serializing, I would like to serialize an object only once, then any references to that object should be serialized as a reference to the object. This is because, when I later deserialize the objects, I would like to maintain those references. To illustrate my goal, the code below should output "After Serialization: true".

class Program
{
    static void Main(string[] args)
    {
        MyObject obj = new MyObject() { Name = "obj" };
        MyObject[] myObjs = new MyObject[]
        {
            obj, obj
        };

        Console.WriteLine("Object Refs Equal?");
        Console.WriteLine(string.Format("Before Serialization: {0}",
            object.ReferenceEquals(myObjs[0], myObjs[1])));

        XmlSerializer toXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream toFile = File.Create(@"C:\foo.xml"))
        {
            toXml.Serialize(toFile, myObjs);
        }

        XmlSerializer fromXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream fromFile = File.OpenRead(@"C:\foo.xml"))
        {
            MyObject[] deserialized = (MyObject[])fromXml.Deserialize(fromFile);

            Console.WriteLine(string.Format("After Serialization: {0}",
            object.ReferenceEquals(deserialized[0], deserialized[1])));
        }

        Console.ReadLine();
    }
}

[Serializable]
public class MyObject
{
    public string Name { get; set; }
}

OwnerDisplayName: Jan Bannister


答:
Ok, I figured it out.  I used the contoureR package to get a single contour line from the irregular grid and then plotted there:

```<code>library(ggplot2)
library(contoureR)

dat <- read.table("stack.csv",header=TRUE,sep=",")
ln <- getContourLines(dat$Lon,dat$Lat,dat$Data,levels=300)
df <- data.frame("Lon"=ln$x,"Lat"=ln$y,"Data"=ln$z)
</code>```

In the last line I created a data frame with column names identical to those in the data since I couldn't get the ggplot part to work otherwise:

```<code>p1 <- ggplot(dat,aes(x=Lon,y=Lat,z=Data,colour=Data)) + geom_point() +
scale_color_gradientn(colors=c("grey95","yellow2","firebrick"),na.value="white",values=c(0,0.25,0.75,1.0)) +
geom_path(data=df,mapping=aes(x=df$Lon,y=df$Lat),
linetype=1,color="black",lwd=0.25,alpha=0.5) +
theme(panel.background=element_blank(), axis.ticks=element_blank())
</code>```

The geom_path() part gave me various errors when I tried using the output from getContourLines so I copied the relevant columns to a data frame, which only worked when I gave column names identical to those in dat.  Then it worked!

This is the resulting image

Title: Superimpose two datasets with different color scales with ggplot

Body:
I would like to plot some data with lat,lon with points colorized to value and three specified contour levels superimposed on top.  I can't seem to get stat_contour or geom_contour to work since my data are not in a perfect grid format and I can't seem to get stat_density_2d to work since 1) I'm interested in the value not the point density, and 2) even when I rework my data to make it look like a density dataset I can't seem to figure out how to plot only the specific contour lines that I'm interested in. I also tried to get individual contour lines with contourLines() but that also led me to failure.

Here is a sample of the data I am working with.

Lon Lat Data
-76.2834    39.7619 26.0
-76.2823    39.7696 125.6
-76.2811    39.7774 134.2
-76.2800    39.7852 105.7
-76.2789    39.7930 61.6
-76.2778    39.8008 9.9
-76.2530    39.7544 313.4
-76.2519    39.7622 500.5
-76.2508    39.7700 554.2
-76.2497    39.7778 542.5
-76.2485    39.7856 505.2
-76.2474    39.7934 456.8
-76.2463    39.8011 402.8
-76.2452    39.8089 345.5
-76.2441    39.8167 286.3
-76.2429    39.8245 225.8
-76.2418    39.8323 164.4
-76.2407    39.8401 102.3
-76.2396    39.8479 39.8
-76.2215    39.7547 68.7
-76.2204    39.7625 229.8
-76.2193    39.7703 341.0
-76.2182    39.7781 409.9
-76.2170    39.7859 445.9
-76.2159    39.7937 457.8
-76.2148    39.8015 452.2
-76.2137    39.8093 433.9
-76.2125    39.8171 406.3
-76.2114    39.8248 371.7
-76.2103    39.8326 331.9
-76.2092    39.8404 288.1
-76.2080    39.8482 241.1
-76.2069    39.8560 191.6
-76.2058    39.8638 140.0
-76.2047    39.8716 86.8
-76.2035    39.8794 32.2
-76.1878    39.7706 82.0
-76.1867    39.7784 179.4
-76.1855    39.7862 251.9
-76.1844    39.7940 303.1
-76.1833    39.8018 336.3
-76.1822    39.8096 354.6
-76.1810    39.8174 360.6
-76.1799    39.8252 356.5
-76.1788    39.8330 344.0
-76.1777    39.8407 324.7
-76.1765    39.8485 299.6
-76.1754    39.8563 269.8
-76.1743    39.8641 235.9
-76.1731    39.8719 198.6
-76.1720    39.8797 158.4
-76.1709    39.8875 115.7
-76.1698    39.8953 70.9
-76.1686    39.9031 24.2
-76.1540    39.7865 17.5
-76.1529    39.7943 91.7
-76.1518    39.8021 150.1
-76.1507    39.8099 194.5
-76.1495    39.8177 226.5
-76.1484    39.8255 247.8
-76.1473    39.8333 259.7
-76.1461    39.8411 263.3
-76.1450    39.8488 259.9
-76.1439    39.8566 250.3
-76.1427    39.8644 235.2
-76.1416    39.8722 215.5
-76.1405    39.8800 191.5
-76.1393    39.8878 164.0
-76.1382    39.8956 133.2
-76.1371    39.9034 99.7
-76.1359    39.9112 63.5
-76.1348    39.9189 25.2
-76.1180    39.8180 44.5
-76.1169    39.8258 85.3
-76.1157    39.8336 116.7
-76.1146    39.8414 139.7
-76.1135    39.8492 155.0
-76.1123    39.8569 163.6
-76.1112    39.8647 166.0
-76.1101    39.8725 163.0
-76.1089    39.8803 155.0
-76.1078    39.8881 142.6
-76.1067    39.8959 126.2
-76.1055    39.9037 106.2
-76.1044    39.9115 82.9
-76.1032    39.9192 56.8
-76.1021    39.9270 27.9
-76.0819    39.8495 6.8
-76.0808    39.8572 30.9
-76.0797    39.8650 48.6
-76.0785    39.8728 60.5
-76.0774    39.8806 67.0
-76.0762    39.8884 68.7
-76.0751    39.8962 65.9
-76.0740    39.9040 59.0
-76.0728    39.9118 48.3
-76.0717    39.9195 34.3
-76.0705    39.9273 17.0

Here is my code right now.  I would like something to the effect of p1 and p2 on the same graph, but ggplot won't let me implement two different color schemes on the same plot:

library(ggplot2)

## Read Data from CSV file ##
data <- read.table("stack.csv",header=TRUE,sep=",")

## Rework the data to look like a density plot
n <- length(data[,1])
for (i in 1:n)
{
    v <- as.integer(data[i,4]/50)
    lon <- rep(data[i,2],v)
    lat <- rep(data[i,3],v)
    z <- rep(data[i,4],v)
    if (i == 1) {d <- data.frame(lon,lat,z)}
    else
    {
        dd <- data.frame(lon,lat,z)
        d <- rbind(d,dd)
    }
}

# Plot data
p1 <- ggplot(data,aes(x=Lon,y=Lat,z=Data,colour=Data)) + geom_point() +
scale_color_gradientn(colors=c("grey95","yellow2","firebrick"),na.value="white",values=c(0.0,0.85,0.95,1.0)) +
xlim(-76.31,-76.05) +
ylim(39.74,39.94) +
theme(panel.background=element_blank(), axis.ticks=element_blank())

# Get contour
p2 <- ggplot(d,aes(x=lon,y=lat)) +
stat_density_2d(aes(color=..level..),lwd=0.3) +
scale_color_gradientn(colors=c("white","white","grey60","grey95","white"),
na.value="white",values=c(0.0,0.85,0.90,0.95,1.0)) +
xlim(-76.31,-76.05) +
ylim(39.74,39.94) +
theme(panel.background=element_blank(), axis.ticks=element_blank())

Any help would be greatly appreciated.  Oh, and please go easy on me since this is my first ever post...

Here is the output of dput:

structure(list(X = c(401L, 601L, 801L, 1001L, 1201L, 1401L, 5001L,
5201L, 5401L, 5601L, 5801L, 6001L, 6201L, 6401L, 6601L, 6801L,
7001L, 7201L, 7401L, 9801L, 10001L, 10201L, 10401L, 10601L, 10801L,
11001L, 11201L, 11401L, 11601L, 11801L, 12001L, 12201L, 12401L,
12601L, 12801L, 13001L, 15001L, 15201L, 15401L, 15601L, 15801L,
16001L, 16201L, 16401L, 16601L, 16801L, 17001L, 17201L, 17401L,
17601L, 17801L, 18001L, 18201L, 18401L, 20201L, 20401L, 20601L,
20801L, 21001L, 21201L, 21401L, 21601L, 21801L, 22001L, 22201L,
22401L, 22601L, 22801L, 23001L, 23201L, 23401L, 23601L, 25801L,
26001L, 26201L, 26401L, 26601L, 26801L, 27001L, 27201L, 27401L,
27601L, 27801L, 28001L, 28201L, 28401L, 28601L, 31401L, 31601L,
31801L, 32001L, 32201L, 32401L, 32601L, 32801L, 33001L, 33201L,
33401L), Lon = c(-76.2833766152044, -76.2822614845223, -76.2811461257035,
-76.2800305386072, -76.2789147230922, -76.2777986790175, -76.2530102918317,
-76.2518918288511, -76.2507731365048, -76.2496542146515, -76.2485350631496,
-76.2474156818575, -76.2462960706334, -76.2451762293357, -76.2440561578225,
-76.2429358559517, -76.2418153235816, -76.2406945605699, -76.2395735667744,
-76.2215285318079, -76.220406508839, -76.2192842551349, -76.2181617705536,
-76.217039054953, -76.215916108191, -76.2147929301251, -76.2136695206132,
-76.2125458795127, -76.2114220066812, -76.210297901976, -76.2091735652545,
-76.2080489963739, -76.2069241951914, -76.2057991615641, -76.2046738953489,
-76.2035483964028, -76.1877948538244, -76.1866688068276, -76.1855425274412,
-76.1844160155223, -76.1832892709281, -76.1821622935157, -76.1810350831421,
-76.1799076396641, -76.1787799629386, -76.1776520528224, -76.176523909172,
-76.1753955318441, -76.1742669206952, -76.1731380755816, -76.1720089963598,
-76.170879682886, -76.1697501350163, -76.1686203526068, -76.1540454940392,
-76.1529154172824, -76.1517851064791, -76.1506545614859, -76.149523782159,
-76.1483927683548, -76.1472615199296, -76.1461300367394, -76.1449983186405,
-76.1438663654888, -76.1427341771401, -76.1416017534504, -76.1404690942754,
-76.1393361994707, -76.138203068892, -76.1370697023948, -76.1359360998344,
-76.1348022610662, -76.1180119900133, -76.116877406209, -76.1157425864104,
-76.1146075304732, -76.1134722382528, -76.1123367096047, -76.1112009443841,
-76.1100649424463, -76.1089287036465, -76.1077922278398, -76.1066555148811,
-76.1055185646255, -76.1043813769276, -76.1032439516424, -76.1021062886244,
-76.0819456814837, -76.0808065776724, -76.0796672359135, -76.0785276560616,
-76.0773878379713, -76.0762477814972, -76.0751074864935, -76.0739669528148,
-76.0728261803152, -76.0716851688488, -76.0705439182699), Lat = c(39.7618502813269,
39.7696398264863, 39.7774293547284, 39.7852188660436, 39.7930083604226,
39.8007978378559, 39.7544048721348, 39.7621941870797, 39.7699834849497,
39.7777727657353, 39.7855620294269, 39.7933512760152, 39.8011405054906,
39.8089297178436, 39.8167189130646, 39.8245080911442, 39.8322972520729,
39.8400863958411, 39.8478755224393, 39.7547404892594, 39.7625295547245,
39.7703186029472, 39.7781076339179, 39.7858966476271, 39.7936856440653,
39.8014746232228, 39.8092635850901, 39.8170525296577, 39.824841456916,
39.8326303668554, 39.8404192594663, 39.8482081347393, 39.8559969926646,
39.8637858332328, 39.8715746564343, 39.8793634622594, 39.770645180057,
39.7784339588547, 39.7862227202227, 39.7940114641515, 39.8018001906315,
39.8095888996529, 39.8173775912063, 39.825166265282, 39.8329549218704,
39.8407435609618, 39.8485321825466, 39.8563207866153, 39.8641093731582,
39.8718979421656, 39.8796864936279, 39.8874750275354, 39.8952635438786,
39.9030520426478, 39.786540246803, 39.7943287358635, 39.8021172073064,
39.809905661122, 39.8176940973007, 39.8254825158328, 39.8332709167086,
39.8410592999185, 39.8488476654527, 39.8566360133016, 39.8644243434555,
39.8722126559047, 39.8800009506396, 39.8877892276504, 39.8955774869274,
39.903365728461, 39.9111539522414, 39.9189421582589, 39.8180020475419,
39.8257902081697, 39.8335783509717, 39.8413664759382, 39.8491545830594,
39.8569426723257, 39.8647307437274, 39.8725187972546, 39.8803068328976,
39.8880948506467, 39.8958828504922, 39.9036708324242, 39.911458796433,
39.919246742509, 39.9270346706422, 39.8494529349797, 39.8572407633009,
39.8650285735872, 39.8728163658288, 39.8806041400158, 39.8883918961386,
39.8961796341873, 39.9039673541522, 39.9117550560233, 39.9195427397909,
39.9273304054451), Data = c(26.01872, 125.5967, 134.2395, 105.6832,
61.55046, 9.894023, 313.3874, 500.5094, 554.2007, 542.473, 505.2249,
456.8239, 402.7803, 345.5363, 286.3161, 225.7946, 164.3729, 102.3032,
39.75208, 68.7181, 229.8339, 340.999, 409.853, 445.9147, 457.7944,
452.1698, 433.8613, 406.2562, 371.7264, 331.9475, 288.1201, 241.1184,
191.59, 140.0223, 86.78784, 32.17551, 82.0317, 179.4106, 251.9416,
303.1165, 336.325, 354.6191, 360.617, 356.498, 344.0441, 324.6988,
299.6271, 269.7693, 235.8863, 198.5966, 158.4054, 115.7276, 70.90639,
24.22691, 17.54184, 91.71716, 150.1082, 194.4878, 226.5373, 247.7999,
259.6597, 263.3375, 259.8975, 250.2603, 235.2186, 215.4528, 191.5466,
164.001, 133.2463, 99.6526, 63.5395, 25.18322, 44.46111, 85.26085,
116.6825, 139.6546, 155.0307, 163.5872, 166.0246, 162.9709, 154.9872,
142.5729, 126.172, 106.1784, 82.94203, 56.77329, 27.94799, 6.796898,
30.87994, 48.59637, 60.4822, 67.03131, 68.69669, 65.89231, 58.99547,
48.34937, 34.26572, 17.02743)), .Names = c("X", "Lon", "Lat",
"Data"), class = "data.frame", row.names = c(NA, -98L))

Body:
Ok, I figured it out.  I used the contoureR package to get a single contour line from the irregular grid and then plotted there:

library(ggplot2)
library(contoureR)

dat <- read.table("stack.csv",header=TRUE,sep=",")
ln <- getContourLines(dat$Lon,dat$Lat,dat$Data,levels=300)
df <- data.frame("Lon"=ln$x,"Lat"=ln$y,"Data"=ln$z)

In the last line I created a data frame with column names identical to those in the data since I couldn't get the ggplot part to work otherwise:

p1 <- ggplot(dat,aes(x=Lon,y=Lat,z=Data,colour=Data)) + geom_point() +
scale_color_gradientn(colors=c("grey95","yellow2","firebrick"),na.value="white",values=c(0,0.25,0.75,1.0)) +
geom_path(data=df,mapping=aes(x=df$Lon,y=df$Lat),
linetype=1,color="black",lwd=0.25,alpha=0.5) +
theme(panel.background=element_blank(), axis.ticks=element_blank())

The geom_path() part gave me various errors when I tried using the output from getContourLines so I copied the relevant columns to a data frame, which only worked when I gave column names identical to those in dat.  Then it worked!

This is the resulting image


问:
Why is Spark setting partitions to the file size in bytes?
I have a very simple pyspark program that is supposed to read CSV files from S3:

```<code>r = sc.textFile('s3a://some-bucket/some-file.csv')
  .map(etc... you know the drill...)
</code>```

This was failing when running a local Spark node (it works in EMR). I was getting OOM errors and GC crashes. Upon further inspection, I realized that the number of partitions was insanely high. In this particular case r.getNumPartitions() would return 2358041.

I realized that that's exactly the size of my file in bytes. This, of course, makes Spark crash miserably.

I've tried different configurations, like chaning mapred.min.split.size:

```<code>conf = SparkConf()
conf.setAppName('iRank {}'.format(datetime.now()))
conf.set("mapred.min.split.size", "536870912")
conf.set("mapred.max.split.size", "536870912")
conf.set("mapreduce.input.fileinputformat.split.minsize", "536870912")
</code>```

I've also tried using repartition or changing passing a partitions argument to textFile, to no avail.

I would love to know what makes Spark think that it's a good idea to derive the number of partitions from the file size.

答:
In general it doesn't. As nicely explained by eliasah in his answer to Spark RDD default number of partitions it uses max of minPartitions (2 if not provided) and splits computed by Hadoop input format.

The latter one will by unreasonably high, only if instructed by the configuration. This suggests that some configuration file interferes with your program.

The possible problem with your code is that you use wrong configuration. Hadoop options should be set using hadoopConfiguration not Spark configuration. It looks like you use Python so you have to use private JavaSparkContext instance:

sc = ...  # type: SparkContext

sc._jsc.hadoopConfiguration().setInt("mapred.min.split.size", min_value)
sc._jsc.hadoopConfiguration().setInt("mapred.max.split.size", max_value)
```

Body:
I have a very simple pyspark program that is supposed to read CSV files from S3:

r = sc.textFile('s3a://some-bucket/some-file.csv')
  .map(etc... you know the drill...)

This was failing when running a local Spark node (it works in EMR). I was getting OOM errors and GC crashes. Upon further inspection, I realized that the number of partitions was insanely high. In this particular case r.getNumPartitions() would return 2358041.

I realized that that's exactly the size of my file in bytes. This, of course, makes Spark crash miserably.

I've tried different configurations, like chaning mapred.min.split.size:

conf = SparkConf()
conf.setAppName('iRank {}'.format(datetime.now()))
conf.set("mapred.min.split.size", "536870912")
conf.set("mapred.max.split.size", "536870912")
conf.set("mapreduce.input.fileinputformat.split.minsize", "536870912")

I've also tried using repartition or changing passing a partitions argument to textFile, to no avail.

I would love to know what makes Spark think that it's a good idea to derive the number of partitions from the file size.


问:
display automatic date in input
I am making a invoices page and I want the date to appear automatically as an input as well as the date of expiration (30 days later)

is there an automatic function?

I have this:

TD

can value change to something like todaysdate??? or 30 days later??

help! :D

答:
Your question is extremely difficult to decipher.

Perhaps you are looking for PHP's strtotime() function. For example, strtotime('today') returns a timestamp for today's date, and strtotime('next Wednesday') returns a timestamp for next Wednesday.

Title: display automatic date in input


问:
Creating a matrix from table in c#
With .Net MVC i am using DB First approach. I need a School Day Program, but I am not sure to use pivoting, DataTable or anything else?

The table in SQL is like that:

```<code>WeeklyProgram
Id RoomId Hour Day
1  1      9    1
2  1      12   1
3  2      14   1
4  2      12   2
5  3      11   1
6  4      10   2
</code>```

And trying to convert it to a table in html with null cells like this:

```<code>For Day 1 My School Program is;
#     Room1 Room2 Room3
9:00  1     null  null
10:00 null  null  null
11:00 null  null  5
12:00 2     null  null
13:00 null  null  null
14:00 null  3     null
</code>```

Tried pivoting but cant get what i thought.

Thanks all.

UPDATE: I'VE FOUND AN ANSWER

```<code>if (!date.HasValue)
            date = DateTime.Now;

        List<WeeklyProgram> modelBase = table
            .Where(b => b.Day == day)
            .ToList();

        int[] hours = { 9, 10, 11, 12, 13, 14};

        List<PivotTable> pivotTable = new List<PivotTable>();

        foreach (var hour in hours)
        {
            PivotTable pivotRow = new PivotTable() { Hour = hour };

            foreach (var item in modelBase)
                if (item.Hour == hour)
                    switch (item.RoomId)
                    {
                        case 1:
                            pivotRow.Room1 = item.Id;
                            break;
                        case 2:
                            pivotRow.Room2 = item.Id;
                            break;
                        case 3:
                            pivotRow.Room3 = item.Id;
                            break;
                    }
            pivotTable.Add(pivotRow);
        }

        return pivotTable;
</code>```

--

```<code>    public class PivotTable
{
    public int Hour { get; set; }
    public int Room1 { get; set; }
    public int Room2 { get; set; }
    public int Room3 { get; set; }
    public int Room4 { get; set; }
    public int Room5 { get; set; }
}
</code>```

答:
First, you need to filter your WeeklyProgram down to the day of interest:

```<code>var dayProgram = from c in WeeklyProgram
                 where c.Day == 1
                 select c;
</code>```

Then you can extract the hourly schedule rows from that data, leaving nulls for unscheduled rooms by converting Id into a nullable type, which is then converted to a Dictionary for lookup later:

```<code>var dayClasses = (from c in dayProgram
                  group c by c.Hour into cg
                  let cgd = cg.ToDictionary(c => c.RoomId, c => (int?)c.Id)
                  select new {
                      Hour = cg.Key,
                      Room1 = cgd.GetValueOrDefault(1),
                      Room2 = cgd.GetValueOrDefault(2),
                      Room3 = cgd.GetValueOrDefault(3)
                  }).ToDictionary(c => c.Hour, c => c);
</code>```

Now you extract all the hours that are used during the WeeklyProgram:

```<code>var hoursInWeek = (from c in WeeklyProgram
                   orderby c.Hour
                   select c.Hour).Distinct();
</code>```

Now you are ready to combine the hours used with the rooms scheduled:

```<code>var ans = from h in hoursInWeek
          select new {
              Hour = $"{h}:00",
              Room1 = dayClasses.GetValueOrDefault(h)?.Room1,
              Room2 = dayClasses.GetValueOrDefault(h)?.Room2,
              Room3 = dayClasses.GetValueOrDefault(h)?.Room3
          };
</code>```

This uses a helper function to make looking up in dictionaries where the key might not exist easier (NOTE: This uses all features up to C# 7.1.)

```<code>static public class Ext {
    public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV defaultValue = default) => dict.TryGetValue(key, out TV value) ? value : defaultValue;
}
</code>```

For earlier versions of C#, you can use this version:

```<code>static public class Ext {
    public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV defaultValue = default(TV)) => dict.TryGetValue(key, out TV value) ? value : defaultValue;
}
</code>```

Title: Creating a matrix from table in c#

Body:
With .Net MVC i am using DB First approach. I need a School Day Program, but I am not sure to use pivoting, DataTable or anything else?

The table in SQL is like that:

WeeklyProgram
Id RoomId Hour Day
1  1      9    1
2  1      12   1
3  2      14   1
4  2      12   2
5  3      11   1
6  4      10   2

And trying to convert it to a table in html with null cells like this:

For Day 1 My School Program is;
#     Room1 Room2 Room3
9:00  1     null  null
10:00 null  null  null
11:00 null  null  5
12:00 2     null  null
13:00 null  null  null
14:00 null  3     null

Tried pivoting but cant get what i thought.

Thanks all.

UPDATE: I'VE FOUND AN ANSWER

if (!date.HasValue)
            date = DateTime.Now;

        List<WeeklyProgram> modelBase = table
            .Where(b => b.Day == day)
            .ToList();

        int[] hours = { 9, 10, 11, 12, 13, 14};

        List<PivotTable> pivotTable = new List<PivotTable>();

        foreach (var hour in hours)
        {
            PivotTable pivotRow = new PivotTable() { Hour = hour };

            foreach (var item in modelBase)
                if (item.Hour == hour)
                    switch (item.RoomId)
                    {
                        case 1:
                            pivotRow.Room1 = item.Id;
                            break;
                        case 2:
                            pivotRow.Room2 = item.Id;
                            break;
                        case 3:
                            pivotRow.Room3 = item.Id;
                            break;
                    }
            pivotTable.Add(pivotRow);
        }

        return pivotTable;

--

    public class PivotTable
{
    public int Hour { get; set; }
    public int Room1 { get; set; }
    public int Room2 { get; set; }
    public int Room3 { get; set; }
    public int Room4 { get; set; }
    public int Room5 { get; set; }
}

Body:
First, you need to filter your WeeklyProgram down to the day of interest:

var dayProgram = from c in WeeklyProgram
                 where c.Day == 1
                 select c;

Then you can extract the hourly schedule rows from that data, leaving nulls for unscheduled rooms by converting Id into a nullable type, which is then converted to a Dictionary for lookup later:

var dayClasses = (from c in dayProgram
                  group c by c.Hour into cg
                  let cgd = cg.ToDictionary(c => c.RoomId, c => (int?)c.Id)
                  select new {
                      Hour = cg.Key,
                      Room1 = cgd.GetValueOrDefault(1),
                      Room2 = cgd.GetValueOrDefault(2),
                      Room3 = cgd.GetValueOrDefault(3)
                  }).ToDictionary(c => c.Hour, c => c);

Now you extract all the hours that are used during the WeeklyProgram:

var hoursInWeek = (from c in WeeklyProgram
                   orderby c.Hour
                   select c.Hour).Distinct();

Now you are ready to combine the hours used with the rooms scheduled:

var ans = from h in hoursInWeek
          select new {
              Hour = $"{h}:00",
              Room1 = dayClasses.GetValueOrDefault(h)?.Room1,
              Room2 = dayClasses.GetValueOrDefault(h)?.Room2,
              Room3 = dayClasses.GetValueOrDefault(h)?.Room3
          };

This uses a helper function to make looking up in dictionaries where the key might not exist easier (NOTE: This uses all features up to C# 7.1.)

static public class Ext {
    public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV defaultValue = default) => dict.TryGetValue(key, out TV value) ? value : defaultValue;
}

For earlier versions of C#, you can use this version:

static public class Ext {
    public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV defaultValue = default(TV)) => dict.TryGetValue(key, out TV value) ? value : defaultValue;
}


问:
Where are my Visual Studio Android emulators?
I'm just starting Jesse Liberty's new Pluralsight course, "Building Your First Mobile Application with Xamarin.Forms and Visual Studio 2017" and I'm running into a problem right out of the gate.

In the video, Jesse creates a new Xamarin.Forms project, modifies the XAML a bit, and runs it.  Here is a screenshot of his list of emulators:

I've disabled Hyper-V, and installed the latest Intel HAXM.
I've followed along step-by-step, using the latest version of VS2017 (installed yesterday, no updates available), and I've used the Android SDK Manager to install the SDK Platforms APIs 23 - 27.  More specifically, I've installed every available option for Android 6 (API 23), which is what shows in Jesse's list.

I have set the following Android project Properties:

```<code>     Application :: Target Framework = Use Latest Platform  (Android 8.0 Oreo)
Android Manifest ::  Minimum Version = Android 6.0 (API 23 - Marshmallow)
Android Manifest ::   Target Version = Android 8.0 (API 26 - Oreo)
</code>```

When I open the dropdown, I don't even see the VisualStudio_android emulators at all, and I'd assume they come preinstalled with VS2017 when I install Xamarin, but no:

I have no idea where to get the Visual Studio emulators; but, as I understand it, they run much faster than others so figuring this out will probably be worth my time.

The Android Virtual Device (AVD) Manager doesn't list the VS emulators, so I can't add them from there. I know there is an Android emulator from Microsoft but it says it's Hyper-V compatible, and I've just disabled Hyper-V to use the other emulators. Is this a good choice?  Are these the emulators I'm missing?

I'm out of ideas - what's my next step?

答:
It turns out, the emulators weren't installed for some reason when I installed VS2017 and the Mobile Development Workflow.

I went into the "Individual Components" tab in the Visual Studio Installer, checked the emulator boxes, and all the emulators show up fine now.

Body:
I'm just starting Jesse Liberty's new Pluralsight course, "Building Your First Mobile Application with Xamarin.Forms and Visual Studio 2017" and I'm running into a problem right out of the gate.

In the video, Jesse creates a new Xamarin.Forms project, modifies the XAML a bit, and runs it.  Here is a screenshot of his list of emulators:

I've disabled Hyper-V, and installed the latest Intel HAXM.
I've followed along step-by-step, using the latest version of VS2017 (installed yesterday, no updates available), and I've used the Android SDK Manager to install the SDK Platforms APIs 23 - 27.  More specifically, I've installed every available option for Android 6 (API 23), which is what shows in Jesse's list.

I have set the following Android project Properties:

     Application :: Target Framework = Use Latest Platform  (Android 8.0 Oreo)
Android Manifest ::  Minimum Version = Android 6.0 (API 23 - Marshmallow)
Android Manifest ::   Target Version = Android 8.0 (API 26 - Oreo)

When I open the dropdown, I don't even see the VisualStudio_android emulators at all, and I'd assume they come preinstalled with VS2017 when I install Xamarin, but no:

I have no idea where to get the Visual Studio emulators; but, as I understand it, they run much faster than others so figuring this out will probably be worth my time.

The Android Virtual Device (AVD) Manager doesn't list the VS emulators, so I can't add them from there. I know there is an Android emulator from Microsoft but it says it's Hyper-V compatible, and I've just disabled Hyper-V to use the other emulators. Is this a good choice?  Are these the emulators I'm missing?

I'm out of ideas - what's my next step?


问:
Assigning value to element of a cstring
Just learned about cstrings in my computer science class and it just hit me,
this is legal

```<code>char ch[] = "hello";
</code>```

However, it seems that I can also assign to the "5th" element in this array

```<code>ch[5] = "!";
</code>```

Is this allowed? Or am I just overriding the null character at the end of the array?

答:
No it's not allowed. As you said, this is overwriting the null-character at the end. It doesn't cause an error at this point, because you are accessing a valid index.

But if you try to print the string, then the print function doesn't know where the string ends. The print function will keep printing the characters until it reaches a zero byte by accident, or something else goes horribly wrong with buffer overflow. This is undefined behavior. The same problem will occur with other string functions, strcpy, strlen, strcmp... who all rely on the null-character to find the end of string.

Title: Assigning value to element of a cstring

Body:
Just learned about cstrings in my computer science class and it just hit me,
this is legal

char ch[] = "hello";

However, it seems that I can also assign to the "5th" element in this array

ch[5] = "!";

Is this allowed? Or am I just overriding the null character at the end of the array?


问:
Dynamic variable in PHP [GET]
I'm trying to use the php get. everthing is working find exept the include page.
it's adding 1 at the end of include content
any ide how do i ride that?

example:

```<code>I love norway
I love norway1
</code>```

Code:

```<code><?php
if($_GET['boy'] == 'zabi') $zabkas =  'it is Zabi';
if($_GET['girl'] == 'veronka') $verona = 'It is veronka';
if($_GET['place'] == 'norway') $norge = include('norway.php');
?>

<?php echo $zabkas ?>
<?php echo $verona ?>
<?php echo $norge ?>
</code>```

答:
Use the output buffer functions to capture the output from the included script.</p>

```<code><?php
if($_GET['boy'] == 'zabi') $zabkas =  'it is Zabi';
if($_GET['girl'] == 'veronka') $verona = 'It is veronka';
if($_GET['place'] == 'norway') {
    ob_start();
    include("norway.php");
    $norge = ob_get_clean();
}
?>

<?php echo $zabkas ?>
<?php echo $verona ?>
<?php echo $norge ?>
</code>```

Title: Dynamic variable in PHP [GET]

Body:
I'm trying to use the php get. everthing is working find exept the include page.
it's adding 1 at the end of include content
any ide how do i ride that?

example:

I love norway
I love norway1

Code:

<?php
if($_GET['boy'] == 'zabi') $zabkas =  'it is Zabi';
if($_GET['girl'] == 'veronka') $verona = 'It is veronka';
if($_GET['place'] == 'norway') $norge = include('norway.php');
?>

<?php echo $zabkas ?>
<?php echo $verona ?>
<?php echo $norge ?>

Body:
Use the output buffer functions to capture the output from the included script.

<?php
if($_GET['boy'] == 'zabi') $zabkas =  'it is Zabi';
if($_GET['girl'] == 'veronka') $verona = 'It is veronka';
if($_GET['place'] == 'norway') {
    ob_start();
    include("norway.php");
    $norge = ob_get_clean();
}
?>

<?php echo $zabkas ?>
<?php echo $verona ?>
<?php echo $norge ?>


问:
How do I remove the objects I want from an array and add them to another array using .forEach?
This is a coding challenge I'm working on and can't seem to grasp what I need to do. Not sure if I am even going in the right direction.

Here is the instructions: Here we have an array called people. Some of them are our friends and some are not.
1. Create an empty array called friends.
2. Using .forEach, loop over people and add those that are our friend to the empty friends array.

Here is the provided code:

```<code>var people = [
  {name: "Landy",friend: true},
  {name: "Corey",friend: true},
  {name: "Ted",friend: false},
  {name: "Sperry",friend: true},
  {name: "Bill",friend: false}
];
</code>```

My code so far:

```<code>var friends = [];
people.forEach(function(people){
  if (people === true) {
    return name;
  } else {
    //
  }
});
</code>```

答:
This is a quick solution using $.grep();

```<code>var friends=$.grep(people,function(o){
                                  return o.friend;
                                     });
</code>```

$.grep() returns array of object passed into the callback function that returns true

Body:
This is a coding challenge I'm working on and can't seem to grasp what I need to do. Not sure if I am even going in the right direction.

Here is the instructions: Here we have an array called people. Some of them are our friends and some are not.
1. Create an empty array called friends.
2. Using .forEach, loop over people and add those that are our friend to the empty friends array.

Here is the provided code:

var people = [
  {name: "Landy",friend: true},
  {name: "Corey",friend: true},
  {name: "Ted",friend: false},
  {name: "Sperry",friend: true},
  {name: "Bill",friend: false}
];

My code so far:

var friends = [];
people.forEach(function(people){
  if (people === true) {
    return name;
  } else {
    //
  }
});

Body:
This is a quick solution using $.grep();

var friends=$.grep(people,function(o){
                                  return o.friend;
                                     });

$.grep() returns array of object passed into the callback function that returns true


问:
Private IBOutlets Swift
I know that our IBOutlets should be private, but for example if I have IBOutlets in TableViewCell, how should I access them from another ViewController? Here is the example why I'm asking this kind of question:

```<code>class BookTableViewCell: UITableViewCell {

    @IBOutlet weak private var bookTitle: UILabel!

}
</code>```

if I assign to the IBOutlet that it should be private, I got an error in another ViewController while I'm accessing the cell property: 'bookTitle' is inaccessible due to 'private' protection level

答:
If I understand your question correctly, you are supposing the @IBOutlet properties should be marked as private all the time... Well it's not true. But also accessing the properties directly is not safe at all. You see the ViewControllers, TableViewCells and these objects use Implicit unwrapping on optional IBOutlets for reason... You don't need to init ViewController when using storyboards or just when using them somewhere in code... The other way - just imagine you are creating VC programmatically and you are passing all the labels to the initializer... It would blow your head... Instead of this, you come with this in storyboard:

@IBOutlet var myLabel: UILabel!

this is cool, you don't need to have that on init, it will just be there waiting to be set somewhere before accessing it's value... Interface builder will handle for you the initialization just before ViewDidLoad, so the label won't be nil after that time... again before AwakeFromNib method goes in the UITableViewCell subclass, when you would try to access your  bookTitle label property, it would crash since it would be nil... This is the tricky part about why this should be private... Otherwise when you know that the VC is 100% on the scene allocated there's no need to be shy and make everything private...

When you for example work in prepare(for segue:) method, you SHOULD NEVER ACCESS THE @IBOutlets. Since they are not allocated and even if they were, they would get overwritten by some internal calls in push/present/ whatever functions...

Okay that's cool.. so what to do now?

When using UITableViewCell subclass, you can safely access the IBOutlets (ONLY IF YOU USE STORYBOARD AND THE CELL IS WITHIN YOUR TABLEVIEW❗)

and change their values... you see

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// We shouldn't return just some constructor with UITableViewCell, but who cares for this purposes...
 guard let cell = tableView.dequeueReusableCell(withIdentifier: "bookTableViewCell", for: indexPath) else { return UITableViewCell() }
cell.bookTitle.text = "any given text" // This should work ok because of interface builder...
}
</code>```

The above case should work in MVC pattern, not MVVM or other patterns where you don't use storyboards with tableViewControllers and embed cells too much... (because of registering cells, but that's other article...)

I will give you few pointers, how you can setup the values in the cell/ViewController without touching the actual values and make this safe... Also good practice (safety) is to make the IBOutlets optional to be 100% Safe, but it's not necessary and honestly it would be strange approach to this problem:

ViewControllers:

```<code>class SomeVC: UIViewController {

    // This solution should be effective when those labels could be marked weak too...
    // Always access weak variables NOT DIRECTLY but with safe unwrap...
    @IBOutlet var titleLabel: UILabel?
    @IBOutlet var subtitleLabel: UILabel?

    var myCustomTitle: String?
    var myCustomSubtitle: String?

    func setup(with dataSource: SomeVCDataSource ) {

        guard let titleLabel = titleLabel, let subtitleLabel = subtitleLabel else { return }
        // Now the values are safely unwrapped and nothing can crash...
        titleLabel.text = dataSource.title
        subtitleLabel.text = dataSource.subtitle
    }

    // WHen using prepare for segue, use this:
    override func viewDidLoad() {

        super.viewDidLoad()
        titleLabel.text = myCustomTitle
        subtitleLabel.text = myCustomSubtitle

    }

}

struct SomeVCDataSource {

    var title: String
    var subtitle: String
}
</code>```

The next problem could be this:

```<code>    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    guard let destinationVC = segue.destination as? SomeVC else { return }

    let datasource = SomeVCDataSource(title: "Foo", subtitle: "Bar")
    // This sets up cool labels... but the labels are Nil before the segue occurs and even after that, so the guard in setup(with dataSource:) will fail and return...
    destinationVC.setup(with: datasource)

    // So instead of this you should set the properties myCustomTitle and myCustomSubtitle to values you want and then in viewDidLoad set the values
    destinationVC.myCustomTitle = "Foo"
    destinationVC.myCustomSubtitle = "Bar"
}
</code>```

You see, you don' need to set your IBOutlets to private since you never know how you will use them If you need any more examples or something is not clear to you, ask as you want... Wish you happy coding and deep learning!

Title: Private IBOutlets Swift

Body:
I know that our IBOutlets should be private, but for example if I have IBOutlets in TableViewCell, how should I access them from another ViewController? Here is the example why I'm asking this kind of question:

class BookTableViewCell: UITableViewCell {

    @IBOutlet weak private var bookTitle: UILabel!

}

if I assign to the IBOutlet that it should be private, I got an error in another ViewController while I'm accessing the cell property: 'bookTitle' is inaccessible due to 'private' protection level

Body:
If I understand your question correctly, you are supposing the @IBOutlet properties should be marked as private all the time... Well it's not true. But also accessing the properties directly is not safe at all. You see the ViewControllers, TableViewCells and these objects use Implicit unwrapping on optional IBOutlets for reason... You don't need to init ViewController when using storyboards or just when using them somewhere in code... The other way - just imagine you are creating VC programmatically and you are passing all the labels to the initializer... It would blow your head... Instead of this, you come with this in storyboard:

@IBOutlet var myLabel: UILabel!

this is cool, you don't need to have that on init, it will just be there waiting to be set somewhere before accessing it's value... Interface builder will handle for you the initialization just before ViewDidLoad, so the label won't be nil after that time... again before AwakeFromNib method goes in the UITableViewCell subclass, when you would try to access your  bookTitle label property, it would crash since it would be nil... This is the tricky part about why this should be private... Otherwise when you know that the VC is 100% on the scene allocated there's no need to be shy and make everything private...

When you for example work in prepare(for segue:) method, you SHOULD NEVER ACCESS THE @IBOutlets. Since they are not allocated and even if they were, they would get overwritten by some internal calls in push/present/ whatever functions...

Okay that's cool.. so what to do now?

When using UITableViewCell subclass, you can safely access the IBOutlets (ONLY IF YOU USE STORYBOARD AND THE CELL IS WITHIN YOUR TABLEVIEW❗)

and change their values... you see

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// We shouldn't return just some constructor with UITableViewCell, but who cares for this purposes...
 guard let cell = tableView.dequeueReusableCell(withIdentifier: "bookTableViewCell", for: indexPath) else { return UITableViewCell() }
cell.bookTitle.text = "any given text" // This should work ok because of interface builder...
}

The above case should work in MVC pattern, not MVVM or other patterns where you don't use storyboards with tableViewControllers and embed cells too much... (because of registering cells, but that's other article...)

I will give you few pointers, how you can setup the values in the cell/ViewController without touching the actual values and make this safe... Also good practice (safety) is to make the IBOutlets optional to be 100% Safe, but it's not necessary and honestly it would be strange approach to this problem:

ViewControllers:

class SomeVC: UIViewController {

    // This solution should be effective when those labels could be marked weak too...
    // Always access weak variables NOT DIRECTLY but with safe unwrap...
    @IBOutlet var titleLabel: UILabel?
    @IBOutlet var subtitleLabel: UILabel?

    var myCustomTitle: String?
    var myCustomSubtitle: String?

    func setup(with dataSource: SomeVCDataSource ) {

        guard let titleLabel = titleLabel, let subtitleLabel = subtitleLabel else { return }
        // Now the values are safely unwrapped and nothing can crash...
        titleLabel.text = dataSource.title
        subtitleLabel.text = dataSource.subtitle
    }

    // WHen using prepare for segue, use this:
    override func viewDidLoad() {

        super.viewDidLoad()
        titleLabel.text = myCustomTitle
        subtitleLabel.text = myCustomSubtitle

    }

}

struct SomeVCDataSource {

    var title: String
    var subtitle: String
}

The next problem could be this:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    guard let destinationVC = segue.destination as? SomeVC else { return }

    let datasource = SomeVCDataSource(title: "Foo", subtitle: "Bar")
    // This sets up cool labels... but the labels are Nil before the segue occurs and even after that, so the guard in setup(with dataSource:) will fail and return...
    destinationVC.setup(with: datasource)

    // So instead of this you should set the properties myCustomTitle and myCustomSubtitle to values you want and then in viewDidLoad set the values
    destinationVC.myCustomTitle = "Foo"
    destinationVC.myCustomSubtitle = "Bar"
}

You see, you don' need to set your IBOutlets to private since you never know how you will use them If you need any more examples or something is not clear to you, ask as you want... Wish you happy coding and deep learning!


问:
How to subset ffdf by index?
I would like to subset an ffdf object by index, returning another ffdf object.

The help file on subset.ffdf indicates that you can pass a range index (ri) object as an argument, but when I tried:

```<code>data_subset <- subset.ffdf(data, ri(1, 1e5))
</code>```

I got this error:

```<code>Error in which(eval(e, nl, envir)) : argument to 'which' is not logical
</code>```

Per You-Leee's suggestion, I tried passing a logical vector of the index of interest with this code:

```<code>n <- length(data[[1]]) #10.5 million
logical_index = c(1, 1e5) == seq.int(1, n)
data_subset <- subset(data, logical_index)
</code>```

I tried to run it twice and each time my R-Studio crashed with the message R encountered a fatal error.  The session was terminated. At first I thought it might be a memory constraint, but looking at my activity monitor, I still have 4gb available out of 8gb.  And besides, this shouldn't be loading much into memory anyway.

答:
The argument has to be logical, so you have to put TRUE on the desired indices and FALSE otherwise:</p>

```<code>> data <- ffdf(a = ff(1:12))
> subset.ffdf(data, c(1, 1e5) == seq.int(1, length(data$a)))
ffdf (all open) dim=c(1,1), dimorder=c(1,2) row.names=NULL
ffdf virtual mapping
  PhysicalName VirtualVmode PhysicalVmode  AsIs VirtualIsMatrix     PhysicalIsMatrix
a            a      integer       integer FALSE           FALSE                FALSE
  PhysicalElementNo PhysicalFirstCol PhysicalLastCol PhysicalIsOpen
a                 1                1               1           TRUE
ffdf data
  a
1 1
</code>```

Title: How to subset ffdf by index?

Body:
I would like to subset an ffdf object by index, returning another ffdf object.

The help file on subset.ffdf indicates that you can pass a range index (ri) object as an argument, but when I tried:

data_subset <- subset.ffdf(data, ri(1, 1e5))

I got this error:

Error in which(eval(e, nl, envir)) : argument to 'which' is not logical

Per You-Leee's suggestion, I tried passing a logical vector of the index of interest with this code:

n <- length(data[[1]]) #10.5 million
logical_index = c(1, 1e5) == seq.int(1, n)
data_subset <- subset(data, logical_index)

I tried to run it twice and each time my R-Studio crashed with the message R encountered a fatal error.  The session was terminated. At first I thought it might be a memory constraint, but looking at my activity monitor, I still have 4gb available out of 8gb.  And besides, this shouldn't be loading much into memory anyway.

Body:
The argument has to be logical, so you have to put TRUE on the desired indices and FALSE otherwise:

> data <- ffdf(a = ff(1:12))
> subset.ffdf(data, c(1, 1e5) == seq.int(1, length(data$a)))
ffdf (all open) dim=c(1,1), dimorder=c(1,2) row.names=NULL
ffdf virtual mapping
  PhysicalName VirtualVmode PhysicalVmode  AsIs VirtualIsMatrix     PhysicalIsMatrix
a            a      integer       integer FALSE           FALSE                FALSE
  PhysicalElementNo PhysicalFirstCol PhysicalLastCol PhysicalIsOpen
a                 1                1               1           TRUE
ffdf data
  a
1 1