问:
How to open multiple windows in a queue, each window waiting for previous to close?
I'm trying to create a primitive notifications system.

This is how I show my window:

```<code>var data = new NotificationData {
    Title = "New order",
    OrderId = "1"
}
var notification = new NotificationWindow(data);
    Activated += (s, e) => { notification.Owner = this; };
    notification.Show();
</code>```

Then the NotificationWindow just displays provided data. But if there are multiple notifications, they all stack in one spot, I need them to appear after previous is closed.

I tried to use ShowDialog() instead and it did work - but the MainWindow hangs when notification is open. Running it in a different thread using Task.Run() causes notifications not to appear.

答:
You need to register to the closed event and then check if another notification is queued.

The key is the ShowOrQueueNotification which checks if there is a notification present or not. If there is one present, queue the new one and when the notification is closed, you need to check if there is one queued.

I've made an example to show how to use a queue for it:

MainWindow.xaml

```<code><Window x:Class="TestNotificationQueue.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestNotificationQueue"
        mc:Ignorable="d"
        Title="MainWindow" Height="158.868" Width="266.385">
    <Grid>
        <Border Background="Yellow" VerticalAlignment="Center" HorizontalAlignment="Center" BorderThickness="1" BorderBrush="Black" >
            <StackPanel Margin="20">
                <TextBox x:Name="TextBoxMessage" Width="192" />
                <Button Content="ShowNotification" Width="128" Height="24" Click="Button_Click" Margin="8"/>
            </StackPanel>
        </Border>
    </Grid>
</Window>
</code>```

MainWindow.xaml.cs

```<code>using System;
using System.Collections.Generic;
using System.Windows;

namespace TestNotificationQueue
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Queue<NotificationInfo> _notificationQueue = new Queue<NotificationInfo>();
        private NotificationWindow _currentNotificationWindow;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ShowOrQueueNotification(new NotificationInfo(TextBoxMessage.Text));
        }

        private void ShowOrQueueNotification(NotificationInfo notificationInfo)
        {
// ----->   If no notification is presented, create one.
            if (_currentNotificationWindow == null)
            {
                _currentNotificationWindow = new NotificationWindow(notificationInfo);
                _currentNotificationWindow.Closed += CurrentNotificationWindow_Closed;
                _currentNotificationWindow.Show();
            }
            else
// ----->       queue it.
                _notificationQueue.Enqueue(notificationInfo);
        }

        private void CurrentNotificationWindow_Closed(object sender, EventArgs e)
        {
// ----->   This is crucial, you need to set the current to null, else all new notification will be queued and never be presented.
            _currentNotificationWindow = null;

            if(_notificationQueue.Count > 0)
                ShowOrQueueNotification(_notificationQueue.Dequeue());
        }
    }
}
</code>```

Notification.cs

```<code>namespace TestNotificationQueue
{
    public class NotificationInfo
    {
        public NotificationInfo(string message)
        {
            Message = message;
        }

        public string Message { get; }
    }
}
</code>```

NotificationWindow.xaml

```<code><Window x:Class="TestNotificationQueue.NotificationWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestNotificationQueue"
        mc:Ignorable="d"
        Title="NotificationWindow" Height="93.117" Width="239.4">
    <Grid>
        <TextBlock x:Name="TextBoxMessage" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Height="30" />
    </Grid>
</Window>
</code>```

NotificationWindow.xaml.cs

```<code>using System.Windows;

namespace TestNotificationQueue
{
    /// <summary>
    /// Interaction logic for NotificationWindow.xaml
    /// </summary>
    public partial class NotificationWindow : Window
    {
        public NotificationWindow(NotificationInfo notificationInfo)
        {
            InitializeComponent();
            TextBoxMessage.Text = notificationInfo.Message;
        }
    }
}
</code>```

Body:
I'm trying to create a primitive notifications system.

This is how I show my window:

var data = new NotificationData {
    Title = "New order",
    OrderId = "1"
}
var notification = new NotificationWindow(data);
    Activated += (s, e) => { notification.Owner = this; };
    notification.Show();

Then the NotificationWindow just displays provided data. But if there are multiple notifications, they all stack in one spot, I need them to appear after previous is closed.

I tried to use ShowDialog() instead and it did work - but the MainWindow hangs when notification is open. Running it in a different thread using Task.Run() causes notifications not to appear.

Body:
You need to register to the closed event and then check if another notification is queued.

The key is the ShowOrQueueNotification which checks if there is a notification present or not. If there is one present, queue the new one and when the notification is closed, you need to check if there is one queued.

I've made an example to show how to use a queue for it:

MainWindow.xaml

<Window x:Class="TestNotificationQueue.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestNotificationQueue"
        mc:Ignorable="d"
        Title="MainWindow" Height="158.868" Width="266.385">
    <Grid>
        <Border Background="Yellow" VerticalAlignment="Center" HorizontalAlignment="Center" BorderThickness="1" BorderBrush="Black" >
            <StackPanel Margin="20">
                <TextBox x:Name="TextBoxMessage" Width="192" />
                <Button Content="ShowNotification" Width="128" Height="24" Click="Button_Click" Margin="8"/>
            </StackPanel>
        </Border>
    </Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Windows;

namespace TestNotificationQueue
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Queue<NotificationInfo> _notificationQueue = new Queue<NotificationInfo>();
        private NotificationWindow _currentNotificationWindow;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ShowOrQueueNotification(new NotificationInfo(TextBoxMessage.Text));
        }

        private void ShowOrQueueNotification(NotificationInfo notificationInfo)
        {
// ----->   If no notification is presented, create one.
            if (_currentNotificationWindow == null)
            {
                _currentNotificationWindow = new NotificationWindow(notificationInfo);
                _currentNotificationWindow.Closed += CurrentNotificationWindow_Closed;
                _currentNotificationWindow.Show();
            }
            else
// ----->       queue it.
                _notificationQueue.Enqueue(notificationInfo);
        }

        private void CurrentNotificationWindow_Closed(object sender, EventArgs e)
        {
// ----->   This is crucial, you need to set the current to null, else all new notification will be queued and never be presented.
            _currentNotificationWindow = null;

            if(_notificationQueue.Count > 0)
                ShowOrQueueNotification(_notificationQueue.Dequeue());
        }
    }
}

Notification.cs

namespace TestNotificationQueue
{
    public class NotificationInfo
    {
        public NotificationInfo(string message)
        {
            Message = message;
        }

        public string Message { get; }
    }
}

NotificationWindow.xaml

<Window x:Class="TestNotificationQueue.NotificationWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestNotificationQueue"
        mc:Ignorable="d"
        Title="NotificationWindow" Height="93.117" Width="239.4">
    <Grid>
        <TextBlock x:Name="TextBoxMessage" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Height="30" />
    </Grid>
</Window>

NotificationWindow.xaml.cs

using System.Windows;

namespace TestNotificationQueue
{
    /// <summary>
    /// Interaction logic for NotificationWindow.xaml
    /// </summary>
    public partial class NotificationWindow : Window
    {
        public NotificationWindow(NotificationInfo notificationInfo)
        {
            InitializeComponent();
            TextBoxMessage.Text = notificationInfo.Message;
        }
    }
}


来源: stackexchange

问:
when call router.post method from url get error 404 not found in express.js
I have got a problem with Express, I am trying to use the app.post() function but it's not working and I don't know why...

Even though I have included the bodyParser()...

It returns 404 page not found error

```<code>var express = require('express');

var MongoClient = require('mongodb').MongoClient;

var router = express.Router();

router.post("/hello",(req, res) => {
        res.send('POST CALL');
    });

/* GET home page. */
router.get('/', function(req, res, next) {
    MongoClient.connect('mongodb://localhost:27017/nicky', function (err, client) {
        if (err) throw err

        var db = client.db('nicky')

        db.collection('student').find().toArray(function (err, result) {
            if (err) throw err
            res.send(JSON.stringify(result));
        })
    })
});
module.exports = router;
</code>```

GET is working properly, but POST is not.

答:
I am not sure how rest of your code looks, but I have copied your provided snippet and it works this way:

express-post.js:

```<code>const express = require('express');
const router = express.Router();

// curl -X POST http://localhost:3000/bar/hello
router.post("/hello",(req, res) => {
    res.send('It is POST');
});

// curl -X GET http://localhost:3000/bar/hi
router.get('/hi', function(req, res, next) {
    res.send('It is GET');
});

module.exports = router;
</code>```

express-post-server.js:

```<code>const express = require('express');
const bar = require('./express-post');
const app = express();

// curl -X GET http://localhost:3000/foo
app.get('/foo', function (req, res, next) {
    res.send('This is foo GET!');
});

// register
app.use('/bar', bar);

app.listen(3000);
</code>```

For complete running example clone node-cheat and run node express-post.

ContentLicense: CC BY-SA 4.0

Body:
I have got a problem with Express, I am trying to use the app.post() function but it's not working and I don't know why...

Even though I have included the bodyParser()...

It returns 404 page not found error

var express = require('express');

var MongoClient = require('mongodb').MongoClient;

var router = express.Router();

router.post("/hello",(req, res) => {
        res.send('POST CALL');
    });

/* GET home page. */
router.get('/', function(req, res, next) {
    MongoClient.connect('mongodb://localhost:27017/nicky', function (err, client) {
        if (err) throw err

        var db = client.db('nicky')

        db.collection('student').find().toArray(function (err, result) {
            if (err) throw err
            res.send(JSON.stringify(result));
        })
    })
});
module.exports = router;

GET is working properly, but POST is not.

Body:
I am not sure how rest of your code looks, but I have copied your provided snippet and it works this way:

express-post.js:

const express = require('express');
const router = express.Router();

// curl -X POST http://localhost:3000/bar/hello
router.post("/hello",(req, res) => {
    res.send('It is POST');
});

// curl -X GET http://localhost:3000/bar/hi
router.get('/hi', function(req, res, next) {
    res.send('It is GET');
});

module.exports = router;

express-post-server.js:

const express = require('express');
const bar = require('./express-post');
const app = express();

// curl -X GET http://localhost:3000/foo
app.get('/foo', function (req, res, next) {
    res.send('This is foo GET!');
});

// register
app.use('/bar', bar);

app.listen(3000);

For complete running example clone node-cheat and run node express-post.


问:
Unusual conversion from html to json file
I have a POC to deliver which entitle to convert html content into a json file. This means the json file needs to be in a specific format which I can't figure out how to display it. I have not working out how to format the nodeChild elements in the format requested, so I need help on this matter.

This is the HTML content:

```<code><body>
    <style>
        .myclass{padding-top:50px; left:0;}
    </style>

    <div id="maincontent">
      <div id="myid">
          <p class="myclass">
              This is a paragraph
          </div>
      </div>
</body>
</code>```

And this is the .json format I need to be expelled out from the HTML content:

"t" stands for "type:, "s" stands for "style" and "h" stands for "html"

```<code>[
{
    "t": "s",
    "s": ".myclass{padding-top:50px; left:0;}"
},
{
    "t": "h",
    "h": "<div id='myid'><p class='myclass'>This is a paragraph</p></div>"
}]
</code>```

At the moment the file generated looks like this. But I need to place all the content in an unique line and not separated.

```<code>{
            "t": "DIV",
            "content": [{
                "t": "DIV",
                "content": ["This is a paragraph"],
                "s": {
                    "class": "myclass"
                }
            }],
        }
</code>```

Any help will be appreciated.

答:
Here is one way to do it, using the node-html-parser library and Array.prototype.reduce():</p>

```<code>// Don't forget to `npm i -S node-html-parser`
const HTMLParser = require("node-html-parser");

const root = HTMLParser.parse(
  `<!DOCTYPE html>
              <html>
                <head> </head>
                <body>
                  <style>
                    .myclass {
                      padding-top: 50px;
                      left: 0;
                    }
                  </style>

                  <script>
                    var name = 'world';
                    console.log('Hello ' + name);
                  </script>

                  <div id="maincontent">
                    <div id="myid">
                      <p class="myclass">
                        This is a paragraph
                      </p>
                    </div>
                  </div>
                </body>
              </html>`,
  {
    style: true, // Keep styles
    script: true // Keep scripts
  }
).querySelector("body");

// Clean up whitespace text nodes
root.removeWhitespace();

const result = root.childNodes.reduce((res, node) => {
  // Get the last group (`h`, `s` or `j`)
  const previousGroup = res.slice(-1).pop();
  // Get the type and content for this node
  const { type, propertyName, content } = getProperties(node);

  // If previousGroup exists and it's of the same type
  if (previousGroup && previousGroup.t === type) {
    // Add the content to it
    previousGroup[propertyName] += content;
  } else {
    // Otherwise, create a new group
    res.push({ t: type, [propertyName]: content });
  }

  return res;
}, []);

function getProperties(node) {
  switch (node.tagName) {
    case "style":
      return { type: "s", propertyName: "s", content: node.rawText.replace(/\s+/g, " ") };
    case "script":
      return { type: "j", propertyName: "s", content: node.rawText };
    default:
      return { type: "h", propertyName: "h", content: node.innerHTML };
  }
}

console.log(result);
// Returns:
// [
//   { t: 's', s: '.myclass { padding-top: 50px; left: 0; }' },
//   { t: 'j', s: 'var name = \'world\';\n            console.log(\'Hello \' + name);' },
//   { t: 'h', h: '<div id="myid"><p class="myclass">This is a paragraph</p></div>' }
// ]
</code>```

Body:
I have a POC to deliver which entitle to convert html content into a json file. This means the json file needs to be in a specific format which I can't figure out how to display it. I have not working out how to format the nodeChild elements in the format requested, so I need help on this matter.

This is the HTML content:

              This is a paragraph

And this is the .json format I need to be expelled out from the HTML content:

"t" stands for "type:, "s" stands for "style" and "h" stands for "html"

[
{
    "t": "s",
    "s": ".myclass{padding-top:50px; left:0;}"
},
{
    "t": "h",
    "h": "

This is a paragraph

"
}]

At the moment the file generated looks like this. But I need to place all the content in an unique line and not separated.

{
            "t": "DIV",
            "content": [{
                "t": "DIV",
                "content": ["This is a paragraph"],
                "s": {
                    "class": "myclass"
                }
            }],
        }

Any help will be appreciated.

Body:
Here is one way to do it, using the node-html-parser library and Array.prototype.reduce():

// Don't forget to `npm i -S node-html-parser`
const HTMLParser = require("node-html-parser");

const root = HTMLParser.parse(
  `<!DOCTYPE html>
              <html>
                <head> </head>
                <body>
                  <style>
                    .myclass {
                      padding-top: 50px;
                      left: 0;
                    }
                  </style>

                  <script>
                    var name = 'world';
                    console.log('Hello ' + name);
                  </script>

                  <div id="maincontent">
                    <div id="myid">
                      <p class="myclass">
                        This is a paragraph
                      </p>
                    </div>
                  </div>
                </body>
              </html>`,
  {
    style: true, // Keep styles
    script: true // Keep scripts
  }
).querySelector("body");

// Clean up whitespace text nodes
root.removeWhitespace();

const result = root.childNodes.reduce((res, node) => {
  // Get the last group (`h`, `s` or `j`)
  const previousGroup = res.slice(-1).pop();
  // Get the type and content for this node
  const { type, propertyName, content } = getProperties(node);

  // If previousGroup exists and it's of the same type
  if (previousGroup && previousGroup.t === type) {
    // Add the content to it
    previousGroup[propertyName] += content;
  } else {
    // Otherwise, create a new group
    res.push({ t: type, [propertyName]: content });
  }

  return res;
}, []);

function getProperties(node) {
  switch (node.tagName) {
    case "style":
      return { type: "s", propertyName: "s", content: node.rawText.replace(/\s+/g, " ") };
    case "script":
      return { type: "j", propertyName: "s", content: node.rawText };
    default:
      return { type: "h", propertyName: "h", content: node.innerHTML };
  }
}

console.log(result);
// Returns:
// [
//   { t: 's', s: '.myclass { padding-top: 50px; left: 0; }' },
//   { t: 'j', s: 'var name = \'world\';\n            console.log(\'Hello \' + name);' },
//   { t: 'h', h: '<div id="myid"><p class="myclass">This is a paragraph</p></div>' }
// ]


问:
Group objects by one of its params with javascript
Basically I would want to transform this

```<code>[
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
]
</code>```

To this where every object with the key of  0 would go into the first array and every object with the key of 1 would go into the second array.

```<code>[
  [
    { key: 0, name: 'Some name' },
    { key: 0, name: 'Some name' },
  ],
  [
    { key: 1, name: 'Some name' },
    { key: 1, name: 'Some name' },
  ],
];
</code>```

Would really not mind using lodash for this but couldn't find the correct array method.

答:
You should be able to use Array.reduce for this purpose

lodash offers the groupBy function which suits this application nicely.

For example:

let a = [
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
];

let res = Object.values(a.reduce((acc, r) => {
    acc[r.key] = (acc[r.key] || []).concat([r]);
    return acc;
}, {}));

console.log("Result:",res);

// You can also use lodash groupBy (which is more concise)
console.log("Using lodash:",Object.values(_.groupBy(a, "key")))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script></code>```

Body:
Basically I would want to transform this

[
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
]

To this where every object with the key of  0 would go into the first array and every object with the key of 1 would go into the second array.

[
  [
    { key: 0, name: 'Some name' },
    { key: 0, name: 'Some name' },
  ],
  [
    { key: 1, name: 'Some name' },
    { key: 1, name: 'Some name' },
  ],
];

Would really not mind using lodash for this but couldn't find the correct array method.

Body:
You should be able to use Array.reduce for this purpose

lodash offers the groupBy function which suits this application nicely.

For example:

let a = [
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
];

let res = Object.values(a.reduce((acc, r) => {
    acc[r.key] = (acc[r.key] || []).concat([r]);
    return acc;
}, {}));

console.log("Result:",res);

// You can also use lodash groupBy (which is more concise)
console.log("Using lodash:",Object.values(_.groupBy(a, "key")))

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>


问:
Using XSL to move from one node to another
So I want to convert the following using XSL

```<code><doc>
    <data id="priority" level="2" include="true">
        <name>Priority</name>
    </data>
    <data id="cost" level="1" leveltype="number">
        <name>Cost</name>
    </data>
    <data id="date" level="3" include="true">
        <name>Date</name>
    </data>
</doc>
</code>```

To this

```<code><doc>
    <data id="priority">
        <name>Priority</name>
    </data>
    <data id="cost">
        <name>Cost</name>
    </data>
    <data id="date">
        <name>Date</name>
    </data>

    <!-- ordering matters, though if necessary I can reorder this manually via the DOM instead of XSL -->
    <levels>
        <level id="cost" include="false" type="number"/>
        <level id="priority" include="true"/>
        <level id="date" include="true"/>
    </level>
</doc>
</code>```

Basically I want to take the level attributes and make them their own thing. A huge bonus would be if there were some way to remove the level number and use the order of the node instead to represent that.

答:
May be a simpler way:</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
    <doc>
        <xsl:for-each select="doc/data">
            <data>
                <xsl:attribute name="id">
                    <xsl:value-of select="@id"/>
                </xsl:attribute>
                <name><xsl:value-of select="name" /></name>
            </data>
        </xsl:for-each>
        <levels>
            <xsl:for-each select="doc/data">
                <xsl:sort select="@level" />
                <level>
                    <xsl:attribute name="id">
                        <xsl:value-of select="@id"/>
                    </xsl:attribute>
                    <xsl:choose>
                        <xsl:when test="@include='true'">
                            <xsl:attribute name="include">true</xsl:attribute>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:attribute name="include">false</xsl:attribute>
                        </xsl:otherwise>
                    </xsl:choose>
                </level>
            </xsl:for-each>
        </levels>
    </doc>
</xsl:template>
</xsl:stylesheet>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I want to convert the following using XSL

<doc>
    <data id="priority" level="2" include="true">
        <name>Priority</name>
    </data>
    <data id="cost" level="1" leveltype="number">
        <name>Cost</name>
    </data>
    <data id="date" level="3" include="true">
        <name>Date</name>
    </data>
</doc>

To this

<doc>
    <data id="priority">
        <name>Priority</name>
    </data>
    <data id="cost">
        <name>Cost</name>
    </data>
    <data id="date">
        <name>Date</name>
    </data>

    <levels>
        <level id="cost" include="false" type="number"/>
        <level id="priority" include="true"/>
        <level id="date" include="true"/>
    </level>
</doc>

Basically I want to take the level attributes and make them their own thing. A huge bonus would be if there were some way to remove the level number and use the order of the node instead to represent that.

Body:
May be a simpler way:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
    <doc>
        <xsl:for-each select="doc/data">
            <data>
                <xsl:attribute name="id">
                    <xsl:value-of select="@id"/>
                </xsl:attribute>
                <name><xsl:value-of select="name" /></name>
            </data>
        </xsl:for-each>
        <levels>
            <xsl:for-each select="doc/data">
                <xsl:sort select="@level" />
                <level>
                    <xsl:attribute name="id">
                        <xsl:value-of select="@id"/>
                    </xsl:attribute>
                    <xsl:choose>
                        <xsl:when test="@include='true'">
                            <xsl:attribute name="include">true</xsl:attribute>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:attribute name="include">false</xsl:attribute>
                        </xsl:otherwise>
                    </xsl:choose>
                </level>
            </xsl:for-each>
        </levels>
    </doc>
</xsl:template>
</xsl:stylesheet>


问:
Java TypesafeConfig generate config key and read its value
I am using Typesafeconfig in my project. I want to read the config and generates a value, which is again a config key and I want to read this config key's value.

Example:

```<code>fs {
  city = ${CITY}
  number = ${NUMBER}
  cityNumberKey = ${CITY}"_"${NUMBER}
  cityNumber = ${fs.cityNumberKey}
}
</code>```

In above example, the value of cityNumber is same as cityNumberKey. What I am actually trying to do is to read the value of cityNumberKey config.

Example, let's say if city is Delhi and Number is 31, then I want to read the value of config Delhi_31 in cityNumber object.

Appreciate any example for the same.

Thanks

答:
You can use,

reference.conf

```<code>fs {
    city = "Delhi"
    number = 31
}
</code>```

myconf.conf

```<code>conf {
    city = ${fs.city}
    number = ${fs.number}
    cityNumberKey = ${conf.city}"_"${conf.number}
    cityNumber = ${conf.cityNumberKey}
}
</code>```

TypesafeConfigTest.java

```<code>import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;

public class TypesafeConfigTest {

    public static void main(String[] args) {
        Config refConfig = ConfigFactory.parseResources("reference.conf").resolve();
        Config myConfConfig = ConfigFactory.parseResources("myconf.conf").withFallback(refConfig).resolve();
        System.out.println("name: " + refConfig.getString("fs.city"));
        System.out.println("title: " + refConfig.getString("fs.number"));
        System.out.println("cityNumberKey: " + myConfConfig.getString("conf.cityNumberKey"));
        System.out.println("cityNumber: " + myConfConfig.getString("conf.cityNumber"));
    }
}
</code>```

Edit 1 :

Using single configuration,

```<code>conf {
    city = "Delhi"
    number = 31
    cityNumberKey = ${conf.city}"_"${conf.number}
    cityNumber = ${conf.cityNumberKey}
}
</code>```

TypesafeConfigExamples.java

```<code>import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;

public class TypesafeConfigExamples {

    public static void main(String[] args) {
        Config refConfig = ConfigFactory.parseResources("myconf.conf").resolve();
        System.out.println("name: " + refConfig.getString("conf.city"));
        System.out.println("title: " + refConfig.getString("conf.number"));
        System.out.println("cityNumberKey: " + refConfig.getString("conf.cityNumberKey"));
        System.out.println("cityNumber: " + refConfig.getString("conf.cityNumber"));
    }
}
</code>```

Body:
I am using Typesafeconfig in my project. I want to read the config and generates a value, which is again a config key and I want to read this config key's value.

Example:

fs {
  city = ${CITY}
  number = ${NUMBER}
  cityNumberKey = ${CITY}"_"${NUMBER}
  cityNumber = ${fs.cityNumberKey}
}

In above example, the value of cityNumber is same as cityNumberKey. What I am actually trying to do is to read the value of cityNumberKey config.

Example, let's say if city is Delhi and Number is 31, then I want to read the value of config Delhi_31 in cityNumber object.

Appreciate any example for the same.

Thanks

Body:
You can use,

reference.conf

fs {
    city = "Delhi"
    number = 31
}

myconf.conf

conf {
    city = ${fs.city}
    number = ${fs.number}
    cityNumberKey = ${conf.city}"_"${conf.number}
    cityNumber = ${conf.cityNumberKey}
}

TypesafeConfigTest.java

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;

public class TypesafeConfigTest {

    public static void main(String[] args) {
        Config refConfig = ConfigFactory.parseResources("reference.conf").resolve();
        Config myConfConfig = ConfigFactory.parseResources("myconf.conf").withFallback(refConfig).resolve();
        System.out.println("name: " + refConfig.getString("fs.city"));
        System.out.println("title: " + refConfig.getString("fs.number"));
        System.out.println("cityNumberKey: " + myConfConfig.getString("conf.cityNumberKey"));
        System.out.println("cityNumber: " + myConfConfig.getString("conf.cityNumber"));
    }
}

Edit 1 :

Using single configuration,

conf {
    city = "Delhi"
    number = 31
    cityNumberKey = ${conf.city}"_"${conf.number}
    cityNumber = ${conf.cityNumberKey}
}

TypesafeConfigExamples.java

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;

public class TypesafeConfigExamples {

    public static void main(String[] args) {
        Config refConfig = ConfigFactory.parseResources("myconf.conf").resolve();
        System.out.println("name: " + refConfig.getString("conf.city"));
        System.out.println("title: " + refConfig.getString("conf.number"));
        System.out.println("cityNumberKey: " + refConfig.getString("conf.cityNumberKey"));
        System.out.println("cityNumber: " + refConfig.getString("conf.cityNumber"));
    }
}


问:
My Joomla site shows PHP error: failed to open stream
I am working on a Joomla site, and just recently updated PHP to 7.2, but my site started throwing errors. I have also updated Joomla to the latest version, but errors still appear. I'm not good in PHP and don't know how to fix it.

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; Color has a deprecated constructor in /public_html/templates/jf_social/features/color.php on line 11

Warning: require_once(/public_html/libraries/joomla/document/html/renderer/head.php): failed to open stream: No such file or directory in /public_html/templates/jf_social/error.php on line 52

Fatal error: require_once(): Failed opening required '/public_html/libraries/joomla/document/html/renderer/head.php' (include_path='.:/php:/opt/cpanel/ea-php73/root/usr/share/pear') in /public_html/templates/jf_social/error.php on line 52```

I think error comes from my Joomla template, I am using this one https://www.joomforest.com/joomla/templates/jf-social

I can't receive support from that template developers, because my subscription is expired, and changing the template will take a lot of time for me,
can you please anyone advise how to fix it?

Thank you very much!

答:
Try to delete the line 52

```<code>require_once(/public_html/libraries/joomla/document/html/renderer/head.php)
</code>```

from the File

```<code>/public_html/templates/jf_social/error.php
</code>```

The renderer/head.php doesnt be supported any more in your joomla version. If there are no more errors, everything is fine, if not your template is not supported any more.

Then go to the file

```<code>/public_html/templates/jf_social/features/color.php
</code>```

and edit the line

```<code>function Color($hex){
</code>```

to

```<code>function __construct($hex){
</code>```

Body:
I am working on a Joomla site, and just recently updated PHP to 7.2, but my site started throwing errors. I have also updated Joomla to the latest version, but errors still appear. I'm not good in PHP and don't know how to fix it.

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; Color has a deprecated constructor in /public_html/templates/jf_social/features/color.php on line 11

Warning: require_once(/public_html/libraries/joomla/document/html/renderer/head.php): failed to open stream: No such file or directory in /public_html/templates/jf_social/error.php on line 52

Fatal error: require_once(): Failed opening required '/public_html/libraries/joomla/document/html/renderer/head.php' (include_path='.:/php:/opt/cpanel/ea-php73/root/usr/share/pear') in /public_html/templates/jf_social/error.php on line 52

I think error comes from my Joomla template, I am using this one https://www.joomforest.com/joomla/templates/jf-social

I can't receive support from that template developers, because my subscription is expired, and changing the template will take a lot of time for me,
can you please anyone advise how to fix it?

Thank you very much!

Body:
Try to delete the line 52

require_once(/public_html/libraries/joomla/document/html/renderer/head.php)

from the File

/public_html/templates/jf_social/error.php

The renderer/head.php doesnt be supported any more in your joomla version. If there are no more errors, everything is fine, if not your template is not supported any more.

Then go to the file

/public_html/templates/jf_social/features/color.php

and edit the line

function Color($hex){

to

function __construct($hex){


问:
How to alter a API response with Javascript
I wrote this little app that takes in a set of starwars characters and returns images in an array.

```<code>const app = require('express')();
const fetch = require('node-fetch');
const imageSearch = require('image-search-google');
const bodyParser = require('body-parser')

var urlencodedParser = bodyParser.urlencoded({ extended: true })
app.use(bodyParser.json())

const options = {page:1};

const getImages = (keywords) =>
 Promise.all(keywords.map(keyword => client.search(`${keyword} Wookieepedia`, options)))
 .then(data => firstResult = data.map(result => result[0].url));

 const fun = async () => {
     const res = await getImages(['yoda' , 'luke skywalker' , 'darth vader']);
     console.log(res);
 }

 fun()
</code>```

The result of the above code looks like this :

```<code>[ 'https://vignette.wikia.nocookie.net/starwars/images/d/d6/Yoda_SWSB.png/revision/latest?cb=20150206140125',
  'https://vignette.wikia.nocookie.net/starwars/images/d/d9/Luke-rotjpromo.jpg/revision/latest?cb=20091030151422',
  'https://vignette.wikia.nocookie.net/starwars/images/a/a3/ANOVOS_Darth_Vader_1.png/revision/latest?cb=20150128225029' ]
</code>```

But i would like a result where i can know which image belongs to which keyword.  Maybe a format like this or something similar :

```<code>[{<keyword> : <url>}]
</code>```

I tried this :

```<code>const getImages = (keywords) =>
 Promise.all(keywords.map(keyword => {return { [keyword] : [client.search(`${keyword} Wookieepedia`, options)]}    } ))
 .then(data => firstResult = data.map(result => result));

 const fun = async () => {
     const res = await getImages(['yoda' , 'luke skywalker' , 'darth vader']);
     console.log(res);
 }

 fun()
</code>```

Results were close but not good :

```<code>[ { yoda: [ [Promise] ] },
  { 'luke skywalker': [ [Promise] ] },
  { 'darth vader': [ [Promise] ] } ]
</code>```

答:
```<code>const getImages = (keywords) =>
 Promise.all(keywords.map(keyword => client.search(`${keyword} Wookieepedia`, options).then(result => [keyword, result])))
 .then(entries => Object.fromEntries(entries))
 .then(data => firstResult = data.map(result => result));

 const fun = async () => {
     const res = await getImages(['yoda' , 'luke skywalker' , 'darth vader']);
     console.log(res);
 }

 fun()
</code>```

Body:
I wrote this little app that takes in a set of starwars characters and returns images in an array.

const app = require('express')();
const fetch = require('node-fetch');
const imageSearch = require('image-search-google');
const bodyParser = require('body-parser')

var urlencodedParser = bodyParser.urlencoded({ extended: true })
app.use(bodyParser.json())

const options = {page:1};

const getImages = (keywords) =>
 Promise.all(keywords.map(keyword => client.search(`${keyword} Wookieepedia`, options)))
 .then(data => firstResult = data.map(result => result[0].url));

 const fun = async () => {
     const res = await getImages(['yoda' , 'luke skywalker' , 'darth vader']);
     console.log(res);
 }

 fun()

The result of the above code looks like this :

[ 'https://vignette.wikia.nocookie.net/starwars/images/d/d6/Yoda_SWSB.png/revision/latest?cb=20150206140125',
  'https://vignette.wikia.nocookie.net/starwars/images/d/d9/Luke-rotjpromo.jpg/revision/latest?cb=20091030151422',
  'https://vignette.wikia.nocookie.net/starwars/images/a/a3/ANOVOS_Darth_Vader_1.png/revision/latest?cb=20150128225029' ]

But i would like a result where i can know which image belongs to which keyword.  Maybe a format like this or something similar :

[{<keyword> : <url>}]

I tried this :

const getImages = (keywords) =>
 Promise.all(keywords.map(keyword => {return { [keyword] : [client.search(`${keyword} Wookieepedia`, options)]}    } ))
 .then(data => firstResult = data.map(result => result));

 const fun = async () => {
     const res = await getImages(['yoda' , 'luke skywalker' , 'darth vader']);
     console.log(res);
 }

 fun()

Results were close but not good :

[ { yoda: [ [Promise] ] },
  { 'luke skywalker': [ [Promise] ] },
  { 'darth vader': [ [Promise] ] } ]


问:
How to let the textbox drop strings started with an Arabic character (semi each other) as it does in capital and small characters in default language?
In textbox autocomplete properties when i entered a character like 'm' it dropped all strings start with 'm' or 'M' but when i write a character 'أ' (this is an Arabic character) it dropped only string start with 'أ' , I want when i typed 'أ' or 'ا' or 'إ' or 'آ' it drop all strings start with any character from those not the typed character only , in C# windows application I'm not using ASP.net
Any suggestions???? </p>

答:
I am quite surprised to see that neither the text box control nor the auto complete string collection has a way to specify what defines string equality for the auto-complete mechanism. The only way I can think of to get the behavior that you want would be to create your own auto-complete mechanism.

I have done this several times in the past, before the functionality was supplied by the framework, and it is not difficult.

Just use an editable ComboBox instead of a TextBox, and handle the TextChanged event to create the autocompletions.

Here is some untried pseudocode of the procedure:

```<code>bool textChangedProgramatically = false;
List<string> myStrings; // The list of items that can appear in the auto-complete.

private static myComboBox_TextChanged(object sender, EventArgs args)
{
    if (textChangedProgramatically)
        return;

    string searchText = myComboBox.Text;

    // Use appropriate culturally-sensative string StartsWith comparisons
    List<string> matchingItems = GetMatchingStrings(searchText, myStrings);

    string firstMatch;
    if (matchingItems.Length > 0)
        firstMatch = matchingItems[0];
    else
        firstMatch = string.Empty;

    myComboBox.Items.Clear;
    myComboBox.Items.AddRange(matchingItems);

    string fulltext = searchText;
    if (firstMatch.Length > fullText.Length)
    {
        fullText = fullText + firstMatch.Substring(fullText.Length);
        textChangeProgramatically = true;
        myComboBox.Text = fullText;
        myComboBox.SelectionStart = searchText.Length;
        myComboBox.SelectionLength = fullText.Length - searchText.Length;
        textChangeProgramatically = false;
    }
}
</code>```

The trick is to get the right matching behavior in GetMatchingStrings. You may want to use string compatibility normalization to get the Arabic characters into non-presentation forms before doing the comparison, but I expect the right SubString overload might handle all of these cases for you.

Body:
I am quite surprised to see that neither the text box control nor the auto complete string collection has a way to specify what defines string equality for the auto-complete mechanism. The only way I can think of to get the behavior that you want would be to create your own auto-complete mechanism.

I have done this several times in the past, before the functionality was supplied by the framework, and it is not difficult.

Just use an editable ComboBox instead of a TextBox, and handle the TextChanged event to create the autocompletions.

Here is some untried pseudocode of the procedure:

bool textChangedProgramatically = false;
List<string> myStrings; // The list of items that can appear in the auto-complete.

private static myComboBox_TextChanged(object sender, EventArgs args)
{
    if (textChangedProgramatically)
        return;

    string searchText = myComboBox.Text;

    // Use appropriate culturally-sensative string StartsWith comparisons
    List<string> matchingItems = GetMatchingStrings(searchText, myStrings);

    string firstMatch;
    if (matchingItems.Length > 0)
        firstMatch = matchingItems[0];
    else
        firstMatch = string.Empty;

    myComboBox.Items.Clear;
    myComboBox.Items.AddRange(matchingItems);

    string fulltext = searchText;
    if (firstMatch.Length > fullText.Length)
    {
        fullText = fullText + firstMatch.Substring(fullText.Length);
        textChangeProgramatically = true;
        myComboBox.Text = fullText;
        myComboBox.SelectionStart = searchText.Length;
        myComboBox.SelectionLength = fullText.Length - searchText.Length;
        textChangeProgramatically = false;
    }
}

The trick is to get the right matching behavior in GetMatchingStrings. You may want to use string compatibility normalization to get the Arabic characters into non-presentation forms before doing the comparison, but I expect the right SubString overload might handle all of these cases for you.


问:
Test slice with @WebMvcTest is loading a substantial amount of controllers unrelated with the target
I have a spring boot application yielding numerous controllers and my goal is to create an integration test for a specific one. I read that we can achieve a test slice with the @WebMvcTest annotation that loads only what is necessary to deploy the target controller, is this assumption correct? Here is my test:

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(
        controllers = {DummyController.class},
)
public class DummyControllerIT {

    @Autowired
    private MockMvc mockMvc;

...
</code>```

Unfortunately the execution attempts to deploy other controllers/services/repositories that have no relation to the target Controller, which forces me use @MockBean on each of them. I was under the impression that @WebMvcTest would spare me from having an extensive listing of declared controllers/services/repositories with the @MockBean annotation, am I wrong?

If I misinterpreted this and I am expected to use @MockBean on unrelated parts of the application, then why is it better to use @WebMvcTest instead of @SpringBootTest? On the other hand, if I interpreted it correctly  what am I missing?

Not sure if it is related but this is my initialiser:

```<code>@ComponentScan(scopedProxy = ScopedProxyMode.INTERFACES)
@SpringBootApplication
@EnableTransactionManagement
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableScheduling
@EnableCaching
@EnableJpaAuditing
@EnableJpaRepositories(repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class)
public class Application extends SpringBootServletInitializer {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    @Bean
    @Primary
    public TaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(Integer.parseInt(Objects.requireNonNull(env.getProperty("coreThreadPoolSize"))));
        executor.setMaxPoolSize(Integer.parseInt(Objects.requireNonNull(env.getProperty("maxThreadPoolSize"))));
        executor.initialize();
        return executor;
    }

}
</code>```

Thank you for your help.

答:
@WebMvcTest works by disabling full auto-configuration of your application and also filtering its component scanning so that only the parts that are needed are configured. Your main class, Application, is enabling auto-configuration (via @SpringBootApplication) but is also explicitly enabling component scanning as well as caching, security, JPA repositories, etc. @WebMvcTest doesn't switch off these explicitly enabled pieces so you're left having to mock things.

This problem and the recommended way to avoid it is described in the reference documentation. In short, you should move the various @Enable… annotations to separate @Configuration classes that are picked up by component scanning. You may also want to review the need for some of them. For example, @EnableTransactionManagement is covered by auto-configuration.

Your use of @ComponentScan is also problematic as it switches off the filtering that @WebMvcTest requires. Moving it away from the @SpringBootApplication-annotated class should fix this part of the problem.

Body:
I have a spring boot application yielding numerous controllers and my goal is to create an integration test for a specific one. I read that we can achieve a test slice with the @WebMvcTest annotation that loads only what is necessary to deploy the target controller, is this assumption correct? Here is my test:

@RunWith(SpringRunner.class)
@WebMvcTest(
        controllers = {DummyController.class},
)
public class DummyControllerIT {

    @Autowired
    private MockMvc mockMvc;

...

Unfortunately the execution attempts to deploy other controllers/services/repositories that have no relation to the target Controller, which forces me use @MockBean on each of them. I was under the impression that @WebMvcTest would spare me from having an extensive listing of declared controllers/services/repositories with the @MockBean annotation, am I wrong?

If I misinterpreted this and I am expected to use @MockBean on unrelated parts of the application, then why is it better to use @WebMvcTest instead of @SpringBootTest? On the other hand, if I interpreted it correctly  what am I missing?

Not sure if it is related but this is my initialiser:

@ComponentScan(scopedProxy = ScopedProxyMode.INTERFACES)
@SpringBootApplication
@EnableTransactionManagement
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableScheduling
@EnableCaching
@EnableJpaAuditing
@EnableJpaRepositories(repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class)
public class Application extends SpringBootServletInitializer {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    @Bean
    @Primary
    public TaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(Integer.parseInt(Objects.requireNonNull(env.getProperty("coreThreadPoolSize"))));
        executor.setMaxPoolSize(Integer.parseInt(Objects.requireNonNull(env.getProperty("maxThreadPoolSize"))));
        executor.initialize();
        return executor;
    }

}

Thank you for your help.


问:
Visual Studio Design View - form is blank
I have a C# project with two forms. All compiles well. When I run the project, all forms are drawn as they are expected to.

A couple of days back, the DesignView of all forms started to shown nothing but a blank form, like the one you get in a new Windows.Forms project.

I went through several questions on SO with a similar problem, here are the comments to those questions:

there are no 3rd party libraries that my project uses (apart from htmlAgilityPack, which does not cause this problem in other Windows.Forms C# projects)

I have checked that the InitializeComponent function is only once in the project for each form

When I create a new Project and add an existing form (i.e. one of my problematic project forms), the Design Viewer works as expected - hence I suspect that the .cs, .Designer.cs and .resx files of my forms are OK.

Is there something I could have messed up in the project settings or somewhere else?

EDIT

The third point above is misleading - I tried creating a new project for the second form as well and there the problem persist. The minimal amount of source code that shows the problem is to to be found here.

答:
Another possibility:
The designer seems to try to design the first class in the .h file, no matter what's its name.
I just had an empty forward ref class declaration before the actual form class, and it tried use that.</p>


问:
Where does 'Hello world' come from?
'hello, world' is usually the first example for any programming language. I've always wondered where this sentence came from and where was it first used.

I've once been told that it was the first sentence ever to be displayed on a computer screen, but I've not been able to find any reference to this.

So my question is:

Where does the practice to use 'hello, world' as the first example for computer languages originate from?

Where was it first used?

Update

Although the answers are quite interesting, I should have noted that I had read the Wikipedia article. It does answer the question about the first use in literature, but does not answer when 'hello world' was first used.

So I think that it is safe to conclude that it was not the first sentence ever to be displayed on a computer screen and that there is no record about when it was first used?

答: First time I came across it in print was (I think) the first edition of K&R, so tha would have been circa 1982, but I'd been writing my own "Hello world" programs long before that, as had everyone else. </p>

OwnerDisplayName: Jacco

Title: Where does 'Hello world' come from?

LastEditorDisplayName: Jacco

OwnerDisplayName: anon

ContentLicense: CC BY-SA 2.5


问:
CSV file import problem in ms access
I have been trying to import a csv file to access and appending it to a table. It only imports some of the rows and stops arbitarily. All the lines in the csv file are in the same format. HAs anyone encounntred this problem? how can I fix it?</p>

答: Make sure text data is quote-encapsulated.  You may have some text fields containing commas that can throw off the record layout and hose the entire import.</p>

Title: CSV file import problem in ms access


问:
grep command or awk to get particular data
i have a large text file

```<code>https://www.google.com/
https://www.google.com/hello?url=xxxxxx
https://www.google.com/admin?x=y&file=zzz
https://www.google.com/abc.png
https://www.google.com//abc.png
https://www.google.com/abc.svg
https://www.google.com/abc.jpg
https://www.google.com/admin?x=aaa&file=yyyy
https://www.google.com/hello?
</code>```

all i want is urls with paramaters but same parameters shouldn't be their with different value

```<code>https://www.google.com/hello?url=xxxxxx
https://www.google.com/admin?x=y&file=zzz
</code>```

i want this result

答:
You can use an associative array in awk to check whether you have seen the URI before, and so just print the first instance:

```<code>$ cat bar.txt
https://www.google.com/
https://www.google.com/hello?url=xxxxxx
https://www.google.com/admin?x=y&file=zzz
https://www.google.com/abc.png
https://www.google.com//abc.png
https://www.google.com/abc.svg
https://www.google.com/abc.jpg
https://www.google.com/admin?x=aaa&file=yyyy
https://www.google.com/hello?
$ awk -F? '$2 != "" && !already_seen[$1]++' bar.txt
https://www.google.com/hello?url=xxxxxx
https://www.google.com/admin?x=y&file=zzz
</code>```

Body:
i have a large text file

https://www.google.com/
https://www.google.com/hello?url=xxxxxx
https://www.google.com/admin?x=y&file=zzz
https://www.google.com/abc.png
https://www.google.com//abc.png
https://www.google.com/abc.svg
https://www.google.com/abc.jpg
https://www.google.com/admin?x=aaa&file=yyyy
https://www.google.com/hello?

all i want is urls with paramaters but same parameters shouldn't be their with different value

https://www.google.com/hello?url=xxxxxx
https://www.google.com/admin?x=y&file=zzz

i want this result

Body:
You can use an associative array in awk to check whether you have seen the URI before, and so just print the first instance:

$ cat bar.txt
https://www.google.com/
https://www.google.com/hello?url=xxxxxx
https://www.google.com/admin?x=y&file=zzz
https://www.google.com/abc.png
https://www.google.com//abc.png
https://www.google.com/abc.svg
https://www.google.com/abc.jpg
https://www.google.com/admin?x=aaa&file=yyyy
https://www.google.com/hello?
$ awk -F? '$2 != "" && !already_seen[$1]++' bar.txt
https://www.google.com/hello?url=xxxxxx
https://www.google.com/admin?x=y&file=zzz


问:
How to restart my minikube kubernetes cluster in AWS instance, after stopping and starting that instance?
I had a t2.micro server running where i had deployed Minikube, however due to memory issue i scared up the server size. For which i had to stop and start the instance.

But now after restarting, when i try with kubectl commands i get the below error.

```<code>root@ip-172-31-23-231:~# kubectl get nodes
The connection to the server 172.31.23.231:6443 was refused - did you
specify the right host or port?
</code>```

So, how can i bring my earlier kube cluster up once i restart my AWS instance?

答:
check this :
run -> minikube status

```<code>host: Running
kubelet: Running
apiserver: Running
kubectl: Correctly Configured: ...
</code>```

if isn't running -> minikube start

then check the dashboard -> minikube dashboard

Body:
I had a t2.micro server running where i had deployed Minikube, however due to memory issue i scared up the server size. For which i had to stop and start the instance.

But now after restarting, when i try with kubectl commands i get the below error.

root@ip-172-31-23-231:~# kubectl get nodes
The connection to the server 172.31.23.231:6443 was refused - did you
specify the right host or port?

So, how can i bring my earlier kube cluster up once i restart my AWS instance?

Body:
check this :
run -> minikube status

host: Running
kubelet: Running
apiserver: Running
kubectl: Correctly Configured: ...

if isn't running -> minikube start

then check the dashboard -> minikube dashboard


问:
IE Browser - Powershell script to add site to trusted sites list, disable protected mode & make all zones security level low
For our website to run we need to:

add site to trusted sites list [Solved]

disable IE protected mode [Solved]

bring down security level for all zones. [facing Issue]

I am automating this site. As a prerequisite i have to take care of security features.

I have create below code. But i am not able to set security level to zero. I can't find 1A10 in zones.

I am adding solved issues code as well. Hoping it might help someone in need

Helpful sites -

https://x86x64.wordpress.com/2014/05/20/powershell-ie-zones-protected-mode-state/
https://support.microsoft.com/en-in/help/182569/internet-explorer-security-zones-registry-entries-for-advanced-users
https://blogs.technet.microsoft.com/heyscriptingguy/2015/04/02/update-or-add-registry-key-value-with-powershell/

```<code>#1. Add site to trusted sites

#Setting IExplorer settings
Write-Verbose "Now configuring IE"

#Navigate to the domains folder in the registry
set-location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
set-location ZoneMap\Domains

#Create a new folder with the website name
new-item testsite.site.com/ -Force #website part without https
set-location testsite.site.com/
new-itemproperty . -Name https -Value 2 -Type DWORD -Force

Write-Host "Site added Successfully"
Start-Sleep -s 2

# 2. Disable IE protected mode

# Disabling protected mode and making level 0

#Zone 0 – My Computer
#Zone 1 – Local Intranet Zone
#Zone 2 – Trusted sites Zone
#Zone 3 – Internet Zone
#Zone 4 – Restricted Sites Zone

#“2500” is the value name representing “Protected Mode” tick. 3 means Disabled, 0 – Enabled

#Disable protected mode for all zones
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1" -Name 2500 -Value "3"
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\2" -Name 2500 -Value "3"
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3" -Name 2500 -Value "3"
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\4" -Name 2500 -Value "3"

Write-Host "IE protection mode turned Off successfully"
Start-Sleep -s 2

# 3. Bring down security level for all zones

#Set Level 0 for low
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1" -Name 1A10 -Value "0"
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\2" -Name 1A10 -Value "0"
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3" -Name 1A10 -Value "0"
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\4" -Name 1A10 -Value "0"

Stop-Process -name explorer
</code>```

Thanks in Advance Guys!!

答:
just remove "0" and replace with 0 it worked for me.</p>

```<code>Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\2" -Name 1A10 -Value 0
</code>```

Body:
For our website to run we need to:

add site to trusted sites list [Solved]

disable IE protected mode [Solved]

bring down security level for all zones. [facing Issue]

I am automating this site. As a prerequisite i have to take care of security features.

I have create below code. But i am not able to set security level to zero. I can't find 1A10 in zones.

I am adding solved issues code as well. Hoping it might help someone in need

Helpful sites -

https://x86x64.wordpress.com/2014/05/20/powershell-ie-zones-protected-mode-state/
https://support.microsoft.com/en-in/help/182569/internet-explorer-security-zones-registry-entries-for-advanced-users
https://blogs.technet.microsoft.com/heyscriptingguy/2015/04/02/update-or-add-registry-key-value-with-powershell/

#1. Add site to trusted sites

#Setting IExplorer settings
Write-Verbose "Now configuring IE"

#Navigate to the domains folder in the registry
set-location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
set-location ZoneMap\Domains

#Create a new folder with the website name
new-item testsite.site.com/ -Force #website part without https
set-location testsite.site.com/
new-itemproperty . -Name https -Value 2 -Type DWORD -Force

Write-Host "Site added Successfully"
Start-Sleep -s 2

# 2. Disable IE protected mode

# Disabling protected mode and making level 0

#Zone 0 – My Computer
#Zone 1 – Local Intranet Zone
#Zone 2 – Trusted sites Zone
#Zone 3 – Internet Zone
#Zone 4 – Restricted Sites Zone

#“2500” is the value name representing “Protected Mode” tick. 3 means Disabled, 0 – Enabled

#Disable protected mode for all zones
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1" -Name 2500 -Value "3"
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\2" -Name 2500 -Value "3"
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3" -Name 2500 -Value "3"
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\4" -Name 2500 -Value "3"

Write-Host "IE protection mode turned Off successfully"
Start-Sleep -s 2

# 3. Bring down security level for all zones

#Set Level 0 for low
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1" -Name 1A10 -Value "0"
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\2" -Name 1A10 -Value "0"
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3" -Name 1A10 -Value "0"
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\4" -Name 1A10 -Value "0"

Stop-Process -name explorer

Thanks in Advance Guys!!

Body:
just remove "0" and replace with 0 it worked for me.

Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\2" -Name 1A10 -Value 0


问:
How to get IMEI in android 10
For security purposes, I want to store the IMEI number of app users but I am getting the following error

```<code>2020-02-14 13:29:36.620 14794-14794/com.udaan.android.creditoperations E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.udaan.android.creditoperations, PID: 14794
    java.lang.SecurityException: getImeiForSlot: The user 10643 does not meet the requirements to access device identifiers.
        at android.os.Parcel.createException(Parcel.java:2071)
        at android.os.Parcel.readException(Parcel.java:2039)
        at android.os.Parcel.readException(Parcel.java:1987)
        at com.android.internal.telephony.ITelephony$Stub$Proxy.getImeiForSlot(ITelephony.java:10471)
        at android.telephony.TelephonyManager.getImei(TelephonyManager.java:1754)
        at android.telephony.TelephonyManager.getImei(TelephonyManager.java:1715)
</code>```

Is there any way to access IMEI number including latest android devices?

答:
Starting from Android 10, Third-party apps installed from the Google Play Store cannot get IMEI number.
That's why you are getting this Security Exception.

I would suggest you use any other unique id for your purpose. For best practices of unique identifiers recommended by Google, you can check out the below link

https://developer.android.com/training/articles/user-data-ids

Title: How to get IMEI in android 10

Body:
For security purposes, I want to store the IMEI number of app users but I am getting the following error

2020-02-14 13:29:36.620 14794-14794/com.udaan.android.creditoperations E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.udaan.android.creditoperations, PID: 14794
    java.lang.SecurityException: getImeiForSlot: The user 10643 does not meet the requirements to access device identifiers.
        at android.os.Parcel.createException(Parcel.java:2071)
        at android.os.Parcel.readException(Parcel.java:2039)
        at android.os.Parcel.readException(Parcel.java:1987)
        at com.android.internal.telephony.ITelephony$Stub$Proxy.getImeiForSlot(ITelephony.java:10471)
        at android.telephony.TelephonyManager.getImei(TelephonyManager.java:1754)
        at android.telephony.TelephonyManager.getImei(TelephonyManager.java:1715)

Is there any way to access IMEI number including latest android devices?


问:
Regex to match URL route
I'm writing a regex to match a route with the pattern /events/awesome-schema/value2/1.

The values could be described as:

```<code>/events >> static part
awesome-schema >> could be any char, number, _ or -
value2 >> could be any char, number, _ or -
1 >> one or more digit
</code>```

For now, I have wrote the following syntax ^/events/([a-z]+[0-9_-]*)/?([a-z]+[0-9_-]*)?/?(\d+)?$ but it's failing.

Any idea why is it wrong?

答:
It fail because ([a-z]+[0-9_-]*) will match as much lower case letter as it can, than only [0-9_-] these characters could match. Which will match the -, but the remaining string is schema/value2/1 but your pattern try to match / char now, but the next character is the character s at this point in your example.

This fix it ^/events/([a-z0-9_-]*)/([a-z0-9_-]*)/(\d+)$

Title: Regex to match URL route

Body:
I'm writing a regex to match a route with the pattern /events/awesome-schema/value2/1.

The values could be described as:

/events >> static part
awesome-schema >> could be any char, number, _ or -
value2 >> could be any char, number, _ or -
1 >> one or more digit

For now, I have wrote the following syntax ^/events/([a-z]+[0-9_-]*)/?([a-z]+[0-9_-]*)?/?(\d+)?$ but it's failing.

Any idea why is it wrong?


问:
ERROR: pull access denied for postgress, repository does not exist or may require 'docker login': denied: requested access to the resource is denied
While learning Docker using Django I got some problem related to installing PostgreSQL in Linux Mint.

This is the code from file docker-compose.yml

```<code>version: '3.7'

services:
    web:
        build: .
        command: python /code/manage.py runserver 0.0.0.0:8000
        volumes:
            - .:/code
        ports:
            - 8000:8000
        depends_on:
            - db

    db:
        image: postgress:11
</code>```

Error that I'm receiving while firing docker-compose up -d command

```<code>Pulling db (postgress:)...
ERROR: The image for the service you're trying to recreate has been removed. If you continue, volume data could be lost. Consider backing up your data before continuing.

Continue with the new image? [yN]y
Pulling db (postgress:)...
ERROR: pull access denied for postgress, repository does not exist or may require 'docker login': denied: requested access to the resource is denied

</code>```

This error still raises after login in docker.

答:
I don't think there is an issue related to docker-login instead you've a typo in your file at image name which is postgress:11 (extra s)

see: https://hub.docker.com/_/postgres

Updated compose file

```<code>version: '3.7'

services:
    web:
        build: .
        command: python /code/manage.py runserver 0.0.0.0:8000
        volumes:
            - .:/code
        ports:
            - 8000:8000
        depends_on:
            - db

    db:
        image: postgres:11
</code>```

Body:
While learning Docker using Django I got some problem related to installing PostgreSQL in Linux Mint.

This is the code from file docker-compose.yml

version: '3.7'

services:
    web:
        build: .
        command: python /code/manage.py runserver 0.0.0.0:8000
        volumes:
            - .:/code
        ports:
            - 8000:8000
        depends_on:
            - db

    db:
        image: postgress:11

Error that I'm receiving while firing docker-compose up -d command

Pulling db (postgress:)...
ERROR: The image for the service you're trying to recreate has been removed. If you continue, volume data could be lost. Consider backing up your data before continuing.

Continue with the new image? [yN]y
Pulling db (postgress:)...
ERROR: pull access denied for postgress, repository does not exist or may require 'docker login': denied: requested access to the resource is denied

This error still raises after login in docker.

Body:
I don't think there is an issue related to docker-login instead you've a typo in your file at image name which is postgress:11 (extra s)

see: https://hub.docker.com/_/postgres

Updated compose file

version: '3.7'

services:
    web:
        build: .
        command: python /code/manage.py runserver 0.0.0.0:8000
        volumes:
            - .:/code
        ports:
            - 8000:8000
        depends_on:
            - db

    db:
        image: postgres:11


问:
Howto: Live Validation with jQuery and Rails
i was wondering if there is a plugin/gem for live validatio with jquery.
I alreay knew some jquery plugins, but is there something out there which make use of ActiveRecord?

g.

答: checkout http://github.com/bcardarella/client_side_validations. Tutorial available at http://railscasts.com/episodes/263-client-side-validations</p>


问:
Create a new column for data-table based on filtered value
I want to filter a column and simultaneously create a new column for an existing data.table based on values of other columns on the earlier subset. Below is such an example -

library(data.table)
X <- data.table(id = 1:5, L = letters[1:5])
X[id > 2, 'ss' := paste(id, L)]
X
   id L   ss
1:  1 a <NA>
2:  2 b <NA>
3:  3 c  3 c
4:  4 d  4 d
5:  5 e  5 e
```

However, as you see this is not returning the subset i.e. row number 3 through 5, but the entire data table instead. Any pointer towards the correct and efficient approach will be highly appreciated.

答:
Probably, you can apply them separately.

```<code>library(data.table)

Y <- X[id > 2][,ss := paste(id, L)]
Y
#   id L  ss
#1:  3 c 3 c
#2:  4 d 4 d
#3:  5 e 5 e
</code>```

You can wrap na.omit to your attempt to remove NA values

```<code>na.omit(X[id > 2, 'ss' := paste(id, L)])
</code>```

Or subset again

```<code>X[id > 2, 'ss' := paste(id, L)][id > 2]
</code>```

Body:
I want to filter a column and simultaneously create a new column for an existing data.table based on values of other columns on the earlier subset. Below is such an example -

library(data.table)
X <- data.table(id = 1:5, L = letters[1:5])
X[id > 2, 'ss' := paste(id, L)]
X
   id L   ss
1:  1 a <NA>
2:  2 b <NA>
3:  3 c  3 c
4:  4 d  4 d
5:  5 e  5 e

However, as you see this is not returning the subset i.e. row number 3 through 5, but the entire data table instead. Any pointer towards the correct and efficient approach will be highly appreciated.

Body:
Probably, you can apply them separately.

library(data.table)

Y <- X[id > 2][,ss := paste(id, L)]
Y
#   id L  ss
#1:  3 c 3 c
#2:  4 d 4 d
#3:  5 e 5 e

You can wrap na.omit to your attempt to remove NA values

na.omit(X[id > 2, 'ss' := paste(id, L)])

Or subset again

X[id > 2, 'ss' := paste(id, L)][id > 2]


问:
Need to remove Header and footer from src url in iframe locally
First of all, I'm new to JS and Jquery.
I created two .html files in a same folder locally(Desktop), one is home.html with Header, Main content(Two para), and footer. Now in another file(detail.html), i used iframe and give home url in it.

```<code><iframe src="home.html" height="600" width="900" id="myframe"></iframe>
</code>```

And in script, i gave this,

```<code>    $("#myframe").contents().find("#site-header").remove();
</code>```

not only this i tried these too,

```<code>var frame = document.querySelector("myframe");
header = frame.contentDocument.querySelector("site-header");
header.remove();
</code>```

--

```<code>var iframe = document.getElementById("myframe");
var elmnt = iframe.contentWindow.document.getElementById("site-header");
elmnt.style.display = "none";
</code>```

Tried same for footer also but not working, its not removing the header and footer in iframe.
Please help me in this, Thanks in advance...

答:
Try using window on load

detail.html code below:

```<code><html>
<body>
<iframe src="home.html" height="600" width="900" id="myframe"></iframe>

<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

    <script>
        $(window).on("load",function(){
            $('#myframe').contents().find("#site-header").remove();
            $('#myframe').contents().find("#site-footer").remove();
        })
    </script>

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

home.html code below:

```<code><html>
<body>
    <div id="site-header">
        <h1>Header</h1>
    </div>

    <div class="body">
        <h1>My Body content goes here</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi consequuntur est fugiat itaque maxime quia. Aspernatur consequuntur, dolore earum est facilis in laborum numquam pariatur placeat quas, ut voluptatibus! Cupiditate deleniti excepturi quos. Atque incidunt iure quasi tempora? Accusamus accusantium delectus.</p>
    </div>

    <div id="site-footer">
        <h1>Footer</h1>
    </div>

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

Body:
First of all, I'm new to JS and Jquery.
I created two .html files in a same folder locally(Desktop), one is home.html with Header, Main content(Two para), and footer. Now in another file(detail.html), i used iframe and give home url in it.

And in script, i gave this,

    $("#myframe").contents().find("#site-header").remove();

not only this i tried these too,

var frame = document.querySelector("myframe");
header = frame.contentDocument.querySelector("site-header");
header.remove();

--

var iframe = document.getElementById("myframe");
var elmnt = iframe.contentWindow.document.getElementById("site-header");
elmnt.style.display = "none";

Tried same for footer also but not working, its not removing the header and footer in iframe.
Please help me in this, Thanks in advance...

Body:
Try using window on load

detail.html code below:

<html>
<body>
<iframe src="home.html" height="600" width="900" id="myframe"></iframe>

<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

    <script>
        $(window).on("load",function(){
            $('#myframe').contents().find("#site-header").remove();
            $('#myframe').contents().find("#site-footer").remove();
        })
    </script>

</body>
</html>

home.html code below:

<html>
<body>
    <div id="site-header">
        <h1>Header</h1>
    </div>

    <div class="body">
        <h1>My Body content goes here</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi consequuntur est fugiat itaque maxime quia. Aspernatur consequuntur, dolore earum est facilis in laborum numquam pariatur placeat quas, ut voluptatibus! Cupiditate deleniti excepturi quos. Atque incidunt iure quasi tempora? Accusamus accusantium delectus.</p>
    </div>

    <div id="site-footer">
        <h1>Footer</h1>
    </div>

</body>
</html>


问:
d3 v5 use nested values when scaling axis
I have the following code that nests my data based on region and date. The problem I am having is that I don't know how to define yScale to dynamically draw the axis so that the max sum from the nested data is returned (the max val of the nested data is higher than the max val in the dataset bc it is aggregated). Thus my yAxis is truncated and the chart doesn't show all the data.

In the code, if I hardcode the domain to .domain([0, 3500]) then the axis is correct, but otherwise it is not correct.  I don't want to hardcode the domain.  How do I reference the nested values?

EDITED to show code provided in comments, which helps but doesn't entirely fix when the script is run on the entire dataset. Please see pic at bottom.

```<code>      var yScale = d3.scaleLinear()
               .domain([0, d3.max(dataset, function(d) {
                  return parseInt(d.count,10);
                })])
               .range([h - padding, padding])

      // var yScale = d3.scaleLinear()
      //   .domain([0, 3500])
      //   .range([h - padding, padding]) //not supposed to hard code the scale but it is not working
</code>```

```<code><!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="utf-8">
    <title>Nested Chart</title>
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <style type="text/css">
      .pagebreak {
        page-break-before: always;
      }

      .axis path,
      .axis line {
        fill: none;
        stroke: black;
        shape-rendering: crispEdges;
      }

      .axis text {
        font-family: sans-serif;
        font-size: 11px;
      }

      .point {
        fill: none;
        size: 2px
      }

      .dot {
        fill: #ffab00;
        stroke: #fff;
        }

    </style>
  </head>

  <div style="width:800px; margin:0 auto;" class='body'></div>
  <div class="pagebreak"> </div>

  <body>

    <script type="text/javascript">
      var parseTime = d3.timeParse("%Y");

      var margin = {
          top: 20,
          right: 20,
          bottom: 30,
          left: 50
        },
        w = 960 - margin.left - margin.right,
        h = 500 - margin.top - margin.bottom;

      var padding = 20;

/////////////////get the data//////////////////
      const csv = `state,region,year,count
        Alabama,South,2010,1
        Alabama,South,2011,1
        Alabama,South,2012,0
        Alabama,South,2013,0
        Alabama,South,2014,2
        Alabama,South,2015,6
        Alaska,West,2010,2245
        Alaska,West,2011,1409
        Alaska,West,2012,1166
        Alaska,West,2013,1329
        Alaska,West,2014,1296
        Alaska,West,2015,1575
        Connecticut,Northeast,2010,0
        Connecticut,Northeast,2011,0
        Connecticut,Northeast,2012,0
        Connecticut,Northeast,2013,0
        Connecticut,Northeast,2014,0
        Connecticut,Northeast,2015,1
        Missouri,Midwest,2010,2
        Missouri,Midwest,2011,3
        Missouri,Midwest,2012,2
        Missouri,Midwest,2013,0
        Missouri,Midwest,2014,1
        Missouri,Midwest,2015,5
        California,West,2010,546
        California,West,2012,243
        California,West,2013,240
        Wyoming,West,2015,198
        California,West,2011,195
        California,West,2014,191`;

      const dataset = d3.csvParse(csv);

      dataset.forEach(function(d) {
        d.date = parseTime(d.year);
        d.region = d['region'];
        d.state = d['state'];
        d.count = d['count'];
        //console.log(d)
      });

      /////////////////scales the data//////////////////
      var xScale = d3.scaleTime()
        .domain([d3.min(dataset, function(d) {
          return d.date
        }), d3.max(dataset, function(d) {
          return d.date
        })]).range([padding, w - padding * 2])

      var yScale = d3.scaleLinear()
        .domain([0, d3.max(dataset, function(d) {
          console.log(d.count)
          return d.count ///ERROR HERE
        })]).range([h - padding, padding])

      // var yScale = d3.scaleLinear()
      //   .domain([0, 3500])
      //   .range([h - padding, padding]) //not supposed to hard code the scale but it is not working otherwise...commented out above

      var xAxis = d3.axisBottom().scale(xScale);

      var yAxis = d3.axisLeft().scale(yScale);

      /////////////////charts start here//////////////////

      var svg = d3.select("body").append("svg")
        .attr("width", w + margin.left + margin.right)
        .attr("height", h + margin.top + margin.bottom)
        .append("g")
        .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

      var svg1 = d3.select("body").append("svg")
        .attr("width", w + margin.left + margin.right)
        .attr("height", h + margin.top + margin.bottom)
        .append("g")
        .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

      //Define the line
      var valueLine = d3.line()
        .x(function(d) {
          return xScale(new Date(d.key));
        })
        .y(function(d) {
          return yScale(d.value);
        })

      var nest = d3.nest()
        .key(function(d) {
          return d.region;
        })
        .key(function(d) {
          return d.date;
        })
        .rollup(function(leaves) {
          return d3.sum(leaves, function(d) {
            return (d.count)
          });
        })
        .entries(dataset)

        console.log(nest)

      // Set the color scheme
        var colors = d3.scaleOrdinal()
          .domain(["South", "West", "Northeast","Midwest"])
          .range(["#EF5285", "#88F284" , "#5965A3","#900C3F"]);

      var regYear = svg.selectAll(".regYear")
        .data(nest)
        .enter()
        .append("g")
        .attr("stroke", function(d){ return colors(d.key)}); // Adding color!

      // console.log(regYear)

      var paths = regYear.selectAll(".line")
        .data(function(d) {
          return [d.values]
        })
        .enter()
        .append("path");

      // Draw the line
      paths
        .attr("d", function(d) {
          return valueLine(d)
        })
        .attr("class", "line")
        .style("fill", "none");

    svg.selectAll(".dot")
        .data(dataset)
        .enter().append("circle") // Uses the enter().append() method
        .attr("class", "dot") // Assign a class for styling
        .attr("cx", function(d, i) { return xScale(i) })
        .attr("cy", function(d) { return yScale(d.count) })//this is not working
        .attr("r", 5);

      svg.append("g").attr("class", "axis").attr("transform", "translate(0," + (h - padding) + ")").call(xAxis);
      //draw Y axis
      svg.append("g").attr("class", "axis").attr("transform", "translate(" + padding + ",0)").call(yAxis);
      // add label
      svg.append("text").attr("x", (w / 2)).attr("y", h + 30).attr("text-anchor", "middle").text("Year");
      svg.append("text").attr("x", padding).attr("y", padding - 20).attr("text-anchor", "middle").text("# of Events");
      //add title
      svg.append("text").attr("x", (w / 2)).attr("y", padding).attr("text-anchor", "middle").text("Events per Year by Category");
      // add legend
      var legend = svg.append("g")
        .attr("class", "legend")
        .attr("x", w - 65)
        .attr("y", 25)
        .attr("height", 100)
        .attr("width", 100);

      ////////////////////////////////////END///////////////////////////

    </script>

  </body>

</html>

</code>```

答:
To get max value inside nested array you can nest d3.max function in the way like"

```<code>var maxCountSum = d3.max(nest, function(d) {
    return d3.max(d.values, function (f) {
        return f.value
    });
});
</code>```

Then apply to yScale domain:

```<code>var yScale = d3.scaleLinear()
    .domain([0, maxCountSum]).range([height, 0]);
</code>```

Body:
I have the following code that nests my data based on region and date. The problem I am having is that I don't know how to define yScale to dynamically draw the axis so that the max sum from the nested data is returned (the max val of the nested data is higher than the max val in the dataset bc it is aggregated). Thus my yAxis is truncated and the chart doesn't show all the data.

In the code, if I hardcode the domain to .domain([0, 3500]) then the axis is correct, but otherwise it is not correct.  I don't want to hardcode the domain.  How do I reference the nested values?

EDITED to show code provided in comments, which helps but doesn't entirely fix when the script is run on the entire dataset. Please see pic at bottom.

      var yScale = d3.scaleLinear()
               .domain([0, d3.max(dataset, function(d) {
                  return parseInt(d.count,10);
                })])
               .range([h - padding, padding])

      // var yScale = d3.scaleLinear()
      //   .domain([0, 3500])
      //   .range([h - padding, padding]) //not supposed to hard code the scale but it is not working

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Nested Chart</title>

Body:
To get max value inside nested array you can nest d3.max function in the way like"

var maxCountSum = d3.max(nest, function(d) {
    return d3.max(d.values, function (f) {
        return f.value
    });
});

Then apply to yScale domain:

var yScale = d3.scaleLinear()
    .domain([0, maxCountSum]).range([height, 0]);


问:
Flask Jinja2 template syntax conflicts with AngularJS (jinja2.exceptions.UndefinedError:)

How to access a $scope.list in html from angularjs?

jinja2.exceptions.UndefinedError: 'car' is undefined

main.js

```<code>(function ()
{
    'use strict';

    angular.module('WordcountApp', [])

    .controller('WordcountController', ['$scope',
                                        function($scope)
                                        {
                                            $scope.some = 'jjj'

                                            console.log( "in WordcountController " , $scope.some)

                                            $scope.cars = [
                                                            {make: 'Mazda', model: 'Miata', year: 2001},
                                                            {make: 'Toyota', model: 'Prius', year: 2013},
                                                            {make: 'Tesla', model: 'S', year: 2015},
                                                            {make: 'BMW', model: '325i', year: 2012}
                                                          ]
                                        }
                                       ]
                );
}()
);
</code>```

index.html

```<code><!DOCTYPE html>
<html ng-app = "WordcountApp" >

    <head>
        <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"> </script>
        <script src = "static/main.js" > </script>
    </head>

    <body ng-controller = "WordcountController">
        <ul ng-repeat = "car in cars" >
            <p> {{ car.make }} </p>
        </ul>
    </body>
</html>
</code>```

app.py

```<code>from flask import Flask
from flask import render_template
from flask import request

app = Flask( __name__ )
displayText = 'Default text from Python'

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index.html')

@app.route("/writeOutput", methods=['POST'])
def writeOutput():
    global displayText

    print("request.get_json():- ", request.get_json())

    displayText = request.get_json()['myOutput']['myText']

    print ("from POST " , displayText)
    return displayText

@app.route("/displayPreviousText", methods=['GET'])
def displayPreviousText():
    global displayText
    return displayText

if __name__ == "__main__":
    app.run()
</code>```

I run this application as python app.py

Error: jinja2.exceptions.UndefinedError: 'car' is undefined

What is the way to access the list in html from angular?

答:
This happened because flask syntax conflicted with angular.

So changes to Python code:

import os

from flask import Flask
from flask import render_template
from flask import send_file, make_response, abort
from flask import request

app = Flask( __name__ )
displayText = 'Default text from Python'

@app.route('/', methods=['GET', 'POST'])
def index():
 return make_response(open('index.html').read())

@app.route("/writeOutput", methods=['POST'])
def writeOutput():
    global displayText

    print("request.get_json():- ", request.get_json())

    displayText = request.get_json()['myOutput']['myText']

    print ("from POST " , displayText)
    return displayText

@app.route("/displayPreviousText", methods=['GET'])
def displayPreviousText():
    global displayText
    return displayText

if __name__ == "__main__":
    app.run()```

return make_response(open('index.html').read())

instead of

render_template('index.html')

This would solve the issue.

Another way could be using partials of Angular.

Body:
How to access a $scope.list in html from angularjs?

jinja2.exceptions.UndefinedError: 'car' is undefined

main.js

(function ()
{
    'use strict';

    angular.module('WordcountApp', [])

    .controller('WordcountController', ['$scope',
                                        function($scope)
                                        {
                                            $scope.some = 'jjj'

                                            console.log( "in WordcountController " , $scope.some)

                                            $scope.cars = [
                                                            {make: 'Mazda', model: 'Miata', year: 2001},
                                                            {make: 'Toyota', model: 'Prius', year: 2013},
                                                            {make: 'Tesla', model: 'S', year: 2015},
                                                            {make: 'BMW', model: '325i', year: 2012}
                                                          ]
                                        }
                                       ]
                );
}()
);

index.html

<!DOCTYPE html>

 {{ car.make }}

app.py

from flask import Flask
from flask import render_template
from flask import request

app = Flask( __name__ )
displayText = 'Default text from Python'

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index.html')

@app.route("/writeOutput", methods=['POST'])
def writeOutput():
    global displayText

    print("request.get_json():- ", request.get_json())

    displayText = request.get_json()['myOutput']['myText']

    print ("from POST " , displayText)
    return displayText

@app.route("/displayPreviousText", methods=['GET'])
def displayPreviousText():
    global displayText
    return displayText

if __name__ == "__main__":
    app.run()

I run this application as python app.py

Error: jinja2.exceptions.UndefinedError: 'car' is undefined

What is the way to access the list in html from angular?

Body:
This happened because flask syntax conflicted with angular.

So changes to Python code:

import os

from flask import Flask
from flask import render_template
from flask import send_file, make_response, abort
from flask import request

app = Flask( __name__ )
displayText = 'Default text from Python'

@app.route('/', methods=['GET', 'POST'])
def index():
 return make_response(open('index.html').read())

@app.route("/writeOutput", methods=['POST'])
def writeOutput():
    global displayText

    print("request.get_json():- ", request.get_json())

    displayText = request.get_json()['myOutput']['myText']

    print ("from POST " , displayText)
    return displayText

@app.route("/displayPreviousText", methods=['GET'])
def displayPreviousText():
    global displayText
    return displayText

if __name__ == "__main__":
    app.run()

return make_response(open('index.html').read())

instead of

render_template('index.html')

This would solve the issue.

Another way could be using partials of Angular.


问:
Trying to make a server in Java that sends an image to my Android device using sockets
I'm trying to send an image using a Java server to my Android device but it doesn't work and I don't know why.

The code for the server is:

```<code>public class Main {

public static void main(String argv[]) throws Exception
{

  ServerSocket welcomeSocket = new ServerSocket(6789);
  Image image = null;

  while(true) {

       Socket connectionSocket = welcomeSocket.accept();

       BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

       ObjectOutputStream  outToClient = new ObjectOutputStream(connectionSocket.getOutputStream());

       File f = new File("/resources/image.png");
       image = ImageIO.read(f);

       outToClient.writeObject( new ImageIcon(""+image) );

    }
}

}
</code>```

I think the problem is in the server because the Android app works with another server

client:

```<code>BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));

DataInputStream in;

BufferedInputStream buf;

DataInputStream mod ;

Socket sc = new Socket(myIP,48000);

DataInputStream infromServer = new DataInputStream(sc.getInputStream());

mod =  infromServer;

Bitmap mPhotoPicture = BitmapFactory.decodeStream(modifiedSentence);

imagen.setImageBitmap((mPhotoPicture));
</code>```

答:
The other server is probably sending the raw image data (not an ImageIcon serialized object).  It looks like BitmapFactory expects the image's raw bytes. Try writing the raw bytes out to your socket:

```<code>FileInputStream fis = null;
int size = (int)f.length();
byte[] bytes = new byte[size];
fis = new FileInputStream( f );
int read = fis.read( bytes );

connectionSocket.getOutputStream().write( bytes );
connectionSocket.getOutputStream().flush();
</code>```

Obviously, you'll need to add some error detection and handling to make this robust.

Body:
I'm trying to send an image using a Java server to my Android device but it doesn't work and I don't know why.

The code for the server is:

public class Main {

public static void main(String argv[]) throws Exception
{

  ServerSocket welcomeSocket = new ServerSocket(6789);
  Image image = null;

  while(true) {

       Socket connectionSocket = welcomeSocket.accept();

       BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

       ObjectOutputStream  outToClient = new ObjectOutputStream(connectionSocket.getOutputStream());

       File f = new File("/resources/image.png");
       image = ImageIO.read(f);

       outToClient.writeObject( new ImageIcon(""+image) );

    }
}

}

I think the problem is in the server because the Android app works with another server

client:

BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));

DataInputStream in;

BufferedInputStream buf;

DataInputStream mod ;

Socket sc = new Socket(myIP,48000);

DataInputStream infromServer = new DataInputStream(sc.getInputStream());

mod =  infromServer;

Bitmap mPhotoPicture = BitmapFactory.decodeStream(modifiedSentence);

imagen.setImageBitmap((mPhotoPicture));

Body:
The other server is probably sending the raw image data (not an ImageIcon serialized object).  It looks like BitmapFactory expects the image's raw bytes. Try writing the raw bytes out to your socket:

FileInputStream fis = null;
int size = (int)f.length();
byte[] bytes = new byte[size];
fis = new FileInputStream( f );
int read = fis.read( bytes );

connectionSocket.getOutputStream().write( bytes );
connectionSocket.getOutputStream().flush();

Obviously, you'll need to add some error detection and handling to make this robust.