问:
Why is asyncio queue await get() blocking?
Why is await queue.get() blocking?

import asyncio

async def producer(queue, item):
    await queue.put(item)

async def consumer(queue):
    val = await queue.get()
    print("val = %d" % val)

async def main():
    queue = asyncio.Queue()
    await consumer(queue)
    await producer(queue, 1)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
```

<p>If I call the <strong>producer()</strong> before <strong>consumer()</strong>, it works fine
That is to say, the following works fine.</p>

<pre class="lang-py prettyprint-override"><code>async def main():
    queue = asyncio.Queue()
    await producer(queue, 1)
    await consumer(queue)
</code>```

Why isn't await queue.get() yielding control back to the event loop so that the producer coroutine can run which will populate the queue so that queue.get() can return.

答:
You need to start the consumer and the producer in parallel, e.g. defining main like this:

```<code>async def main():
    queue = asyncio.Queue()
    await asyncio.gather(consumer(queue), producer(queue, 1))
</code>```

If for some reason you can't use gather, then you can do (the equivalent of) this:

```<code>async def main():
    queue = asyncio.Queue()
    asyncio.create_task(consumer(queue))
    asyncio.create_task(producer(queue, 1))
    await asyncio.sleep(100)  # what your program actually does
</code>```

Why isn't await queue.get() yielding control back to the event loop so that the producer coroutine can run which will populate the queue so that queue.get() can return.

await queue.get() is yielding control back to the event loop. But await means wait, so when your main coroutine says await consumer(queue), that means "resume me once consumer(queue) has completed." Since consumer(queue) is itself waiting for someone to produce something, you have a classic case of deadlock.

Reversing the order works only because your producer is one-shot, so it immediately returns to the caller. If your producer happened to await an external source (such as a socket), you would have a deadlock there as well. Starting them in parallel avoids the deadlock regardless of how producer and consumer are written.

Body:
Why is await queue.get() blocking?

import asyncio

async def producer(queue, item):
    await queue.put(item)

async def consumer(queue):
    val = await queue.get()
    print("val = %d" % val)

async def main():
    queue = asyncio.Queue()
    await consumer(queue)
    await producer(queue, 1)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

If I call the producer() before consumer(), it works fine
That is to say, the following works fine.

async def main():
    queue = asyncio.Queue()
    await producer(queue, 1)
    await consumer(queue)

Why isn't await queue.get() yielding control back to the event loop so that the producer coroutine can run which will populate the queue so that queue.get() can return.

Body:
You need to start the consumer and the producer in parallel, e.g. defining main like this:

async def main():
    queue = asyncio.Queue()
    await asyncio.gather(consumer(queue), producer(queue, 1))

If for some reason you can't use gather, then you can do (the equivalent of) this:

async def main():
    queue = asyncio.Queue()
    asyncio.create_task(consumer(queue))
    asyncio.create_task(producer(queue, 1))
    await asyncio.sleep(100)  # what your program actually does

Why isn't await queue.get() yielding control back to the event loop so that the producer coroutine can run which will populate the queue so that queue.get() can return.

await queue.get() is yielding control back to the event loop. But await means wait, so when your main coroutine says await consumer(queue), that means "resume me once consumer(queue) has completed." Since consumer(queue) is itself waiting for someone to produce something, you have a classic case of deadlock.

Reversing the order works only because your producer is one-shot, so it immediately returns to the caller. If your producer happened to await an external source (such as a socket), you would have a deadlock there as well. Starting them in parallel avoids the deadlock regardless of how producer and consumer are written.


来源: stackexchange

问:
Each VBA sub works perfectly separately, but calling subs from another function doesn't work
I wrote 2 subs to automate a daily task.

First sub MatriksFlowUpdate calls 2 other subs RightClick and SingleClick to simulate a right click and then a left click on a certain part of the screen.  This is done in order to prompt another program to create an Excel file and save it under C:.  This sub works correctly on its own (i.e. it simulates a right click and a left click at the desired locations on the screen, prompting another program to produce an Excel sheet)

Second sub CloseInstance finds the Excel sheet created above, and closes it.  This sub also works correctly on its own.

However, when I try to call these 2 subs one after the other in another sub MainSequence, I get an error saying the Excel that should be found and closed by the second sub can't be found. So I get an error on the CloseInstance sub at the location below

```<code>    Set xlApp =GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application
</code>```

I've tried many things to fix this, but I feel like I am going around in circles for the past few days.  Any help would be much much appreciated.

P.S. My first time posting a q on stackoverflow so please bear with me with the formatting.

```<code>    Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
    Public Declare PtrSafe Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
    Public Const MOUSEEVENTF_LEFTDOWN = &H2
    Public Const MOUSEEVENTF_LEFTUP = &H4
    Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
    Public Const MOUSEEVENTF_RIGHTUP As Long = &H10
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)

    Sub MainSequence()
        'This sub pieces together MatriksFlowUpdate and CloseInstance
        Call MatriksFlowUpdate
        Sleep 2000
        Call CloseInstance
        End Sub

    Sub MatriksFlowUpdate()
        'Prompts 3rd party software (Matriks) to produce Excel with latest flow data
        Call RightClick
        Call SingleClick
        End Sub

    Private Sub RightClick()
    'Simulates a mouse right click at desired screen coordinates
    Sleep 1000
    SetCursorPos 1750, 750 'x and y position
    mouse_event MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0
    End Sub

    Private Sub SingleClick()
    'Simulates a mouse left click at desired screen coordinates
    Sleep 1000
    SetCursorPos 1750, 650 'x and y position
    mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
    End Sub

    Sub CloseInstance()
    'Finds the instance of Excel where Matriks exported its excel and closes that instance of Excel
    Dim xlApp As Excel.Application
    Dim WB As Workbook
    Set xlApp =GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application
    Set WB = xlApp.Workbooks("Temp.xls")
    WB.Close
    End Sub
</code>```

答:
Maybe try something like that

```<code>Sub CloseInstance()
    Dim WB As Workbook
    Set WB = Application.Workbooks("Temp.xls")
    If Not WB Is Nothing Then
        WB.Close
    End If
End Sub
</code>```

Or try this to open

```<code>Sub test()
IsWorkBookOpen ("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls")
End Sub
Sub IsWorkBookOpen(ByVal fullFileName)
Dim wBook As Workbook
If FileExists(fullFileName) Then
    On Error Resume Next
    'Test to see if a Workbook is open.
    Set wBook = Workbooks(Dir(fullFileName))
        If wBook Is Nothing Then 'Not open
            Workbooks.Open (fullFileName)
            Set wBook = Nothing
            On Error GoTo 0
        Else 'It is open
            MsgBox "Yes it is open", vbInformation, "Founded"
            Set wBook = Nothing
            On Error GoTo 0
        End If
Else
    MsgBox "File does not exists"
End If
End Sub

Function FileExists(ByVal fullFileName) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wrote 2 subs to automate a daily task.

First sub MatriksFlowUpdate calls 2 other subs RightClick and SingleClick to simulate a right click and then a left click on a certain part of the screen.  This is done in order to prompt another program to create an Excel file and save it under C:.  This sub works correctly on its own (i.e. it simulates a right click and a left click at the desired locations on the screen, prompting another program to produce an Excel sheet)

Second sub CloseInstance finds the Excel sheet created above, and closes it.  This sub also works correctly on its own.

However, when I try to call these 2 subs one after the other in another sub MainSequence, I get an error saying the Excel that should be found and closed by the second sub can't be found. So I get an error on the CloseInstance sub at the location below

    Set xlApp =GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application

I've tried many things to fix this, but I feel like I am going around in circles for the past few days.  Any help would be much much appreciated.

P.S. My first time posting a q on stackoverflow so please bear with me with the formatting.

    Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
    Public Declare PtrSafe Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
    Public Const MOUSEEVENTF_LEFTDOWN = &H2
    Public Const MOUSEEVENTF_LEFTUP = &H4
    Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
    Public Const MOUSEEVENTF_RIGHTUP As Long = &H10
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)

    Sub MainSequence()
        'This sub pieces together MatriksFlowUpdate and CloseInstance
        Call MatriksFlowUpdate
        Sleep 2000
        Call CloseInstance
        End Sub

    Sub MatriksFlowUpdate()
        'Prompts 3rd party software (Matriks) to produce Excel with latest flow data
        Call RightClick
        Call SingleClick
        End Sub

    Private Sub RightClick()
    'Simulates a mouse right click at desired screen coordinates
    Sleep 1000
    SetCursorPos 1750, 750 'x and y position
    mouse_event MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0
    End Sub

    Private Sub SingleClick()
    'Simulates a mouse left click at desired screen coordinates
    Sleep 1000
    SetCursorPos 1750, 650 'x and y position
    mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
    End Sub

    Sub CloseInstance()
    'Finds the instance of Excel where Matriks exported its excel and closes that instance of Excel
    Dim xlApp As Excel.Application
    Dim WB As Workbook
    Set xlApp =GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application
    Set WB = xlApp.Workbooks("Temp.xls")
    WB.Close
    End Sub

Body:
Maybe try something like that

Sub CloseInstance()
    Dim WB As Workbook
    Set WB = Application.Workbooks("Temp.xls")
    If Not WB Is Nothing Then
        WB.Close
    End If
End Sub

Or try this to open

Sub test()
IsWorkBookOpen ("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls")
End Sub
Sub IsWorkBookOpen(ByVal fullFileName)
Dim wBook As Workbook
If FileExists(fullFileName) Then
    On Error Resume Next
    'Test to see if a Workbook is open.
    Set wBook = Workbooks(Dir(fullFileName))
        If wBook Is Nothing Then 'Not open
            Workbooks.Open (fullFileName)
            Set wBook = Nothing
            On Error GoTo 0
        Else 'It is open
            MsgBox "Yes it is open", vbInformation, "Founded"
            Set wBook = Nothing
            On Error GoTo 0
        End If
Else
    MsgBox "File does not exists"
End If
End Sub

Function FileExists(ByVal fullFileName) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function


问:
Questionable need for mutex with shared resources
I currently have a mechanism where the 2 threads read/write the same data; though not at the same time; and do not use any synchronisation mechanisms.

Perhaps the simplest example would be (pseudocode)

```<code>x = 5;
startThread(changeX).join()
assert(x != 5)
</code>```

thus we can be sure that the thread in question has processed x before it's read by the starting thread.

Is this undefined behavior (as the x might be optimised) - or is it safe?

My experience of c++ and my research so far would say not safe - but I couldn't see anything definitive.

答:
Provided the pseudocode you are writting I can tell you this:

1 - Rule of thumb, whenever 2 threads are doing writting/reading on the same variable you need to take into account to use thread safe structures and you should always use some kind of synchronization between threads.

2 - While in your case you are working with atomic variables, you wont be having a problem when doing the read/write, but you might here have a race condition, and you could have random outputs depending on how windows decides to handle the threads.

Taking both things into account I would strongly recommend you to use some kind of synchronization in order to not get random results depending on how windows decides to handle your threads. Your gut in c++ is telling you something, because there is something going on here

Body:
I currently have a mechanism where the 2 threads read/write the same data; though not at the same time; and do not use any synchronisation mechanisms.

Perhaps the simplest example would be (pseudocode)

x = 5;
startThread(changeX).join()
assert(x != 5)

thus we can be sure that the thread in question has processed x before it's read by the starting thread.

Is this undefined behavior (as the x might be optimised) - or is it safe?

My experience of c++ and my research so far would say not safe - but I couldn't see anything definitive.


问:
Count distinct while aggregating others?
This is how my dataset looks like:

```<code>+---------+------------+-----------------+
|  name   |request_type| request_group_id|
+---------+------------+-----------------+
|Michael  |     X      |  1020           |
|Michael  |     X      |  1018           |
|Joe      |     Y      |  1018           |
|Sam      |     X      |  1018           |
|Michael  |     Y      |  1021           |
|Sam      |     X      |  1030           |
|Elizabeth|     Y      |  1035           |
+---------+------------+-----------------+
</code>```

I want to calculate the amount of request_type's per person and count unique request_group_id's

Result should be following:

```<code>+---------+--------------------+---------------------+--------------------------------+
|  name   |cnt(request_type(X))| cnt(request_type(Y))| cnt(distinct(request_group_id))|
+---------+--------------------+---------------------+--------------------------------+
|Michael  |          2         |         1           |      3                         |
|Joe      |          0         |         1           |      1                         |
|Sam      |          2         |         0           |      2                         |
|John     |          1         |         0           |      1                         |
|Elizabeth|          0         |         1           |      1                         |
+---------+--------------------+---------------------+--------------------------------+
</code>```

What I've done so far: (helps to derive first two columns)

```<code>msgDataFrame.select(NAME, REQUEST_TYPE)
            .groupBy(NAME)
            .pivot(REQUEST_TYPE, Lists.newArrayList(X, Y))
            .agg(functions.count(REQUEST_TYPE))
            .show();
</code>```

How to count distinct request_group_id's in this select? Is it possible to do within it?

I think it's possible only via two datasets join (my current result + separate aggregation by distinct request_group_id)

答:
Example with "countDistinct" ("countDistinct" is not worked over window, replaced with "size","collect_set"):</p>

```<code>val groupIdWindow = Window.partitionBy("name")
df.select($"name", $"request_type",
      size(collect_set("request_group_id").over(groupIdWindow)).alias("countDistinct"))
  .groupBy("name", "countDistinct")
  .pivot($"request_type", Seq("X", "Y"))
  .agg(count("request_type"))
  .show(false)
</code>```

Body:
This is how my dataset looks like:

+---------+------------+-----------------+
|  name   |request_type| request_group_id|
+---------+------------+-----------------+
|Michael  |     X      |  1020           |
|Michael  |     X      |  1018           |
|Joe      |     Y      |  1018           |
|Sam      |     X      |  1018           |
|Michael  |     Y      |  1021           |
|Sam      |     X      |  1030           |
|Elizabeth|     Y      |  1035           |
+---------+------------+-----------------+

I want to calculate the amount of request_type's per person and count unique request_group_id's

Result should be following:

+---------+--------------------+---------------------+--------------------------------+
|  name   |cnt(request_type(X))| cnt(request_type(Y))| cnt(distinct(request_group_id))|
+---------+--------------------+---------------------+--------------------------------+
|Michael  |          2         |         1           |      3                         |
|Joe      |          0         |         1           |      1                         |
|Sam      |          2         |         0           |      2                         |
|John     |          1         |         0           |      1                         |
|Elizabeth|          0         |         1           |      1                         |
+---------+--------------------+---------------------+--------------------------------+

What I've done so far: (helps to derive first two columns)

msgDataFrame.select(NAME, REQUEST_TYPE)
            .groupBy(NAME)
            .pivot(REQUEST_TYPE, Lists.newArrayList(X, Y))
            .agg(functions.count(REQUEST_TYPE))
            .show();

How to count distinct request_group_id's in this select? Is it possible to do within it?

I think it's possible only via two datasets join (my current result + separate aggregation by distinct request_group_id)

Body:
Example with "countDistinct" ("countDistinct" is not worked over window, replaced with "size","collect_set"):

val groupIdWindow = Window.partitionBy("name")
df.select($"name", $"request_type",
      size(collect_set("request_group_id").over(groupIdWindow)).alias("countDistinct"))
  .groupBy("name", "countDistinct")
  .pivot($"request_type", Seq("X", "Y"))
  .agg(count("request_type"))
  .show(false)


问:
Getting directory listing over http
There is a directory that is being served over the net which I'm interested in monitoring. Its contents are various versions of software that I'm using and I'd like to write a script that I could run which checks what's there, and downloads anything that is newer that what I've already got.

Is there a way, say with wget or something, to get a a directory listing. I've tried using wget on the directory, which gives me html. To avoid having to parse the html document, is there a way of retrieving a simple listing like ls would give?

答:
You can use IDM (internet download manager)

It has a utility named "IDM SITE GRABBER" input the http/https URLs and it will download all files and folders from http/https protocol for you.

ContentLicense: CC BY-SA 3.0

Title: Getting directory listing over http


问:
Client side can not find io
I have written a simple program that has a nodejs consumer, consuming data from kafka and then it transfers data using socket.io to a client so that I may render the data using d3.

However i keep running into this error on the client side that it can not find io.

I have tried to use a cdn and other alternatives in my index.html however it has not resulted in any progress.

Consumer.js

```<code>var options = {
  fromOffset: 'latest'
};

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

// Kafka-node initilizations.
var kafka = require('kafka-node'),
 Consumer = kafka.Consumer,
 client = new kafka.KafkaClient(),
 consumer = new Consumer(
     client,
     [
         { topic: 'trial1', partition: 0 }
     ],
     [
 {
   autoCommit: false
 },
 options =
 {
   fromOffset: 'latest'
 }
     ]
 );

 consumer.on('message', function (message) {

     router.get('/', function(req, res, next) {
       res.render('index', {title: 'Test', condition: false});
     });
     console.log(message.value);
 });

// Display error messages if any.
consumer.on('error', function (err)
{
  console.log('ERROR' + err.toString());
});
</code>```

Client.js

```<code> //init socket
var socket = io();
    //on message call update
    socket.on('message', function(message){
      console.log(message)
 });
</code>```

index.html

```<code><html>
 <head>
   <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
   <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
 </head>
 <body>
   <script>
     var socket = io.connect();
   </script>
   <div>This is our socket.html file</div>
 </body>
</html>
</code>```

答:
Your version appears to be slightly outdated, and older versions of Socket.IO only have the server version and the client used to be separated (socket.io-client.js used to be a separate package).

Make sure you're using the correct version of Socket.IO (you can get from https://cdnjs.com/libraries/socket.io)

Like So:

```

<p>Also make sure you use this format:</p>

```
```

Hope I was of help!

Title: Client side can not find io

Body:
I have written a simple program that has a nodejs consumer, consuming data from kafka and then it transfers data using socket.io to a client so that I may render the data using d3.

However i keep running into this error on the client side that it can not find io.

I have tried to use a cdn and other alternatives in my index.html however it has not resulted in any progress.

Consumer.js

var options = {
  fromOffset: 'latest'
};

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

// Kafka-node initilizations.
var kafka = require('kafka-node'),
 Consumer = kafka.Consumer,
 client = new kafka.KafkaClient(),
 consumer = new Consumer(
     client,
     [
         { topic: 'trial1', partition: 0 }
     ],
     [
 {
   autoCommit: false
 },
 options =
 {
   fromOffset: 'latest'
 }
     ]
 );

 consumer.on('message', function (message) {

     router.get('/', function(req, res, next) {
       res.render('index', {title: 'Test', condition: false});
     });
     console.log(message.value);
 });

// Display error messages if any.
consumer.on('error', function (err)
{
  console.log('ERROR' + err.toString());
});

Client.js

 //init socket
var socket = io();
    //on message call update
    socket.on('message', function(message){
      console.log(message)
 });

index.html

This is our socket.html file

Body:
Your version appears to be slightly outdated, and older versions of Socket.IO only have the server version and the client used to be separated (socket.io-client.js used to be a separate package).

Make sure you're using the correct version of Socket.IO (you can get from https://cdnjs.com/libraries/socket.io)

Like So:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>

Also make sure you use this format:

<script>
  var socket = io('my.ip'); // NOT io.connect();
  ... // Rest of code
</script>

Hope I was of help!


问:
Missing asp.net features on IIS 10.0
I'm using IIS 10.0 and  ASP.NET feature section isn't showing

My environment: Windows Server 2016

My issue is similar to the issue posted here: No asp.net features on IIS 7.5 and No ASP.NET features shown in IIS 7.5

The 'add features' fix mentioned in those posts doesn't apply as it was already correctly configured that (see image)

答:
From the Screenshots in the OPs questions I deduced that mine simply weren't selected in the server roles section of the server administrator. For clarity I added these:

```<code>"Add roles and features"
    -> "Server Roles"
       -> "Web Server (iis)"
          -> "Web Server"
             -> "Application Development"
                -> "ASP.NET 4.6" (I also needed 3.5 for legacy reasons)
</code>```

Then restart IIS manager (just close the window and reopen it)

Title: Missing asp.net features on IIS 10.0

Body:
From the Screenshots in the OPs questions I deduced that mine simply weren't selected in the server roles section of the server administrator. For clarity I added these:

"Add roles and features"
    -> "Server Roles"
       -> "Web Server (iis)"
          -> "Web Server"
             -> "Application Development"
                -> "ASP.NET 4.6" (I also needed 3.5 for legacy reasons)

Then restart IIS manager (just close the window and reopen it)


问:
Cannot deserialize instance of `org.json.JSONObject`
I have a basic SpringBoot 2.1.5.RELEASE app. Using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file with some RestControllers.

In 1 of the controller this is the body I send:

```<code>{
    "depositHotel": "xxx",
    "destinationHotel": "aaa",
    "depositHotelAmount": "0.2",
    "destinationHotelAmount": "4",
    "destinationAddress": [{
        "address": "asdf",
        "tag": ""
    }],
    "refundAddress": [{
        "address": "pio",
        "tag": ""
    }]
}
</code>```

so I create this class to use it as a RequestBody:

```<code>public class HotelswitchHotelOrderRequestBody {

    public static class Builder {

        private String depositHotel;
        private String destinationHotel;
        private Float depositHotelAmount;
        private Float destinationHotelAmount;
        private JSONObject destinationAddress;
        private JSONObject refundAddress;

        public Builder(String depositHotel, String destinationHotel) {
            this.depositHotel = depositHotel;
            this.destinationHotel = destinationHotel;
        }

        public Builder withDepositHotelAmount (Float depositHotelAmount) {
            this.depositHotelAmount = depositHotelAmount;
            return this;
        }

        public Builder withDestinationHotelAmount (Float destinationHotelAmount) {
            this.destinationHotelAmount = destinationHotelAmount;
            return this;
        }

        public Builder toDestinationAddress (JSONObject destinationAddress) {
            this.destinationAddress = destinationAddress;
            return this;
        }

        public Builder toRefundAddress (JSONObject refundAddress) {
            this.refundAddress = refundAddress;
            return this;
        }

        public HotelswitchHotelOrderRequestBody build(){

            HotelswitchHotelOrderRequestBody order = new HotelswitchHotelOrderRequestBody();
            order.depositHotel = this.depositHotel;
            order.depositHotelAmount = this.depositHotelAmount;
            order.destinationAddress = this.destinationAddress;
            order.destinationHotel = this.destinationHotel;
            order.destinationHotelAmount = this.destinationHotelAmount;
            order.refundAddress = this.refundAddress;

            return order;

        }
    }

    private String depositHotel;
    private String destinationHotel;
    private Float depositHotelAmount;
    private Float destinationHotelAmount;
    private JSONObject destinationAddress;
    private JSONObject refundAddress;

    private HotelswitchHotelOrderRequestBody () {
        //Constructor is now private.
    }

    public String getDepositHotel() {
        return depositHotel;
    }

    public void setDepositHotel(String depositHotel) {
        this.depositHotel = depositHotel;
    }

    public String getDestinationHotel() {
        return destinationHotel;
    }

    public void setDestinationHotel(String destinationHotel) {
        this.destinationHotel = destinationHotel;
    }

    public Float getDepositHotelAmount() {
        return depositHotelAmount;
    }

    public void setDepositHotelAmount(Float depositHotelAmount) {
        this.depositHotelAmount = depositHotelAmount;
    }

    public Float getDestinationHotelAmount() {
        return destinationHotelAmount;
    }

    public void setDestinationHotelAmount(Float destinationHotelAmount) {
        this.destinationHotelAmount = destinationHotelAmount;
    }

    public JSONObject getDestinationAddress() {
        return destinationAddress;
    }

    public void setDestinationAddress(JSONObject destinationAddress) {
        this.destinationAddress = destinationAddress;
    }

    public JSONObject getRefundAddress() {
        return refundAddress;
    }

    public void setRefundAddress(JSONObject refundAddress) {
        this.refundAddress = refundAddress;
    }

}
</code>```

But I have this error when receiving the object:

```<code>JSON parse error:  out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `org.json.JSONObject` out of START_ARRAY token
</code>```

答:
JSONObject's representation in actual JSON is a hash i.e. {...}. In your json data you're providing an array of hashes [{...}] which is not the same. Judging from your domain I don't think it has to be multiple values, so you can just omit [] in your payload and if it does then the fields in your Java class can be defined as JSONArray.

However, I think you should go with defining an Address class and either using

```<code>private Address destinationAddress;
private Address refundAddress;
</code>```

or if it indeed does have to be an object array

```<code>private List<Address> destinationAddresses;
private List<Address> refundAddresses;
</code>```

Body:
I have a basic SpringBoot 2.1.5.RELEASE app. Using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file with some RestControllers.

In 1 of the controller this is the body I send:

{
    "depositHotel": "xxx",
    "destinationHotel": "aaa",
    "depositHotelAmount": "0.2",
    "destinationHotelAmount": "4",
    "destinationAddress": [{
        "address": "asdf",
        "tag": ""
    }],
    "refundAddress": [{
        "address": "pio",
        "tag": ""
    }]
}

so I create this class to use it as a RequestBody:

public class HotelswitchHotelOrderRequestBody {

    public static class Builder {

        private String depositHotel;
        private String destinationHotel;
        private Float depositHotelAmount;
        private Float destinationHotelAmount;
        private JSONObject destinationAddress;
        private JSONObject refundAddress;

        public Builder(String depositHotel, String destinationHotel) {
            this.depositHotel = depositHotel;
            this.destinationHotel = destinationHotel;
        }

        public Builder withDepositHotelAmount (Float depositHotelAmount) {
            this.depositHotelAmount = depositHotelAmount;
            return this;
        }

        public Builder withDestinationHotelAmount (Float destinationHotelAmount) {
            this.destinationHotelAmount = destinationHotelAmount;
            return this;
        }

        public Builder toDestinationAddress (JSONObject destinationAddress) {
            this.destinationAddress = destinationAddress;
            return this;
        }

        public Builder toRefundAddress (JSONObject refundAddress) {
            this.refundAddress = refundAddress;
            return this;
        }

        public HotelswitchHotelOrderRequestBody build(){

            HotelswitchHotelOrderRequestBody order = new HotelswitchHotelOrderRequestBody();
            order.depositHotel = this.depositHotel;
            order.depositHotelAmount = this.depositHotelAmount;
            order.destinationAddress = this.destinationAddress;
            order.destinationHotel = this.destinationHotel;
            order.destinationHotelAmount = this.destinationHotelAmount;
            order.refundAddress = this.refundAddress;

            return order;

        }
    }

    private String depositHotel;
    private String destinationHotel;
    private Float depositHotelAmount;
    private Float destinationHotelAmount;
    private JSONObject destinationAddress;
    private JSONObject refundAddress;

    private HotelswitchHotelOrderRequestBody () {
        //Constructor is now private.
    }

    public String getDepositHotel() {
        return depositHotel;
    }

    public void setDepositHotel(String depositHotel) {
        this.depositHotel = depositHotel;
    }

    public String getDestinationHotel() {
        return destinationHotel;
    }

    public void setDestinationHotel(String destinationHotel) {
        this.destinationHotel = destinationHotel;
    }

    public Float getDepositHotelAmount() {
        return depositHotelAmount;
    }

    public void setDepositHotelAmount(Float depositHotelAmount) {
        this.depositHotelAmount = depositHotelAmount;
    }

    public Float getDestinationHotelAmount() {
        return destinationHotelAmount;
    }

    public void setDestinationHotelAmount(Float destinationHotelAmount) {
        this.destinationHotelAmount = destinationHotelAmount;
    }

    public JSONObject getDestinationAddress() {
        return destinationAddress;
    }

    public void setDestinationAddress(JSONObject destinationAddress) {
        this.destinationAddress = destinationAddress;
    }

    public JSONObject getRefundAddress() {
        return refundAddress;
    }

    public void setRefundAddress(JSONObject refundAddress) {
        this.refundAddress = refundAddress;
    }

}

But I have this error when receiving the object:

JSON parse error:  out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `org.json.JSONObject` out of START_ARRAY token

Body:
JSONObject's representation in actual JSON is a hash i.e. {...}. In your json data you're providing an array of hashes [{...}] which is not the same. Judging from your domain I don't think it has to be multiple values, so you can just omit [] in your payload and if it does then the fields in your Java class can be defined as JSONArray.

However, I think you should go with defining an Address class and either using

private Address destinationAddress;
private Address refundAddress;

or if it indeed does have to be an object array

private List<Address> destinationAddresses;
private List<Address> refundAddresses;


问:
NSG rule configuration using powershell – having trouble with importing ASGs
I am in the process or writing a powershell script to configure NSG rules. Most of the rules contain IP addresses as the source but some others source are defined by ASGs. My script works ok if the source is an IP address but throws out an error if the source is an ASG.

The error message is as follows.

Add-AzureRmNetworkSecurityRuleConfig : Cannot bind parameter
  'SourceApplicationSecurityGroup'. Cannot convert the "xxxx-fw-asg"
  value of type "System.String" to type
  "Microsoft.Azure.Commands.Network.Models.PSApplicationSecurityGroup".

As per the error message, the script expects the ASG in a certain data type while actually it is a string.
I could not find a way to convert this string to the type that Powershell expects.
Appreciate any help to convert the data type ( or to resolve this by any other way ).

```<code>$nsgCsv = Import-Csv .\NSG-rule-list.csv

foreach ($rule in $nsgCsv) {
    if ($rule.SourceAddressPrefix) {
        Get-AzureRmNetworkSecurityGroup -Name  $rule.NSG -ResourceGroupName $rule.resourceGroup | Add-AzureRmNetworkSecurityRuleConfig `
            -Name $rule.ruleName `
            -Description $rule.Description `
            -Access $rule.Access `
            -Protocol $rule.Protocol `
            -Direction $rule.Direction `
            -priority $rule.Priority `
            -SourceAddressPrefix ($rule.SourceAddressPrefix -split ',') `
            -SourcePortRange * `
            -DestinationAddressPrefix ($rule.DestinationAddressPrefix -split ',') `
            -DestinationPortRange ($rule.DestinationPortRange -split ',') `
        | Set-AzureRmNetworkSecurityGroup
    }
    else {
        Get-AzureRmNetworkSecurityGroup -Name  $rule.NSG -ResourceGroupName $rule.resourceGroup | Add-AzureRmNetworkSecurityRuleConfig `
            -Name $rule.ruleName `
            -Description $rule.Description `
            -Access $rule.Access `
            -Protocol $rule.Protocol `
            -Direction $rule.Direction `
            -priority $rule.Priority `
            -SourceApplicationSecurityGroup  $rule.sourceASG `
            -SourcePortRange * `
            -DestinationAddressPrefix ($rule.DestinationAddressPrefix -split ',') `
            -DestinationPortRange ($rule.DestinationPortRange -split ',') `
        | Set-AzureRmNetworkSecurityGroup
    }
}
</code>```

Following is the CSV content

```<code>resourceGroup,NSG,ruleName,Description,Protocol,SourcePortRange,DestinationPortRange,SourceAddressPrefix,sourceASG,DestinationAddressPrefix,DestinationASG,Access,Priority,Direction
poc-network-rg,poc-dmz-nsg,Test7,test rule 7,TCP,*,443,,tes-fw-asg,192.168.0.0/24,NA,Allow,609,inbound
</code>```

答:
For the -SourceApplicationSecurityGroup , you need to get the ASG and refer it here.

Sample:

$srcAsg = New-AzureRmApplicationSecurityGroup -ResourceGroupName MyResourceGroup -Name srcAsg -Location "West US"

{

        Get-AzureRmNetworkSecurityGroup -Name  $rule.NSG -ResourceGroupName $rule.resourceGroup | Add-AzureRmNetworkSecurityRuleConfig
            -Name $rule.ruleName
            -Description $rule.Description
            -Access $rule.Access
            -Protocol $rule.Protocol
            -Direction $rule.Direction
            -priority $rule.Priority
            -SourceApplicationSecurityGroup  $srcAsg
            -SourcePortRange *
            -DestinationAddressPrefix ($rule.DestinationAddressPrefix -split ',')
            -DestinationPortRange ($rule.DestinationPortRange -split ',') `
        | Set-AzureRmNetworkSecurityGroup

    }

Body:
I am in the process or writing a powershell script to configure NSG rules. Most of the rules contain IP addresses as the source but some others source are defined by ASGs. My script works ok if the source is an IP address but throws out an error if the source is an ASG.

The error message is as follows.

Add-AzureRmNetworkSecurityRuleConfig : Cannot bind parameter
  'SourceApplicationSecurityGroup'. Cannot convert the "xxxx-fw-asg"
  value of type "System.String" to type
  "Microsoft.Azure.Commands.Network.Models.PSApplicationSecurityGroup".

As per the error message, the script expects the ASG in a certain data type while actually it is a string.
I could not find a way to convert this string to the type that Powershell expects.
Appreciate any help to convert the data type ( or to resolve this by any other way ).

$nsgCsv = Import-Csv .\NSG-rule-list.csv

foreach ($rule in $nsgCsv) {
    if ($rule.SourceAddressPrefix) {
        Get-AzureRmNetworkSecurityGroup -Name  $rule.NSG -ResourceGroupName $rule.resourceGroup | Add-AzureRmNetworkSecurityRuleConfig `
            -Name $rule.ruleName `
            -Description $rule.Description `
            -Access $rule.Access `
            -Protocol $rule.Protocol `
            -Direction $rule.Direction `
            -priority $rule.Priority `
            -SourceAddressPrefix ($rule.SourceAddressPrefix -split ',') `
            -SourcePortRange * `
            -DestinationAddressPrefix ($rule.DestinationAddressPrefix -split ',') `
            -DestinationPortRange ($rule.DestinationPortRange -split ',') `
        | Set-AzureRmNetworkSecurityGroup
    }
    else {
        Get-AzureRmNetworkSecurityGroup -Name  $rule.NSG -ResourceGroupName $rule.resourceGroup | Add-AzureRmNetworkSecurityRuleConfig `
            -Name $rule.ruleName `
            -Description $rule.Description `
            -Access $rule.Access `
            -Protocol $rule.Protocol `
            -Direction $rule.Direction `
            -priority $rule.Priority `
            -SourceApplicationSecurityGroup  $rule.sourceASG `
            -SourcePortRange * `
            -DestinationAddressPrefix ($rule.DestinationAddressPrefix -split ',') `
            -DestinationPortRange ($rule.DestinationPortRange -split ',') `
        | Set-AzureRmNetworkSecurityGroup
    }
}

Following is the CSV content

resourceGroup,NSG,ruleName,Description,Protocol,SourcePortRange,DestinationPortRange,SourceAddressPrefix,sourceASG,DestinationAddressPrefix,DestinationASG,Access,Priority,Direction
poc-network-rg,poc-dmz-nsg,Test7,test rule 7,TCP,*,443,,tes-fw-asg,192.168.0.0/24,NA,Allow,609,inbound


问:
How to remove string between unbalanced brackets in Python3 without Regex?
Good day!

I have a string like  esdfd((esdf)(esdf i want to remove brackets and data if brackets don't close, should be like this --> esdfd((esdf). Also, I can't use regex.

Thank you!

答:
Try this:</p>

```<code>def remove_unbalance(s):
    last_open = s.rfind("(")
    last_close = s.rfind(")")
    return s[:last_open] if last_open > last_close else s

print(remove_unbalance("aaaa(bbbb)(ccccc"))
# aaaa(bbbb)

print(remove_unbalance("esdfd((esdf)(esdf"))
# esdfd((esdf)

print(remove_unbalance("aaaa((bbbb)(ccccc) ddd"))
# aaaa((bbbb)(ccccc) ddd
</code>```

Body:
Try this:

def remove_unbalance(s):
    last_open = s.rfind("(")
    last_close = s.rfind(")")
    return s[:last_open] if last_open > last_close else s

print(remove_unbalance("aaaa(bbbb)(ccccc"))
# aaaa(bbbb)

print(remove_unbalance("esdfd((esdf)(esdf"))
# esdfd((esdf)

print(remove_unbalance("aaaa((bbbb)(ccccc) ddd"))
# aaaa((bbbb)(ccccc) ddd


问:
Extract number as an an integer from a string
I have some data which is badly formatted ( inherited) after some manipulation and some concatenation I have  something resembling the following in a string

"SIGNAGE -- 11 Requires door signage. "

My table has to cross reference a some data from a VLOOKUP and then tries to get the first chars in a pattern after the --

My formula is this

```<code>=IF(VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)<>"",LEFT((RIGHT((VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)), LEN((VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)))-SEARCH("--", (VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)),1)-2)),2),"")
</code>```

This successfully gives me the number 11.

My problem is that the number is being treated as a string and not as a numeric value.

What am I missing?

答: Use NUMBERVALUE() function to convert a string into a number.

Body:
I have some data which is badly formatted ( inherited) after some manipulation and some concatenation I have  something resembling the following in a string

"SIGNAGE -- 11 Requires door signage. "

My table has to cross reference a some data from a VLOOKUP and then tries to get the first chars in a pattern after the --

My formula is this

=IF(VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)<>"",LEFT((RIGHT((VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)), LEN((VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)))-SEARCH("--", (VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)),1)-2)),2),"")

This successfully gives me the number 11.

My problem is that the number is being treated as a string and not as a numeric value.

What am I missing?


问:
How to make a proper MVC Pattern with Javafx and Scene builder
Hi I'm very new to Java and Javafx so I hope you can help me with a problem. I'm trying to do a proper MVC Pattern with Scene Builder but my code doesn't work and I don't know why.

I have understood that the Model class have to get the data and the Controller class should use and handle the data but I have big problems with that the Scene builder does accept one controller class for one FXML file. That is why I tried it with getters and setters to have the connection between Model and Controller.

But also I think I am not doing it right.

Main class:

```<code>package application;

import javafx.application.Application;
import javafx.fxml.*;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application{

    @Override
    public void start(Stage primaryStage) throws Exception{

        try {
        Parent root = FXMLLoader.load(getClass().getResource("/login/LoginUI.fxml"));
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startApp(Stage Stage) throws Exception{

        try {
            Parent root = FXMLLoader.load(getClass().getResource("/financeApp/UI.fxml"));
            Scene scene = new Scene(root, 1022, 593);
            Stage.setScene(scene);
            Stage.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Controller class:

```<code>package login;

import application.Main;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import login.ModelLogin;

public class ControllerLogin {

    @FXML TextField userNameField;
    @FXML PasswordField passwordField;
    @FXML Button loginButton;
    ModelLogin model = new ModelLogin();

    public void setUserName() {
        model.setUserNameField(userNameField);
    }

    public void setPassword() {
        model.setPasswordField(passwordField);
    }

    public void login(ActionEvent event) {
        if (model.getUserNameField().getText().equals("test") && model.getPasswordField().getText().equals("1234")) {
            Stage stage = new Stage();
            Main startUI = new Main();

            try {
                startUI.startApp(stage);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            System.out.println("Try again");
        }
    }
}
</code>```

Model class:

```<code>package login;

import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;

public class ModelLogin {

    private TextField userNameField;
    private PasswordField passwordField;

    public TextField getUserNameField() {
        return userNameField;
    }
    public void setUserNameField(TextField userNameField) {
        this.userNameField = userNameField;
    }
    public PasswordField getPasswordField() {
        return passwordField;
    }
    public void setPasswordField(PasswordField passwordField) {
        this.passwordField = passwordField;
    }

}
</code>```

and this is the FXML file created with Scene builder:

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="290.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="login.ControllerLogin">
   <children>
      <AnchorPane prefHeight="290.0" prefWidth="400.0">
         <children>
            <Label alignment="CENTER" layoutX="150.0" layoutY="38.0" prefHeight="30.0" prefWidth="100.0" text="Login">
               <font>
                  <Font name="System Bold" size="20.0" />
               </font>
            </Label>
            <Label layoutX="159.0" layoutY="108.0" text="Benutzername">
               <font>
                  <Font name="System Bold" size="12.0" />
               </font>
            </Label>
            <TextField fx:id="userNameField" layoutX="126.0" layoutY="125.0" onAction="#setUserName" />
            <Label layoutX="175.0" layoutY="165.0" text="Passwort">
               <font>
                  <Font name="System Bold" size="12.0" />
               </font>
            </Label>
            <PasswordField fx:id="passwordField" layoutX="126.0" layoutY="182.0" onAction="#setPassword" />
            <Button fx:id="loginButton" layoutX="175.0" layoutY="233.0" mnemonicParsing="false" onAction="#login" text="Login" />
         </children>
      </AnchorPane>
   </children>
</VBox>
</code>```

Folders

I would be happy about some Feedback. Thank you!!

答:
All UI elements should be in the view.
A model should have only information and logic that the view and controller use.

```<code>public class ModelLogin {

    private final String userName;
    private final String password;

    ModelLogin(String userName, String password) {

        this.userName = userName;
        this.password = password;
    }

    boolean isCorrectCredentials(String userName, String password){

        return this.userName.equals(userName)&&this.password.equals(password);
    }
}
</code>```

The controller "wires" the view and the model: it handles credential verification and
change of scene.
Note that it is modified to accept a reference of Main so it can change scene:

```<code>import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;

public class ControllerLogin {

    @FXML TextField userNameField;
    @FXML PasswordField passwordField;

    private ModelLogin model;
    private Main main;

    @FXML
    void initialize() {
        model = new ModelLogin("test", "1234");
    }

    public void login(ActionEvent event) {

        if (model.isCorrectCredentials(userNameField.getText(), passwordField.getText() )) {

            try {
                main.startApp();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            System.out.println("Try again");
        }
    }

    void setMain(Main main) {
        this.main = main;
    }
}
</code>```

The text field onAction is not used, so it was removed from the fxml:

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="290.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="login.ControllerLogin">
   <children>
      <AnchorPane prefHeight="290.0" prefWidth="400.0">
         <children>
            <Label alignment="CENTER" layoutX="150.0" layoutY="38.0" prefHeight="30.0" prefWidth="100.0" text="Login">
               <font>
                  <Font name="System Bold" size="20.0" />
               </font>
            </Label>
            <Label layoutX="159.0" layoutY="108.0" text="Benutzername">
               <font>
                  <Font name="System Bold" size="12.0" />
               </font>
            </Label>
            <TextField fx:id="userNameField" layoutX="126.0" layoutY="125.0"/>
            <Label layoutX="175.0" layoutY="165.0" text="Passwort">
               <font>
                  <Font name="System Bold" size="12.0" />
               </font>
            </Label>
            <PasswordField fx:id="passwordField" layoutX="126.0" layoutY="182.0" />
            <Button fx:id="loginButton" layoutX="175.0" layoutY="233.0" mnemonicParsing="false" onAction="#login" text="Login" />
         </children>
      </AnchorPane>
   </children>
</VBox>
</code>```

The Main was modified to get a reference to the controller, and to change scene:

```<code>import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application{

    private Stage primaryStage;
    private Parent root;

    @Override
    public void start(Stage primaryStage) throws Exception{

        try {

            this.primaryStage = primaryStage;
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/login/LoginUI.fxml"));
            root = loader.load();
            ControllerLogin controller = loader.getController();
            controller.setMain(this);

            Scene scene = new Scene(root, 400, 400);
            primaryStage.setScene(scene);
            primaryStage.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startApp() throws Exception{

        try {
            root = FXMLLoader.load(getClass().getResource("/financeApp/UI.fxml"));
            Scene scene = new Scene(root, 1022, 593);
            primaryStage.setScene(scene);
            primaryStage.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Body:
Hi I'm very new to Java and Javafx so I hope you can help me with a problem. I'm trying to do a proper MVC Pattern with Scene Builder but my code doesn't work and I don't know why.

I have understood that the Model class have to get the data and the Controller class should use and handle the data but I have big problems with that the Scene builder does accept one controller class for one FXML file. That is why I tried it with getters and setters to have the connection between Model and Controller.

But also I think I am not doing it right.

Main class:

package application;

import javafx.application.Application;
import javafx.fxml.*;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application{

    @Override
    public void start(Stage primaryStage) throws Exception{

        try {
        Parent root = FXMLLoader.load(getClass().getResource("/login/LoginUI.fxml"));
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startApp(Stage Stage) throws Exception{

        try {
            Parent root = FXMLLoader.load(getClass().getResource("/financeApp/UI.fxml"));
            Scene scene = new Scene(root, 1022, 593);
            Stage.setScene(scene);
            Stage.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

Controller class:

package login;

import application.Main;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import login.ModelLogin;

public class ControllerLogin {

    @FXML TextField userNameField;
    @FXML PasswordField passwordField;
    @FXML Button loginButton;
    ModelLogin model = new ModelLogin();

    public void setUserName() {
        model.setUserNameField(userNameField);
    }

    public void setPassword() {
        model.setPasswordField(passwordField);
    }

    public void login(ActionEvent event) {
        if (model.getUserNameField().getText().equals("test") && model.getPasswordField().getText().equals("1234")) {
            Stage stage = new Stage();
            Main startUI = new Main();

            try {
                startUI.startApp(stage);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            System.out.println("Try again");
        }
    }
}

Model class:

package login;

import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;

public class ModelLogin {

    private TextField userNameField;
    private PasswordField passwordField;

    public TextField getUserNameField() {
        return userNameField;
    }
    public void setUserNameField(TextField userNameField) {
        this.userNameField = userNameField;
    }
    public PasswordField getPasswordField() {
        return passwordField;
    }
    public void setPasswordField(PasswordField passwordField) {
        this.passwordField = passwordField;
    }

}

and this is the FXML file created with Scene builder:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="290.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="login.ControllerLogin">
   <children>
      <AnchorPane prefHeight="290.0" prefWidth="400.0">
         <children>

            <TextField fx:id="userNameField" layoutX="126.0" layoutY="125.0" onAction="#setUserName" />

            <PasswordField fx:id="passwordField" layoutX="126.0" layoutY="182.0" onAction="#setPassword" />
            <Button fx:id="loginButton" layoutX="175.0" layoutY="233.0" mnemonicParsing="false" onAction="#login" text="Login" />
         </children>
      </AnchorPane>
   </children>
</VBox>

Folders

I would be happy about some Feedback. Thank you!!

Body:
All UI elements should be in the view.
A model should have only information and logic that the view and controller use.

public class ModelLogin {

    private final String userName;
    private final String password;

    ModelLogin(String userName, String password) {

        this.userName = userName;
        this.password = password;
    }

    boolean isCorrectCredentials(String userName, String password){

        return this.userName.equals(userName)&&this.password.equals(password);
    }
}

The controller "wires" the view and the model: it handles credential verification and
change of scene.
Note that it is modified to accept a reference of Main so it can change scene:

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;

public class ControllerLogin {

    @FXML TextField userNameField;
    @FXML PasswordField passwordField;

    private ModelLogin model;
    private Main main;

    @FXML
    void initialize() {
        model = new ModelLogin("test", "1234");
    }

    public void login(ActionEvent event) {

        if (model.isCorrectCredentials(userNameField.getText(), passwordField.getText() )) {

            try {
                main.startApp();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            System.out.println("Try again");
        }
    }

    void setMain(Main main) {
        this.main = main;
    }
}

The text field onAction is not used, so it was removed from the fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="290.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="login.ControllerLogin">
   <children>
      <AnchorPane prefHeight="290.0" prefWidth="400.0">
         <children>
            <Label alignment="CENTER" layoutX="150.0" layoutY="38.0" prefHeight="30.0" prefWidth="100.0" text="Login">
               <font>
                  <Font name="System Bold" size="20.0" />
               </font>
            </Label>
            <Label layoutX="159.0" layoutY="108.0" text="Benutzername">
               <font>
                  <Font name="System Bold" size="12.0" />
               </font>
            </Label>
            <TextField fx:id="userNameField" layoutX="126.0" layoutY="125.0"/>
            <Label layoutX="175.0" layoutY="165.0" text="Passwort">
               <font>
                  <Font name="System Bold" size="12.0" />
               </font>
            </Label>
            <PasswordField fx:id="passwordField" layoutX="126.0" layoutY="182.0" />
            <Button fx:id="loginButton" layoutX="175.0" layoutY="233.0" mnemonicParsing="false" onAction="#login" text="Login" />
         </children>
      </AnchorPane>
   </children>
</VBox>

The Main was modified to get a reference to the controller, and to change scene:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application{

    private Stage primaryStage;
    private Parent root;

    @Override
    public void start(Stage primaryStage) throws Exception{

        try {

            this.primaryStage = primaryStage;
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/login/LoginUI.fxml"));
            root = loader.load();
            ControllerLogin controller = loader.getController();
            controller.setMain(this);

            Scene scene = new Scene(root, 400, 400);
            primaryStage.setScene(scene);
            primaryStage.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startApp() throws Exception{

        try {
            root = FXMLLoader.load(getClass().getResource("/financeApp/UI.fxml"));
            Scene scene = new Scene(root, 1022, 593);
            primaryStage.setScene(scene);
            primaryStage.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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


问:
How to show count on "PWA web application icon" through JavaScript?
How to show count on "PWA web application icon" through JavaScript?

I have implemented FCM push notification already in system but does not know how to show count for launcher icon in PWA web app

答:
Currently badge's notifications are not possible in PWA's but they'll be available in the future. Google has already an experimental API for it.
You can get further info in Is there a way to add badge notifications using progressive web apps (PWA)?</p>


问:
Previous period calculation in Azure Data Explorer\Kusto
We are building a report in Power BI on data sitting in Azure Data Explore r.Because we need the report to be fully dynamic we cannot pre-write the queries but must rely on Power BI to generate the queries for Data Explorer according to the user actions on the report.

One of our requirements is to show several measures compared to their value on previous period (month). The measure must also be very dynamic and so the correct value must be based on the user filters and actions and can't be pre-calculated.

We added a calculated measure in Power BI:

```<code>Prev_Month_Amt=CALCULATE(SUM(sales[Amt]),DATEADD(dates[Record_DT],-1,MONTH))
</code>```

The dates table contains one row per day and is linked to the sales table in Power BI using Many-to-one relationship. The sales table includes several hundred millions records.

The problem is that when we add the Prev_Month_Amt measure to a Power BI object like Matrix we encountered very long run times and quite often "ge  Accumulated string array getting too large" errors.

Is there a better way to build previous period calcualtions in Power BI based on Azure Data Explorer?

Thanks,
H.G.

答:
You can add the previous month amount column to the Kusto table presented to PBI (either by adding it to a real table using update policy or Microsoft flow, or by extending it in a stored function). The PBI will see it as a regular column, here is an example:</p>

```<code>let T = datatable(Amount:double, Day:datetime, LineItem:string, Account:string)
[2, datetime(2019-01-03), "revenue", "a",
2, datetime(2019-01-05), "revenue", "a",
5, datetime(2019-01-03), "revenue", "b",
5, datetime(2019-01-05), "revenue", "b",
10, datetime(2019-02-07), "revenue", "a",
2, datetime(2019-02-10), "revenue", "a",
3, datetime(2019-02-10), "revenue", "b",
4, datetime(2019-02-10), "revenue", "b"
];
T
| extend Month = startofmonth(Day)
| summarize Amount = sum(Amount) by Month, LineItem, Account
| join kind=leftouter
 (
    T
    | extend Month = startofmonth(endofmonth(Day) + 1d) // sets the current month to the next month
    | summarize LastMonthAmount= sum(Amount) by Month, LineItem,  Account
) on Month, LineItem, Account
| project Month, LineItem,  Account, Amount, LastMonthAmount
</code>```

Body:
We are building a report in Power BI on data sitting in Azure Data Explore r.Because we need the report to be fully dynamic we cannot pre-write the queries but must rely on Power BI to generate the queries for Data Explorer according to the user actions on the report.

One of our requirements is to show several measures compared to their value on previous period (month). The measure must also be very dynamic and so the correct value must be based on the user filters and actions and can't be pre-calculated.

We added a calculated measure in Power BI:

Prev_Month_Amt=CALCULATE(SUM(sales[Amt]),DATEADD(dates[Record_DT],-1,MONTH))

The dates table contains one row per day and is linked to the sales table in Power BI using Many-to-one relationship. The sales table includes several hundred millions records.

The problem is that when we add the Prev_Month_Amt measure to a Power BI object like Matrix we encountered very long run times and quite often "ge  Accumulated string array getting too large" errors.

Is there a better way to build previous period calcualtions in Power BI based on Azure Data Explorer?

Thanks,
H.G.

Body:
You can add the previous month amount column to the Kusto table presented to PBI (either by adding it to a real table using update policy or Microsoft flow, or by extending it in a stored function). The PBI will see it as a regular column, here is an example:

let T = datatable(Amount:double, Day:datetime, LineItem:string, Account:string)
[2, datetime(2019-01-03), "revenue", "a",
2, datetime(2019-01-05), "revenue", "a",
5, datetime(2019-01-03), "revenue", "b",
5, datetime(2019-01-05), "revenue", "b",
10, datetime(2019-02-07), "revenue", "a",
2, datetime(2019-02-10), "revenue", "a",
3, datetime(2019-02-10), "revenue", "b",
4, datetime(2019-02-10), "revenue", "b"
];
T
| extend Month = startofmonth(Day)
| summarize Amount = sum(Amount) by Month, LineItem, Account
| join kind=leftouter
 (
    T
    | extend Month = startofmonth(endofmonth(Day) + 1d) // sets the current month to the next month
    | summarize LastMonthAmount= sum(Amount) by Month, LineItem,  Account
) on Month, LineItem, Account
| project Month, LineItem,  Account, Amount, LastMonthAmount


问:
How do I add a square button with a '+' on it to uinavigationbar?
Like the right button shown in this image.
http://i.stack.imgur.com/D2Q61.jpg
Is it a default button provided by apple?
If yes then how do I add it to the navigationBar?</p>

答:
Yes, that [+] button is a default button, provided by Apple. It is the UIBarButtonSystemItemAdd identifier.

Here's some code to get it working:

```<code>// Create the Add button

UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(someMethod)];

// Display it

self.navigationItem.rightBarButtonItem = addButton;

//  Release the button

[addButton release];
</code>```

You will need to define someMethod, so your program has code to run when the button is tapped.

Body:
Yes, that [+] button is a default button, provided by Apple. It is the UIBarButtonSystemItemAdd identifier.

Here's some code to get it working:

// Create the Add button

UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(someMethod)];

// Display it

self.navigationItem.rightBarButtonItem = addButton;

//  Release the button

[addButton release];

You will need to define someMethod, so your program has code to run when the button is tapped.


问:
Is hashinfo equivalent to peer ID in Mainline DHT?
I am working on Mainline DHT and I don't understand one nuance.

Here: https://www.bittorrent.org/beps/bep_0005.html writes: "A "distance metric" is used to compare two node IDs or a node ID and an info hash for "closeness."

Also writes: "Announce that the peer, controlling the querying node, is downloading a torrent on a port. announce_peer has four arguments: "id" containing the node ID of the querying node, "info_hash" containing the info hash of the torrent, "port" containing the port as an integer, and the "token" received in response to a previous get_peers query."

So, for example, we have a peer with ID 223456789zxcvbnmasdf which IP is 86.23.145.714 and port is: 7853
I know that this peer downloaded 2 torrent files with info hashes: 023456789zxcvbnmasdf and 123456789zxcvbnmasdf.

So how exactly my k-bucket record should look like?
Like this:

```<code>{"id": "223456789zxcvbnmasdf", "ip": "86.23.145.714", "port": "7853", "torrents": ["023456789zxcvbnmasdg", "123456789zxcvbnmasdh"]} ?
</code>```

Or should torrent files be like an "equivalent" record (with duplicated ips and ports) in k-buckets along with peer:

```<code>{"id": "223456789zxcvbnmasdf", "ip": "86.23.145.714", "port": "7853"},

{"id": "023456789zxcvbnmasdg", "ip": "86.23.145.714", "port": "7853"},

{"id": "123456789zxcvbnmasdh", "ip": "86.23.145.714", "port": "7853"} ?
</code>```

I am asking because this is not just implementation nuance. Because "k" is normally 20 or some other integer in all clients. So if I would use k-buckets to store torrent files as full-right members, I would have less space to store real peers data.

Thanks for answers!

答:
k-buckets datastructure is an implementation detail of bit-torrent protocol so that peers reply quickly enough to FIND_PEERS and FIND_VALUE.

What I do in my kademlia implementation is that keep the the routing table in a python dictionary and I compute the nearest peers under the 5 seconds by default which is the timeout I use to wait for a UDP reply. To achieve that I need to keep the routing table below 1 000 000 entries.

Like I said above, the routing table is a simple python dict that maps peerid to (address, port).

The routing table stores peers not values ie. not infohash addresses.

When I receive a FIND_PEERS message, the program replies with the following code:

```<code>async def peers(self, address, uid):
    """Remote procedure that returns peers that are near UID"""
    log.debug("[%r] find peers uid=%r from %r", self._uid, uid, address)
    # XXX: if this takes more than 5 seconds (see RPCProtocol) it
    # will timeout in the other side.
    uids = nearest(self._replication, self._peers.keys(), uid)
    out = [self._peers[x] for x in uids]
    return out
</code>```

When I receive a FIND_VALUE message, the program replies with the following code:

```<code>async def value(self, address, key):
    """Remote procedure that returns the associated value or peers that
    are near KEY"""
    log.debug("[%r] value key=%r from %r", self._uid, key, address)
    out = await lookup(key)
    if out is None:
        # value is not found, reply with peers that are near KEY
        out = nearest(self._replication, self._peers.keys(), uid)
        return (b"PEERS", out)
    else:
        return (b"VALUE", out)
</code>```

Here is the definition of nearest:

```<code>def nearest(k, peers, uid):
    """Return K nearest to to UID peers in PEERS according to XOR"""
    # XXX: It only works with len(peers) < 10^6 more than that count
    # of peers and the time it takes to compute the nearest peers will
    # timeout after 5 seconds on the other side. See RPCProtocol and
    # Peer.peers.
    return nsmallest(k, peers, key=functools.partial(operator.xor, uid))
</code>```

That is it sorts the peers according to their peerid and return the k smallest. nsmallest is supposed to be an optimized version of sort(peers, key=functools.partial(operator.xor, uid))[:k] where uid is a peerid or infohash (respectively FIND_PEERS and FIND_VALUE).

Now back at your question(s):

Is hashinfo equivalent to peer ID in Mainline DHT?

hashinfo is a hash-something that is the same kind of hash as peerid ie. they are possible keys in the routing table. That is, torrent files are associated with a hash, peers are associated with the same kind of hash called peerid. And peers have the "ownership" of keys that near their peerid. BUT hashinfo are not stored in the routing table or k-buckets if you prefer. hashinfo are stored in another mapping that associate hashinfo hash with their value(s).

I am asking because this is not just implementation nuance. Because "k" is normally 20 or some other integer in all clients. So if I would use k-buckets to store torrent files as full-right members, I would have less space to store real peers data.

There is mis-understanding here about the same thing I try explain above. hashinfo are keys in storage dictionary. Whereas peerid are keys in the routing table aka. k-buckets datastructure. They both have the same format because that is how the kademlia routing algorithm work. You must be able to compare hashinfo with peerid with xor to be able to tell which peers "own" which hashinfo value.

As you can see in the second snippet, when a another peer ask for a value associated with an hash, it calls lookup(key) that is something like storage.get(key) except in my case the code stores values in a database.

Maybe there is a mis-understanding about the fact that k-buckets are used to store DHT routing information. And that on top of that, torrent protocol use the DHT to store torrent routing information.

For what it is worth, qadom's peer.py file is where I implement a DHT inspired from kademlia (except I use 256 bits hash and forgo alpha and k parameters and use a single REPLICATION parameter). The code works most of the  time check the tests.

Also, there is another project I got inspiration from called simply kademlia that (try to?) implement k-buckets.

As far as I understand, torrent DHT routing looks like qadom bag functions except the receiving peer must authenticate the announcement, whereas in qadom bags are free-for-all.

Also, check the original kademlia paper.

Body:
I am working on Mainline DHT and I don't understand one nuance.

Here: https://www.bittorrent.org/beps/bep_0005.html writes: "A "distance metric" is used to compare two node IDs or a node ID and an info hash for "closeness."

Also writes: "Announce that the peer, controlling the querying node, is downloading a torrent on a port. announce_peer has four arguments: "id" containing the node ID of the querying node, "info_hash" containing the info hash of the torrent, "port" containing the port as an integer, and the "token" received in response to a previous get_peers query."

So, for example, we have a peer with ID 223456789zxcvbnmasdf which IP is 86.23.145.714 and port is: 7853
I know that this peer downloaded 2 torrent files with info hashes: 023456789zxcvbnmasdf and 123456789zxcvbnmasdf.

So how exactly my k-bucket record should look like?
Like this:

{"id": "223456789zxcvbnmasdf", "ip": "86.23.145.714", "port": "7853", "torrents": ["023456789zxcvbnmasdg", "123456789zxcvbnmasdh"]} ?

Or should torrent files be like an "equivalent" record (with duplicated ips and ports) in k-buckets along with peer:

{"id": "223456789zxcvbnmasdf", "ip": "86.23.145.714", "port": "7853"},

{"id": "023456789zxcvbnmasdg", "ip": "86.23.145.714", "port": "7853"},

{"id": "123456789zxcvbnmasdh", "ip": "86.23.145.714", "port": "7853"} ?

I am asking because this is not just implementation nuance. Because "k" is normally 20 or some other integer in all clients. So if I would use k-buckets to store torrent files as full-right members, I would have less space to store real peers data.

Thanks for answers!

Body:
k-buckets datastructure is an implementation detail of bit-torrent protocol so that peers reply quickly enough to FIND_PEERS and FIND_VALUE.

What I do in my kademlia implementation is that keep the the routing table in a python dictionary and I compute the nearest peers under the 5 seconds by default which is the timeout I use to wait for a UDP reply. To achieve that I need to keep the routing table below 1 000 000 entries.

Like I said above, the routing table is a simple python dict that maps peerid to (address, port).

The routing table stores peers not values ie. not infohash addresses.

When I receive a FIND_PEERS message, the program replies with the following code:

async def peers(self, address, uid):
    """Remote procedure that returns peers that are near UID"""
    log.debug("[%r] find peers uid=%r from %r", self._uid, uid, address)
    # XXX: if this takes more than 5 seconds (see RPCProtocol) it
    # will timeout in the other side.
    uids = nearest(self._replication, self._peers.keys(), uid)
    out = [self._peers[x] for x in uids]
    return out

When I receive a FIND_VALUE message, the program replies with the following code:

async def value(self, address, key):
    """Remote procedure that returns the associated value or peers that
    are near KEY"""
    log.debug("[%r] value key=%r from %r", self._uid, key, address)
    out = await lookup(key)
    if out is None:
        # value is not found, reply with peers that are near KEY
        out = nearest(self._replication, self._peers.keys(), uid)
        return (b"PEERS", out)
    else:
        return (b"VALUE", out)

Here is the definition of nearest:

def nearest(k, peers, uid):
    """Return K nearest to to UID peers in PEERS according to XOR"""
    # XXX: It only works with len(peers) < 10^6 more than that count
    # of peers and the time it takes to compute the nearest peers will
    # timeout after 5 seconds on the other side. See RPCProtocol and
    # Peer.peers.
    return nsmallest(k, peers, key=functools.partial(operator.xor, uid))

That is it sorts the peers according to their peerid and return the k smallest. nsmallest is supposed to be an optimized version of sort(peers, key=functools.partial(operator.xor, uid))[:k] where uid is a peerid or infohash (respectively FIND_PEERS and FIND_VALUE).

Now back at your question(s):

Is hashinfo equivalent to peer ID in Mainline DHT?

hashinfo is a hash-something that is the same kind of hash as peerid ie. they are possible keys in the routing table. That is, torrent files are associated with a hash, peers are associated with the same kind of hash called peerid. And peers have the "ownership" of keys that near their peerid. BUT hashinfo are not stored in the routing table or k-buckets if you prefer. hashinfo are stored in another mapping that associate hashinfo hash with their value(s).

I am asking because this is not just implementation nuance. Because "k" is normally 20 or some other integer in all clients. So if I would use k-buckets to store torrent files as full-right members, I would have less space to store real peers data.

There is mis-understanding here about the same thing I try explain above. hashinfo are keys in storage dictionary. Whereas peerid are keys in the routing table aka. k-buckets datastructure. They both have the same format because that is how the kademlia routing algorithm work. You must be able to compare hashinfo with peerid with xor to be able to tell which peers "own" which hashinfo value.

As you can see in the second snippet, when a another peer ask for a value associated with an hash, it calls lookup(key) that is something like storage.get(key) except in my case the code stores values in a database.

Maybe there is a mis-understanding about the fact that k-buckets are used to store DHT routing information. And that on top of that, torrent protocol use the DHT to store torrent routing information.

For what it is worth, qadom's peer.py file is where I implement a DHT inspired from kademlia (except I use 256 bits hash and forgo alpha and k parameters and use a single REPLICATION parameter). The code works most of the  time check the tests.

Also, there is another project I got inspiration from called simply kademlia that (try to?) implement k-buckets.

As far as I understand, torrent DHT routing looks like qadom bag functions except the receiving peer must authenticate the announcement, whereas in qadom bags are free-for-all.

Also, check the original kademlia paper.


问:
Using Win32::Env perl module, environment variable not setting permanently in windows
Win32::Env module is used for environment variable set for temporary basis.
I need to set permanently, please help

Please help me to set as permanent .
Because i want it use in another exe.

```<code>use Win32::Env;

SetEnv(ENV_USER, 'AUTO_EXCEL_EXPORT', 'TRUE');
</code>```

By this code, i can set environment variable in windows only as temporary.
when i check with echo command of that variable it is not showing.
because it is set as semi permanent value.

答:
When assigning/changing environment variables in Windows, the Explorer subsystem needs to be notified that the changes occurred before newly opened windows/applications see the changes. If this doesn't happen, then a reboot is necessary before other processes will see the changes.

As you can see in the SYNOPSIS of Win32::Env, they've got a call to BroadcastEnv() which performs said notification task.

After reviewing the module's code, the author is setting the variables within the registry, so that call should correct the issue. Note though, that if you're running things from a cmd window while running your script, no matter what, you have to close that window and open a new one for the changes to take effect. All new windows should get the updated environment.

Example:

```<code>use Win32::Env;

SetEnv(ENV_USER, 'AUTO_EXCEL_EXPORT', 'TRUE');

BroadcastEnv();
</code>```

Body:
Win32::Env module is used for environment variable set for temporary basis.
I need to set permanently, please help

Please help me to set as permanent .
Because i want it use in another exe.

use Win32::Env;

SetEnv(ENV_USER, 'AUTO_EXCEL_EXPORT', 'TRUE');

By this code, i can set environment variable in windows only as temporary.
when i check with echo command of that variable it is not showing.
because it is set as semi permanent value.

Body:
When assigning/changing environment variables in Windows, the Explorer subsystem needs to be notified that the changes occurred before newly opened windows/applications see the changes. If this doesn't happen, then a reboot is necessary before other processes will see the changes.

As you can see in the SYNOPSIS of Win32::Env, they've got a call to BroadcastEnv() which performs said notification task.

After reviewing the module's code, the author is setting the variables within the registry, so that call should correct the issue. Note though, that if you're running things from a cmd window while running your script, no matter what, you have to close that window and open a new one for the changes to take effect. All new windows should get the updated environment.

Example:

use Win32::Env;

SetEnv(ENV_USER, 'AUTO_EXCEL_EXPORT', 'TRUE');

BroadcastEnv();


问:
Position information transmission from one device to the other
I need to transmit GPS position information from one device to another but passing through my database to store the information. Something like Uber does when they show you the position of a vehicle. I was wondering what the best means of doing this would be in Android. I was thinking about firebase to transmit notifications and use the payload to transmit this data but I am not sure if this is the correct way of doing it. I see there is also a real time database in firebase which syncs information across all connected devices. Could this be a solution?</p>

答: Firebase will do the job. Connect two apps to firebase project - from app A write location, from app B red location with onChildChange listener.</p>


问:
Minikube is slow and unresponsive
Today randomly minikube seems to be taking very long to respond to command via kubectl.

And occasionally even:

```<code>kubectl get pods
Unable to connect to the server: net/http: TLS handshake timeout
</code>```

How can I diagnose this?

Some logs from minikube logs:

```<code>==> kube-scheduler <==
I0527 14:16:55.809859       1 serving.go:319] Generated self-signed cert in-memory
W0527 14:16:56.256478       1 authentication.go:387] failed to read in-cluster kubeconfig for delegated authentication: open /var/run/secrets/kubernetes.io/serviceaccount/token: no such file or directory
W0527 14:16:56.256856       1 authentication.go:249] No authentication-kubeconfig provided in order to lookup client-ca-file in configmap/extension-apiserver-authentication in kube-system, so client certificate authentication won't work.
W0527 14:16:56.257077       1 authentication.go:252] No authentication-kubeconfig provided in order to lookup requestheader-client-ca-file in configmap/extension-apiserver-authentication in kube-system, so request-header client certificate authentication won't work.
W0527 14:16:56.257189       1 authorization.go:177] failed to read in-cluster kubeconfig for delegated authorization: open /var/run/secrets/kubernetes.io/serviceaccount/token: no such file or directory
W0527 14:16:56.257307       1 authorization.go:146] No authorization-kubeconfig provided, so SubjectAccessReview of authorization tokens won't work.
I0527 14:16:56.264875       1 server.go:142] Version: v1.14.1
I0527 14:16:56.265228       1 defaults.go:87] TaintNodesByCondition is enabled, PodToleratesNodeTaints predicate is mandatory
W0527 14:16:56.286959       1 authorization.go:47] Authorization is disabled
W0527 14:16:56.286982       1 authentication.go:55] Authentication is disabled
I0527 14:16:56.286995       1 deprecated_insecure_serving.go:49] Serving healthz insecurely on [::]:10251
I0527 14:16:56.287397       1 secure_serving.go:116] Serving securely on 127.0.0.1:10259
I0527 14:16:57.417028       1 controller_utils.go:1027] Waiting for caches to sync for scheduler controller
I0527 14:16:57.524378       1 controller_utils.go:1034] Caches are synced for scheduler controller
I0527 14:16:57.827438       1 leaderelection.go:217] attempting to acquire leader lease  kube-system/kube-scheduler...
E0527 14:17:10.865448       1 leaderelection.go:306] error retrieving resource lock kube-system/kube-scheduler: Get https://localhost:8443/api/v1/namespaces/kube-system/endpoints/kube-scheduler?timeout=10s: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
E0527 14:17:43.418910       1 leaderelection.go:306] error retrieving resource lock kube-system/kube-scheduler: Get https://localhost:8443/api/v1/namespaces/kube-system/endpoints/kube-scheduler?timeout=10s: context deadline exceeded (Client.Timeout exceeded while awaiting headers)
I0527 14:18:01.447065       1 leaderelection.go:227] successfully acquired lease kube-system/kube-scheduler
I0527 14:18:29.044544       1 leaderelection.go:263] failed to renew lease kube-system/kube-scheduler: failed to tryAcquireOrRenew context deadline exceeded
E0527 14:18:38.999295       1 server.go:252] lost master
E0527 14:18:39.204637       1 leaderelection.go:306] error retrieving resource lock kube-system/kube-scheduler: Get https://localhost:8443/api/v1/namespaces/kube-system/endpoints/kube-scheduler?timeout=10s: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
lost lease
</code>```

Update:
To work around this issue I just did a minikube delete and minikube start, and the performance issue resolved..

答:
As solution has been found, I am posting this as Community Wiki for future users.

1) Debugging issues with minikube by adding -v flag and set debug level (0, 1, 2, 3, 7).

As example: minikube start --v=1 to set outbut to INFO level.

More detailed information here

2) Use logs command minikube logs

3) Because Minikube is working on Virtual Machine sometimes is better to delete minikube and start it again (It helped in this case).

```<code>minikube delete
minikube start
</code>```

4) It might get slow due to lack of resources.

Minikube as default is using 2048MB of memory and 2 CPUs. More details about this can be fund here
In addition, you can enforce Minikube to create more using command

```<code>minikube start --cpus 4 --memory 8192
</code>```

Title: Minikube is slow and unresponsive

Body:
Today randomly minikube seems to be taking very long to respond to command via kubectl.

And occasionally even:

kubectl get pods
Unable to connect to the server: net/http: TLS handshake timeout

How can I diagnose this?

Some logs from minikube logs:

==> kube-scheduler <==
I0527 14:16:55.809859       1 serving.go:319] Generated self-signed cert in-memory
W0527 14:16:56.256478       1 authentication.go:387] failed to read in-cluster kubeconfig for delegated authentication: open /var/run/secrets/kubernetes.io/serviceaccount/token: no such file or directory
W0527 14:16:56.256856       1 authentication.go:249] No authentication-kubeconfig provided in order to lookup client-ca-file in configmap/extension-apiserver-authentication in kube-system, so client certificate authentication won't work.
W0527 14:16:56.257077       1 authentication.go:252] No authentication-kubeconfig provided in order to lookup requestheader-client-ca-file in configmap/extension-apiserver-authentication in kube-system, so request-header client certificate authentication won't work.
W0527 14:16:56.257189       1 authorization.go:177] failed to read in-cluster kubeconfig for delegated authorization: open /var/run/secrets/kubernetes.io/serviceaccount/token: no such file or directory
W0527 14:16:56.257307       1 authorization.go:146] No authorization-kubeconfig provided, so SubjectAccessReview of authorization tokens won't work.
I0527 14:16:56.264875       1 server.go:142] Version: v1.14.1
I0527 14:16:56.265228       1 defaults.go:87] TaintNodesByCondition is enabled, PodToleratesNodeTaints predicate is mandatory
W0527 14:16:56.286959       1 authorization.go:47] Authorization is disabled
W0527 14:16:56.286982       1 authentication.go:55] Authentication is disabled
I0527 14:16:56.286995       1 deprecated_insecure_serving.go:49] Serving healthz insecurely on [::]:10251
I0527 14:16:56.287397       1 secure_serving.go:116] Serving securely on 127.0.0.1:10259
I0527 14:16:57.417028       1 controller_utils.go:1027] Waiting for caches to sync for scheduler controller
I0527 14:16:57.524378       1 controller_utils.go:1034] Caches are synced for scheduler controller
I0527 14:16:57.827438       1 leaderelection.go:217] attempting to acquire leader lease  kube-system/kube-scheduler...
E0527 14:17:10.865448       1 leaderelection.go:306] error retrieving resource lock kube-system/kube-scheduler: Get https://localhost:8443/api/v1/namespaces/kube-system/endpoints/kube-scheduler?timeout=10s: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
E0527 14:17:43.418910       1 leaderelection.go:306] error retrieving resource lock kube-system/kube-scheduler: Get https://localhost:8443/api/v1/namespaces/kube-system/endpoints/kube-scheduler?timeout=10s: context deadline exceeded (Client.Timeout exceeded while awaiting headers)
I0527 14:18:01.447065       1 leaderelection.go:227] successfully acquired lease kube-system/kube-scheduler
I0527 14:18:29.044544       1 leaderelection.go:263] failed to renew lease kube-system/kube-scheduler: failed to tryAcquireOrRenew context deadline exceeded
E0527 14:18:38.999295       1 server.go:252] lost master
E0527 14:18:39.204637       1 leaderelection.go:306] error retrieving resource lock kube-system/kube-scheduler: Get https://localhost:8443/api/v1/namespaces/kube-system/endpoints/kube-scheduler?timeout=10s: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
lost lease

Update:
To work around this issue I just did a minikube delete and minikube start, and the performance issue resolved..

Body:
As solution has been found, I am posting this as Community Wiki for future users.

1) Debugging issues with minikube by adding -v flag and set debug level (0, 1, 2, 3, 7).

As example: minikube start --v=1 to set outbut to INFO level.

More detailed information here

2) Use logs command minikube logs

3) Because Minikube is working on Virtual Machine sometimes is better to delete minikube and start it again (It helped in this case).

minikube delete
minikube start

4) It might get slow due to lack of resources.

Minikube as default is using 2048MB of memory and 2 CPUs. More details about this can be fund here
In addition, you can enforce Minikube to create more using command

minikube start --cpus 4 --memory 8192